@stackwright-pro/mcp 0.2.0-alpha.2 → 0.2.0-alpha.21

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,9 +268,9 @@ 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");
@@ -291,7 +324,7 @@ SHA-256 computed: ${sha256}`
291
324
  "stackwright_pro_list_approved_specs",
292
325
  "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
326
  {
294
- configPath: z2.string().optional().describe("Path to stackwright.yml")
327
+ configPath: z3.string().optional().describe("Path to stackwright.yml")
295
328
  },
296
329
  async ({ configPath }) => {
297
330
  const configFile = configPath || path.join(process.cwd(), "stackwright.yml");
@@ -360,16 +393,18 @@ SHA-256 computed: ${sha256}`
360
393
  }
361
394
 
362
395
  // src/tools/isr.ts
363
- import { z as z3 } from "zod";
396
+ import { z as z4 } from "zod";
364
397
  function registerIsrTools(server2) {
365
398
  server2.tool(
366
399
  "stackwright_pro_configure_isr",
367
400
  "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
401
  {
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")
402
+ collection: z4.string().describe('Collection name (e.g., "equipment", "supplies")'),
403
+ revalidateSeconds: numCoerce(z4.number().optional()).describe(
404
+ "Revalidation interval in seconds (default: 60)"
405
+ ),
406
+ fallback: z4.enum(["blocking", "true", "false"]).optional().describe("Fallback behavior for new pages"),
407
+ configPath: z4.string().optional().describe("Path to stackwright.yml")
373
408
  },
374
409
  async ({ collection, revalidateSeconds = 60, fallback = "blocking", configPath }) => {
375
410
  const revalidate = revalidateSeconds;
@@ -412,14 +447,16 @@ ${yamlSnippet}
412
447
  "stackwright_pro_configure_isr_batch",
413
448
  "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
449
  {
415
- collections: z3.array(
416
- z3.object({
417
- name: z3.string().describe("Collection name"),
418
- revalidateSeconds: z3.number().optional().describe("Revalidation interval")
419
- })
450
+ collections: jsonCoerce(
451
+ z4.array(
452
+ z4.object({
453
+ name: z4.string().describe("Collection name"),
454
+ revalidateSeconds: numCoerce(z4.number().optional()).describe("Revalidation interval")
455
+ })
456
+ )
420
457
  ).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")
458
+ defaultFallback: z4.enum(["blocking", "true", "false"]).optional().describe("Default fallback behavior"),
459
+ configPath: z4.string().optional().describe("Path to stackwright.yml")
423
460
  },
424
461
  async ({ collections, defaultFallback = "blocking", configPath }) => {
425
462
  const lines = [`\u2699\uFE0F Batch ISR Configuration:
@@ -447,17 +484,17 @@ Fallback: ${defaultFallback}`);
447
484
  }
448
485
 
449
486
  // src/tools/dashboard.ts
450
- import { z as z4 } from "zod";
487
+ import { z as z5 } from "zod";
451
488
  import { listEntities as listEntities2 } from "@stackwright-pro/cli-data-explorer";
452
489
  function registerDashboardTools(server2) {
453
490
  server2.tool(
454
491
  "stackwright_pro_generate_dashboard",
455
492
  "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
493
  {
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")
494
+ entities: jsonCoerce(z5.array(z5.string())).describe("Entity slugs to include in dashboard"),
495
+ layout: z5.enum(["grid", "table", "mixed"]).optional().describe("Dashboard layout style"),
496
+ pageTitle: z5.string().optional().describe("Page title"),
497
+ specPath: z5.string().optional().describe("Path to OpenAPI spec for entity details")
461
498
  },
462
499
  async ({ entities, layout = "mixed", pageTitle, specPath }) => {
463
500
  let entityDetails = [];
@@ -543,9 +580,9 @@ ${yaml}
543
580
  "stackwright_pro_generate_detail_page",
544
581
  "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
582
  {
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")
583
+ entity: z5.string().describe('Entity slug (e.g., "equipment")'),
584
+ slugField: z5.string().optional().describe('Field to use as URL slug (default: "id")'),
585
+ specPath: z5.string().optional().describe("Path to OpenAPI spec for field details")
549
586
  },
550
587
  async ({ entity, slugField = "id", specPath }) => {
551
588
  let fields = [];
@@ -621,298 +658,170 @@ ${yaml}
621
658
  }
622
659
 
623
660
  // 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
- }
661
+ import { z as z6 } from "zod";
662
+ var CONTRADICTION_PATTERNS = [
663
+ {
664
+ keywords: ["minimal", "clean", "simple"],
665
+ conflicts: ["vibrant", "rich", "content-heavy", "playful"]
666
+ },
667
+ {
668
+ keywords: ["dark", "dark mode"],
669
+ conflicts: ["light mode only", "light"]
670
+ },
671
+ {
672
+ keywords: ["enterprise", "professional", "corporate"],
673
+ conflicts: ["playful", "casual", "fun"]
674
+ },
675
+ {
676
+ keywords: ["accessible", "wcag", "section 508"],
677
+ conflicts: ["compact", "dense", "small text"]
678
+ },
679
+ {
680
+ keywords: ["government", "defense", "federal"],
681
+ conflicts: ["public", "no auth", "consumer"]
682
+ }
683
+ ];
684
+ function handleClarify(input) {
685
+ const { question_type, question, choices, priority, target_field, context } = input;
686
+ const base = {
687
+ action: "ask_user",
688
+ targetField: target_field
689
+ };
690
+ if (question_type === "closed_choice" && choices && choices.length > 0) {
691
+ const header = truncateHeader(question);
692
+ base.adaptedQuestion = {
693
+ question,
694
+ header,
695
+ options: choices.map((c) => ({ label: c }))
706
696
  };
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
- });
697
+ } else {
698
+ const contextPrefix = context ? `Context: ${context}
699
+
700
+ ` : "";
701
+ base.prompt = `${contextPrefix}${question}`;
702
+ }
703
+ if (priority === "optional") {
704
+ base.suggestedDefault = inferDefault(question_type, choices);
705
+ }
706
+ return base;
731
707
  }
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;
708
+ function handleDetectConflict(input) {
709
+ const preferenceLower = input.stated_preference.toLowerCase();
710
+ const valuesLower = Object.values(input.selected_values).map((v) => v.toLowerCase());
711
+ for (const pattern of CONTRADICTION_PATTERNS) {
712
+ const preferenceMatch = pattern.keywords.some((kw) => preferenceLower.includes(kw));
713
+ if (!preferenceMatch) continue;
714
+ const conflictingValues = valuesLower.filter(
715
+ (val) => pattern.conflicts.some((c) => val.includes(c))
716
+ );
717
+ if (conflictingValues.length > 0) {
718
+ const matchedKeywords = pattern.keywords.filter((kw) => preferenceLower.includes(kw));
719
+ const primaryKeyword = matchedKeywords[0] ?? "preference";
720
+ return {
721
+ conflict: true,
722
+ description: `Stated preference includes "${matchedKeywords.join(", ")}" but selections contain "${conflictingValues.join(", ")}" \u2014 these are contradictory.`,
723
+ resolution_options: [
724
+ `Align selections with the "${primaryKeyword}" preference`,
725
+ `Revise stated preference to match current selections`,
726
+ "Ask user which direction they actually want"
727
+ ]
728
+ };
741
729
  }
742
730
  }
743
- return process.cwd();
731
+ return { conflict: false };
732
+ }
733
+ function truncateHeader(text) {
734
+ const MAX = 50;
735
+ if (text.length <= MAX) return text;
736
+ return text.slice(0, MAX - 1) + "\u2026";
737
+ }
738
+ function inferDefault(questionType, choices) {
739
+ if (questionType === "closed_choice" && choices && choices.length > 0) {
740
+ return choices[0] ?? "(first choice)";
741
+ }
742
+ return "(use sensible project default)";
744
743
  }
745
744
  function registerClarificationTools(server2) {
746
745
  server2.tool(
747
746
  "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.",
747
+ "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
748
  {
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?")
749
+ context: z6.string().optional().describe("Context about what the otter is trying to do"),
750
+ question_type: z6.enum(["closed_choice", "open_text"]).describe("Type of question being asked"),
751
+ question: z6.string().describe("The clarification question to ask the user"),
752
+ choices: jsonCoerce(z6.array(z6.string()).optional()).describe(
753
+ "Options for closed_choice questions"
754
+ ),
755
+ priority: z6.enum(["blocking", "preferred", "optional"]).optional().default("preferred").describe("How critical is this clarification? Default: preferred"),
756
+ target_field: z6.string().optional().describe("What field/config does this clarify?")
756
757
  },
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
- }
758
+ async ({ context, question_type, question, choices, priority, target_field }) => {
759
+ const result = handleClarify({
760
+ context: context ?? void 0,
761
+ question_type,
762
+ question,
763
+ choices: choices ?? void 0,
764
+ priority: priority ?? "preferred",
765
+ target_field: target_field ?? void 0
766
+ });
767
+ return {
768
+ content: [
769
+ {
770
+ type: "text",
771
+ 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.")
772
+ },
773
+ {
774
+ type: "text",
775
+ text: JSON.stringify(result)
776
+ }
777
+ ]
778
+ };
830
779
  }
831
780
  );
832
781
  server2.tool(
833
782
  "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.",
783
+ "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
784
  {
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")
785
+ stated_preference: z6.string().describe("What the user said they wanted"),
786
+ selected_values: jsonCoerce(z6.record(z6.string(), z6.string())).describe(
787
+ "What the user actually selected (field \u2192 value)"
788
+ )
838
789
  },
839
790
  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
791
+ const result = handleDetectConflict({ stated_preference, selected_values });
792
+ if (result.conflict) {
793
+ return {
794
+ content: [
795
+ {
796
+ type: "text",
797
+ text: `\u26A0\uFE0F CONFLICT DETECTED
857
798
 
858
799
  User stated: "${stated_preference}"
859
800
  But selected: ${JSON.stringify(selected_values)}
860
801
 
861
- Conflict: ${data.description}
802
+ ${result.description}
862
803
 
863
- Resolution options: ${data.options?.join(", ") || "Ask user to clarify"}
804
+ Resolution options:
805
+ ${result.resolution_options?.map((o) => ` \u2022 ${o}`).join("\n")}
864
806
 
865
807
  \u{1F4A1} Consider asking the user to reconcile this conflict.`
866
- }
867
- ]
868
- };
869
- }
870
- return {
871
- content: [
808
+ },
872
809
  {
873
810
  type: "text",
874
- text: `\u2705 No conflict detected between stated preference and selections.`
811
+ text: JSON.stringify(result)
875
812
  }
876
813
  ]
877
814
  };
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
815
  }
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
816
  return {
900
817
  content: [
901
818
  {
902
819
  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.`
820
+ text: "\u2705 No conflict detected between stated preference and selections."
821
+ },
822
+ {
823
+ type: "text",
824
+ text: JSON.stringify(result)
916
825
  }
917
826
  ]
918
827
  };
@@ -921,31 +830,53 @@ Default behaviors:
921
830
  }
922
831
 
923
832
  // src/tools/packages.ts
924
- import { z as z6 } from "zod";
925
- import { readFileSync, writeFileSync, existsSync as existsSync2, realpathSync, lstatSync } from "fs";
833
+ import { z as z7 } from "zod";
834
+ import { readFileSync, writeFileSync, existsSync, realpathSync, lstatSync } from "fs";
926
835
  import { execSync } from "child_process";
927
836
  import path2 from "path";
837
+ var BASELINE_DEPS = {
838
+ "@stackwright-pro/mcp": "latest",
839
+ "@stackwright-pro/otters": "latest",
840
+ "@stackwright-pro/openapi": "latest",
841
+ "@stackwright-pro/auth": "latest",
842
+ "@stackwright-pro/auth-nextjs": "latest",
843
+ zod: "^3.23.0"
844
+ };
845
+ var BASELINE_DEV_DEPS = {
846
+ "@stoplight/prism-cli": "^5.14.2"
847
+ };
928
848
  function registerPackageTools(server2) {
929
849
  server2.tool(
930
850
  "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.",
851
+ "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
852
  {
933
853
  // 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" }'
854
+ packages: jsonCoerce(z7.record(z7.string(), z7.string()).optional().default({})).describe(
855
+ 'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }. Omit or pass {} when using includeBaseline: true.'
856
+ ),
857
+ devPackages: jsonCoerce(z7.record(z7.string(), z7.string()).optional()).describe(
858
+ "devDependencies to add. Same format as packages."
859
+ ),
860
+ scripts: jsonCoerce(z7.record(z7.string(), z7.string()).optional()).describe(
861
+ "npm scripts to add. Only adds if key does not already exist."
936
862
  ),
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(
863
+ targetDir: z7.string().optional().describe(
940
864
  "Project directory containing package.json. Defaults to process.cwd(). Must be an absolute path within the current working directory."
941
865
  ),
942
- runInstall: z6.boolean().optional().default(true).describe("Run pnpm install after writing package.json. Defaults to true.")
866
+ runInstall: boolCoerce(z7.boolean().optional().default(true)).describe(
867
+ "Run pnpm install after writing package.json. Defaults to true. Pass boolean true/false."
868
+ ),
869
+ includeBaseline: boolCoerce(z7.boolean().optional().default(false)).describe(
870
+ "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."
871
+ )
943
872
  },
944
- async ({ packages, devPackages, scripts, targetDir, runInstall }) => {
873
+ async ({ packages, devPackages, scripts, targetDir, runInstall, includeBaseline }) => {
874
+ const mergedPackages = includeBaseline ? { ...BASELINE_DEPS, ...packages } : { ...packages };
875
+ const mergedDevPackages = includeBaseline ? { ...BASELINE_DEV_DEPS, ...devPackages ?? {} } : devPackages;
945
876
  const result = setupPackages({
946
- packages,
877
+ packages: mergedPackages,
947
878
  runInstall,
948
- ...devPackages !== void 0 ? { devPackages } : {},
879
+ ...mergedDevPackages !== void 0 ? { devPackages: mergedDevPackages } : {},
949
880
  ...scripts !== void 0 ? { scripts } : {},
950
881
  ...targetDir !== void 0 ? { targetDir } : {}
951
882
  });
@@ -998,7 +929,7 @@ function setupPackages(opts) {
998
929
  };
999
930
  }
1000
931
  const preResolvePackageJsonPath = path2.join(resolvedTarget, "package.json");
1001
- if (!existsSync2(preResolvePackageJsonPath)) {
932
+ if (!existsSync(preResolvePackageJsonPath)) {
1002
933
  return {
1003
934
  success: false,
1004
935
  ...emptyResult,
@@ -1094,11 +1025,11 @@ function setupPackages(opts) {
1094
1025
  }
1095
1026
  }
1096
1027
  const raw = readFileSync(realPackageJsonPath, "utf8");
1097
- const PackageJsonSchema = z6.object({
1028
+ const PackageJsonSchema = z7.object({
1098
1029
  // 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()
1030
+ dependencies: z7.record(z7.string(), z7.string()).optional(),
1031
+ devDependencies: z7.record(z7.string(), z7.string()).optional(),
1032
+ scripts: z7.record(z7.string(), z7.string()).optional()
1102
1033
  }).passthrough();
1103
1034
  const schemaResult = PackageJsonSchema.safeParse(JSON.parse(raw));
1104
1035
  if (!schemaResult.success) {
@@ -1178,38 +1109,2418 @@ function setupPackages(opts) {
1178
1109
  }
1179
1110
  }
1180
1111
 
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.2",
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"
1112
+ // src/tools/questions.ts
1113
+ import { readFile } from "fs/promises";
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: JSON.stringify({
1387
+ phase,
1388
+ skipped: true,
1389
+ reason: "No questions to present (all filtered by dependsOn conditions)",
1390
+ answers: []
1391
+ })
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
+ }
1413
+
1414
+ // src/tools/orchestration.ts
1415
+ import { z as z9 } from "zod";
1416
+ import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync2, mkdirSync, lstatSync as lstatSync2 } from "fs";
1417
+ import { join as join2 } from "path";
1418
+ var OTTER_NAME_TO_PHASE = [
1419
+ ["designer", "designer"],
1420
+ ["theme", "theme"],
1421
+ ["api", "api"],
1422
+ ["auth", "auth"],
1423
+ ["dashboard", "dashboard"],
1424
+ ["data", "data"],
1425
+ ["page", "pages"],
1426
+ ["workflow", "workflow"]
1427
+ ];
1428
+ var PHASE_TO_OTTER = {
1429
+ designer: "stackwright-pro-designer-otter",
1430
+ theme: "stackwright-pro-theme-otter",
1431
+ api: "stackwright-pro-api-otter",
1432
+ auth: "stackwright-pro-auth-otter",
1433
+ pages: "stackwright-pro-page-otter",
1434
+ dashboard: "stackwright-pro-dashboard-otter",
1435
+ data: "stackwright-pro-data-otter",
1436
+ workflow: "stackwright-pro-workflow-otter"
1437
+ };
1438
+ function detectPhase(otterName) {
1439
+ const lower = otterName.toLowerCase();
1440
+ for (const [keyword, phase] of OTTER_NAME_TO_PHASE) {
1441
+ if (lower.includes(keyword)) return phase;
1442
+ }
1443
+ return lower.replace(/^stackwright-pro-/, "").replace(/-otter$/, "");
1444
+ }
1445
+ function handleParseOtterResponse(input) {
1446
+ const phase = detectPhase(input.otterName);
1447
+ try {
1448
+ const questions = parseLLMQuestionsResponse(input.responseText);
1449
+ return {
1450
+ result: { phase, otter: input.otterName, questions },
1451
+ isError: false
1452
+ };
1453
+ } catch (err) {
1454
+ const message = err instanceof Error ? err.message : String(err);
1455
+ return {
1456
+ result: {
1457
+ error: true,
1458
+ otterName: input.otterName,
1459
+ phase,
1460
+ questions: [],
1461
+ parseError: message
1462
+ },
1463
+ isError: true
1464
+ };
1465
+ }
1466
+ }
1467
+ function handleSaveManifest(input) {
1468
+ const cwd = input._cwd ?? process.cwd();
1469
+ const dir = join2(cwd, ".stackwright");
1470
+ const filePath = join2(dir, "question-manifest.json");
1471
+ try {
1472
+ mkdirSync(dir, { recursive: true });
1473
+ if (existsSync2(filePath)) {
1474
+ const stat = lstatSync2(filePath);
1475
+ if (stat.isSymbolicLink()) {
1476
+ const message = `Refusing to write to symlink: ${filePath}`;
1477
+ return {
1478
+ text: JSON.stringify({ success: false, error: message }),
1479
+ isError: true
1480
+ };
1481
+ }
1482
+ }
1483
+ const manifest = {
1484
+ version: "1.0",
1485
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1486
+ phases: input.phases
1487
+ };
1488
+ writeFileSync2(filePath, JSON.stringify(manifest, null, 2) + "\n");
1489
+ return {
1490
+ text: JSON.stringify({ success: true, path: filePath, phaseCount: input.phases.length }),
1491
+ isError: false
1492
+ };
1493
+ } catch (err) {
1494
+ const message = err instanceof Error ? err.message : String(err);
1495
+ return {
1496
+ text: JSON.stringify({ success: false, error: message }),
1497
+ isError: true
1498
+ };
1499
+ }
1500
+ }
1501
+ function handleSavePhaseAnswers(input) {
1502
+ const cwd = input._cwd ?? process.cwd();
1503
+ const dir = join2(cwd, ".stackwright", "answers");
1504
+ const filePath = join2(dir, `${input.phase}.json`);
1505
+ try {
1506
+ mkdirSync(dir, { recursive: true });
1507
+ let answers;
1508
+ if (input.questions && input.questions.length > 0) {
1509
+ answers = answersToManifestFormat(input.rawAnswers, input.questions);
1510
+ } else {
1511
+ answers = Object.fromEntries(
1512
+ input.rawAnswers.map((a) => [a.question_header, a.selected_options[0] ?? ""])
1513
+ );
1514
+ }
1515
+ const payload = {
1516
+ version: "1.0",
1517
+ phase: input.phase,
1518
+ completedAt: (/* @__PURE__ */ new Date()).toISOString(),
1519
+ answers
1520
+ };
1521
+ if (existsSync2(filePath)) {
1522
+ const stat = lstatSync2(filePath);
1523
+ if (stat.isSymbolicLink()) {
1524
+ const message = `Refusing to write to symlink: ${filePath}`;
1525
+ return {
1526
+ text: JSON.stringify({ success: false, error: message }),
1527
+ isError: true
1528
+ };
1529
+ }
1530
+ }
1531
+ writeFileSync2(filePath, JSON.stringify(payload, null, 2) + "\n");
1532
+ return {
1533
+ text: JSON.stringify({
1534
+ success: true,
1535
+ path: filePath,
1536
+ answersCount: Object.keys(answers).length
1537
+ }),
1538
+ isError: false
1539
+ };
1540
+ } catch (err) {
1541
+ const message = err instanceof Error ? err.message : String(err);
1542
+ return {
1543
+ text: JSON.stringify({ success: false, error: message }),
1544
+ isError: true
1545
+ };
1546
+ }
1547
+ }
1548
+ function handleReadPhaseAnswers(input) {
1549
+ const cwd = input._cwd ?? process.cwd();
1550
+ const filePath = join2(cwd, ".stackwright", "answers", `${input.phase}.json`);
1551
+ if (!existsSync2(filePath)) {
1552
+ return {
1553
+ text: JSON.stringify({ missing: true, phase: input.phase }),
1554
+ isError: false
1555
+ };
1556
+ }
1557
+ try {
1558
+ const raw = readFileSync2(filePath, "utf8");
1559
+ const parsed = JSON.parse(raw);
1560
+ return { text: JSON.stringify(parsed), isError: false };
1561
+ } catch (err) {
1562
+ const message = err instanceof Error ? err.message : String(err);
1563
+ return {
1564
+ text: JSON.stringify({ error: true, phase: input.phase, readError: message }),
1565
+ isError: true
1566
+ };
1567
+ }
1568
+ }
1569
+ function handleGetOtterName(input) {
1570
+ const normalised = input.phase.toLowerCase().trim();
1571
+ const otterName = PHASE_TO_OTTER[normalised];
1572
+ if (!otterName) {
1573
+ return {
1574
+ text: JSON.stringify({ error: true, message: `Unknown phase: ${input.phase}` }),
1575
+ isError: true
1576
+ };
1577
+ }
1578
+ return {
1579
+ text: JSON.stringify({ phase: normalised, otterName }),
1580
+ isError: false
1581
+ };
1582
+ }
1583
+ function registerOrchestrationTools(server2) {
1584
+ server2.tool(
1585
+ "stackwright_pro_parse_otter_response",
1586
+ "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.",
1587
+ {
1588
+ otterName: z9.string().describe('The agent name, e.g. "stackwright-pro-api-otter"'),
1589
+ responseText: z9.string().describe("Raw text response from the otter's QUESTION_COLLECTION_MODE invocation")
1590
+ },
1591
+ async ({ otterName, responseText }) => {
1592
+ const { result, isError } = handleParseOtterResponse({ otterName, responseText });
1593
+ return {
1594
+ content: [{ type: "text", text: JSON.stringify(result) }],
1595
+ isError
1596
+ };
1597
+ }
1598
+ );
1599
+ server2.tool(
1600
+ "stackwright_pro_save_manifest",
1601
+ "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.",
1602
+ {
1603
+ phases: jsonCoerce(
1604
+ z9.array(
1605
+ z9.object({
1606
+ phase: z9.string(),
1607
+ otter: z9.string(),
1608
+ questions: z9.array(z9.any()),
1609
+ requiredPackages: z9.object({
1610
+ dependencies: z9.record(z9.string(), z9.string()).optional(),
1611
+ devPackages: z9.record(z9.string(), z9.string()).optional()
1612
+ }).optional()
1613
+ })
1614
+ )
1615
+ ).describe("Array of parsed phase objects from stackwright_pro_parse_otter_response")
1616
+ },
1617
+ async ({ phases }) => {
1618
+ const { text, isError } = handleSaveManifest({ phases });
1619
+ return {
1620
+ content: [{ type: "text", text }],
1621
+ isError
1622
+ };
1623
+ }
1624
+ );
1625
+ server2.tool(
1626
+ "stackwright_pro_save_phase_answers",
1627
+ "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.",
1628
+ {
1629
+ phase: z9.string().describe('Phase name, e.g. "designer"'),
1630
+ rawAnswers: jsonCoerce(
1631
+ z9.array(
1632
+ z9.object({
1633
+ question_header: z9.string(),
1634
+ selected_options: z9.array(z9.string()),
1635
+ other_text: z9.string().nullable().optional()
1636
+ })
1637
+ )
1638
+ ).describe(
1639
+ "Answers as returned by ask_user_question \u2014 pass the native array, not a JSON string"
1640
+ ),
1641
+ questions: jsonCoerce(z9.array(z9.any()).optional()).describe(
1642
+ "Original manifest questions for label\u2192value reverse-mapping \u2014 pass the native array, not a JSON string"
1643
+ )
1644
+ },
1645
+ async ({ phase, rawAnswers, questions }) => {
1646
+ const { text, isError } = handleSavePhaseAnswers({
1647
+ phase,
1648
+ rawAnswers,
1649
+ ...questions && questions.length > 0 ? { questions } : {}
1650
+ });
1651
+ return {
1652
+ content: [{ type: "text", text }],
1653
+ isError
1654
+ };
1655
+ }
1656
+ );
1657
+ server2.tool(
1658
+ "stackwright_pro_read_phase_answers",
1659
+ "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.",
1660
+ {
1661
+ phase: z9.string().describe('Phase name, e.g. "designer"')
1662
+ },
1663
+ async ({ phase }) => {
1664
+ const { text, isError } = handleReadPhaseAnswers({ phase });
1665
+ return {
1666
+ content: [{ type: "text", text }],
1667
+ isError
1668
+ };
1669
+ }
1670
+ );
1671
+ server2.tool(
1672
+ "stackwright_pro_get_otter_name",
1673
+ "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.",
1674
+ {
1675
+ phase: z9.string().describe('Phase name, e.g. "designer", "api", "pages"')
1676
+ },
1677
+ async ({ phase }) => {
1678
+ const { text, isError } = handleGetOtterName({ phase });
1679
+ return {
1680
+ content: [{ type: "text", text }],
1681
+ isError
1682
+ };
1683
+ }
1684
+ );
1685
+ }
1686
+
1687
+ // src/tools/pipeline.ts
1688
+ import { z as z10 } from "zod";
1689
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, existsSync as existsSync3, mkdirSync as mkdirSync2, lstatSync as lstatSync3 } from "fs";
1690
+ import { join as join3 } from "path";
1691
+ var PHASE_ORDER = [
1692
+ "designer",
1693
+ "theme",
1694
+ "api",
1695
+ "auth",
1696
+ "data",
1697
+ "pages",
1698
+ "dashboard",
1699
+ "workflow"
1700
+ ];
1701
+ var PHASE_DEPENDENCIES = {
1702
+ designer: [],
1703
+ theme: ["designer"],
1704
+ api: [],
1705
+ auth: [],
1706
+ data: ["api"],
1707
+ pages: ["designer", "theme", "api", "data", "auth"],
1708
+ dashboard: ["designer", "theme", "api", "data"],
1709
+ workflow: ["auth"]
1710
+ };
1711
+ var PHASE_ARTIFACT = {
1712
+ designer: "design-language.json",
1713
+ theme: "theme-tokens.json",
1714
+ api: "api-config.json",
1715
+ auth: "auth-config.json",
1716
+ data: "data-config.json",
1717
+ pages: "pages-manifest.json",
1718
+ dashboard: "dashboard-manifest.json",
1719
+ workflow: "workflow-config.json"
1720
+ };
1721
+ var PHASE_TO_OTTER2 = {
1722
+ designer: "stackwright-pro-designer-otter",
1723
+ theme: "stackwright-pro-theme-otter",
1724
+ api: "stackwright-pro-api-otter",
1725
+ auth: "stackwright-pro-auth-otter",
1726
+ data: "stackwright-pro-data-otter",
1727
+ pages: "stackwright-pro-page-otter",
1728
+ dashboard: "stackwright-pro-dashboard-otter",
1729
+ workflow: "stackwright-pro-workflow-otter"
1730
+ };
1731
+ function isValidPhase(phase) {
1732
+ return PHASE_ORDER.includes(phase);
1733
+ }
1734
+ function defaultPhaseStatus() {
1735
+ return {
1736
+ questionsCollected: false,
1737
+ answered: false,
1738
+ executed: false,
1739
+ artifactWritten: false,
1740
+ retryCount: 0
1741
+ };
1742
+ }
1743
+ function createDefaultState() {
1744
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1745
+ const phases = {};
1746
+ for (const p of PHASE_ORDER) {
1747
+ phases[p] = defaultPhaseStatus();
1748
+ }
1749
+ return {
1750
+ version: "1.0",
1751
+ currentPhase: PHASE_ORDER[0],
1752
+ status: "setup",
1753
+ phases,
1754
+ startedAt: now,
1755
+ updatedAt: now
1756
+ };
1757
+ }
1758
+ function statePath(cwd) {
1759
+ return join3(cwd, ".stackwright", "pipeline-state.json");
1760
+ }
1761
+ function readState(cwd) {
1762
+ const p = statePath(cwd);
1763
+ if (!existsSync3(p)) return createDefaultState();
1764
+ const raw = JSON.parse(safeReadSync(p));
1765
+ if (typeof raw !== "object" || raw === null || raw.version !== "1.0") {
1766
+ return createDefaultState();
1767
+ }
1768
+ return raw;
1769
+ }
1770
+ function safeWriteSync(filePath, content) {
1771
+ if (existsSync3(filePath)) {
1772
+ const stat = lstatSync3(filePath);
1773
+ if (stat.isSymbolicLink()) {
1774
+ throw new Error(`Refusing to write to symlink: ${filePath}`);
1775
+ }
1776
+ }
1777
+ writeFileSync3(filePath, content);
1778
+ }
1779
+ function safeReadSync(filePath) {
1780
+ if (existsSync3(filePath)) {
1781
+ const stat = lstatSync3(filePath);
1782
+ if (stat.isSymbolicLink()) {
1783
+ throw new Error(`Refusing to read symlink: ${filePath}`);
1784
+ }
1785
+ }
1786
+ return readFileSync3(filePath, "utf-8");
1787
+ }
1788
+ function writeState(cwd, state) {
1789
+ const dir = join3(cwd, ".stackwright");
1790
+ mkdirSync2(dir, { recursive: true });
1791
+ state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1792
+ safeWriteSync(statePath(cwd), JSON.stringify(state, null, 2) + "\n");
1793
+ }
1794
+ function extractJsonFromResponse(text) {
1795
+ let cleaned = text;
1796
+ cleaned = cleaned.replace(/```(?:json)?\s*/gi, "");
1797
+ cleaned = cleaned.replace(/```\s*$/gm, "");
1798
+ const firstBrace = cleaned.indexOf("{");
1799
+ if (firstBrace === -1) throw new Error("No JSON object found in response");
1800
+ cleaned = cleaned.substring(firstBrace);
1801
+ const lastBrace = cleaned.lastIndexOf("}");
1802
+ if (lastBrace === -1) throw new Error("Unclosed JSON object in response");
1803
+ cleaned = cleaned.substring(0, lastBrace + 1);
1804
+ cleaned = cleaned.replace(/,(\s*[}\]])/g, "$1");
1805
+ return JSON.parse(cleaned);
1806
+ }
1807
+ function handleGetPipelineState(_cwd) {
1808
+ const cwd = _cwd ?? process.cwd();
1809
+ try {
1810
+ const state = readState(cwd);
1811
+ return { text: JSON.stringify(state), isError: false };
1812
+ } catch (err) {
1813
+ return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
1814
+ }
1815
+ }
1816
+ function handleSetPipelineState(input) {
1817
+ const cwd = input._cwd ?? process.cwd();
1818
+ if (input.phase && !isValidPhase(input.phase)) {
1819
+ return {
1820
+ text: JSON.stringify({
1821
+ error: true,
1822
+ message: `Invalid phase: ${input.phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
1823
+ }),
1824
+ isError: true
1825
+ };
1826
+ }
1827
+ const VALID_FIELDS = ["questionsCollected", "answered", "executed", "artifactWritten"];
1828
+ if (input.field && !VALID_FIELDS.includes(input.field)) {
1829
+ return {
1830
+ text: JSON.stringify({
1831
+ error: true,
1832
+ message: `Invalid field: ${input.field}. Valid fields are: ${VALID_FIELDS.join(", ")}`
1833
+ }),
1834
+ isError: true
1835
+ };
1836
+ }
1837
+ try {
1838
+ const state = readState(cwd);
1839
+ if (input.status) {
1840
+ state.status = input.status;
1841
+ }
1842
+ if (input.phase) {
1843
+ const phase = input.phase;
1844
+ if (!state.phases[phase]) {
1845
+ state.phases[phase] = defaultPhaseStatus();
1846
+ }
1847
+ const phaseState = state.phases[phase];
1848
+ if (input.field && input.value !== void 0) {
1849
+ phaseState[input.field] = input.value;
1850
+ }
1851
+ if (input.incrementRetry) {
1852
+ phaseState.retryCount += 1;
1853
+ }
1854
+ state.currentPhase = phase;
1855
+ }
1856
+ writeState(cwd, state);
1857
+ return { text: JSON.stringify(state), isError: false };
1858
+ } catch (err) {
1859
+ return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
1860
+ }
1861
+ }
1862
+ function handleCheckExecutionReady(_cwd) {
1863
+ const cwd = _cwd ?? process.cwd();
1864
+ try {
1865
+ const answersDir = join3(cwd, ".stackwright", "answers");
1866
+ const answeredPhases = [];
1867
+ const missingPhases = [];
1868
+ for (const phase of PHASE_ORDER) {
1869
+ const answerFile = join3(answersDir, `${phase}.json`);
1870
+ if (existsSync3(answerFile)) {
1871
+ try {
1872
+ const raw = safeReadSync(answerFile);
1873
+ const parsed = JSON.parse(raw);
1874
+ if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
1875
+ missingPhases.push(phase);
1876
+ continue;
1877
+ }
1878
+ answeredPhases.push(phase);
1879
+ } catch {
1880
+ missingPhases.push(phase);
1881
+ }
1882
+ } else {
1883
+ missingPhases.push(phase);
1884
+ }
1885
+ }
1886
+ return {
1887
+ text: JSON.stringify({
1888
+ ready: missingPhases.length === 0,
1889
+ answeredPhases,
1890
+ missingPhases,
1891
+ totalPhases: PHASE_ORDER.length
1892
+ }),
1893
+ isError: false
1894
+ };
1895
+ } catch (err) {
1896
+ return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
1897
+ }
1898
+ }
1899
+ function handleListArtifacts(_cwd) {
1900
+ const cwd = _cwd ?? process.cwd();
1901
+ try {
1902
+ const artifactsDir = join3(cwd, ".stackwright", "artifacts");
1903
+ const artifacts = [];
1904
+ let completedCount = 0;
1905
+ for (const phase of PHASE_ORDER) {
1906
+ const expectedFile = PHASE_ARTIFACT[phase];
1907
+ const fullPath = join3(artifactsDir, expectedFile);
1908
+ const exists = existsSync3(fullPath);
1909
+ if (exists) completedCount++;
1910
+ artifacts.push({ phase, expectedFile, exists, path: fullPath });
1911
+ }
1912
+ return {
1913
+ text: JSON.stringify({ artifacts, completedCount, totalCount: PHASE_ORDER.length }),
1914
+ isError: false
1915
+ };
1916
+ } catch (err) {
1917
+ return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
1918
+ }
1919
+ }
1920
+ function handleWritePhaseQuestions(input) {
1921
+ const cwd = input._cwd ?? process.cwd();
1922
+ const { phase, responseText } = input;
1923
+ if (!isValidPhase(phase)) {
1924
+ return {
1925
+ text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
1926
+ isError: true
1927
+ };
1928
+ }
1929
+ try {
1930
+ const questions = parseLLMQuestionsResponse(responseText);
1931
+ let requiredPackages = {
1932
+ dependencies: {},
1933
+ devPackages: {}
1934
+ };
1935
+ try {
1936
+ const fullParsed = extractJsonFromResponse(responseText);
1937
+ if (fullParsed.requiredPackages && typeof fullParsed.requiredPackages === "object") {
1938
+ const rp = fullParsed.requiredPackages;
1939
+ requiredPackages = {
1940
+ dependencies: rp.dependencies ?? {},
1941
+ devPackages: rp.devPackages ?? {}
1942
+ };
1943
+ }
1944
+ } catch {
1945
+ }
1946
+ const questionsDir = join3(cwd, ".stackwright", "questions");
1947
+ mkdirSync2(questionsDir, { recursive: true });
1948
+ const filePath = join3(questionsDir, `${phase}.json`);
1949
+ const payload = {
1950
+ version: "1.0",
1951
+ phase,
1952
+ otter: PHASE_TO_OTTER2[phase],
1953
+ collectedAt: (/* @__PURE__ */ new Date()).toISOString(),
1954
+ questions,
1955
+ requiredPackages
1956
+ };
1957
+ safeWriteSync(filePath, JSON.stringify(payload, null, 2) + "\n");
1958
+ const state = readState(cwd);
1959
+ if (!state.phases[phase]) state.phases[phase] = defaultPhaseStatus();
1960
+ const ps = state.phases[phase];
1961
+ ps.questionsCollected = true;
1962
+ writeState(cwd, state);
1963
+ return {
1964
+ text: JSON.stringify({
1965
+ success: true,
1966
+ phase,
1967
+ questionCount: questions.length,
1968
+ requiredPackages,
1969
+ path: filePath
1970
+ }),
1971
+ isError: false
1972
+ };
1973
+ } catch (err) {
1974
+ const message = err instanceof Error ? err.message : String(err);
1975
+ return { text: JSON.stringify({ error: true, phase, message }), isError: true };
1976
+ }
1977
+ }
1978
+ function handleBuildSpecialistPrompt(input) {
1979
+ const cwd = input._cwd ?? process.cwd();
1980
+ const { phase } = input;
1981
+ if (!isValidPhase(phase)) {
1982
+ return {
1983
+ text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
1984
+ isError: true
1985
+ };
1986
+ }
1987
+ try {
1988
+ const answersPath = join3(cwd, ".stackwright", "answers", `${phase}.json`);
1989
+ let answers = {};
1990
+ if (existsSync3(answersPath)) {
1991
+ answers = JSON.parse(safeReadSync(answersPath));
1992
+ }
1993
+ const deps = PHASE_DEPENDENCIES[phase];
1994
+ const artifactSections = [];
1995
+ const missingDependencies = [];
1996
+ for (const dep of deps) {
1997
+ const artifactFile = PHASE_ARTIFACT[dep];
1998
+ const artifactPath = join3(cwd, ".stackwright", "artifacts", artifactFile);
1999
+ if (existsSync3(artifactPath)) {
2000
+ const content = JSON.parse(safeReadSync(artifactPath));
2001
+ const expectedOtter = PHASE_TO_OTTER2[dep];
2002
+ const artifactOtter = content["generatedBy"];
2003
+ if (!artifactOtter) {
2004
+ missingDependencies.push(dep);
2005
+ artifactSections.push(
2006
+ `[${artifactFile}]:
2007
+ (integrity check failed: missing generatedBy field)`
2008
+ );
2009
+ } else if (artifactOtter !== expectedOtter) {
2010
+ missingDependencies.push(dep);
2011
+ artifactSections.push(
2012
+ `[${artifactFile}]:
2013
+ (integrity check failed: artifact claims generatedBy="${artifactOtter}" but expected="${expectedOtter}")`
2014
+ );
2015
+ } else {
2016
+ artifactSections.push(`[${artifactFile}]:
2017
+ ${JSON.stringify(content, null, 2)}`);
2018
+ }
2019
+ } else {
2020
+ missingDependencies.push(dep);
2021
+ artifactSections.push(`[${artifactFile}]:
2022
+ (not yet available)`);
2023
+ }
2024
+ }
2025
+ const parts = ["ANSWERS:", JSON.stringify(answers, null, 2)];
2026
+ if (artifactSections.length > 0) {
2027
+ parts.push("", "UPSTREAM ARTIFACTS:", "", ...artifactSections);
2028
+ }
2029
+ parts.push("", "Execute using these answers and the upstream artifacts provided.");
2030
+ const prompt = parts.join("\n");
2031
+ const dependenciesSatisfied = missingDependencies.length === 0;
2032
+ return {
2033
+ text: JSON.stringify({
2034
+ otterName: PHASE_TO_OTTER2[phase],
2035
+ phase,
2036
+ prompt,
2037
+ dependenciesSatisfied,
2038
+ missingDependencies
2039
+ }),
2040
+ isError: false
2041
+ };
2042
+ } catch (err) {
2043
+ const message = err instanceof Error ? err.message : String(err);
2044
+ return { text: JSON.stringify({ error: true, phase, message }), isError: true };
2045
+ }
2046
+ }
2047
+ var OFF_SCRIPT_PATTERNS = [
2048
+ {
2049
+ pattern: /```(?:ts|tsx|js|jsx|python|bash|sh|sql|ruby|go|rust|java|csharp|c\+\+)\b/,
2050
+ label: "code fence"
2051
+ },
2052
+ { pattern: /\bimport\s+[\w{]/, label: "import statement" },
2053
+ { pattern: /\bexport\s+(?:const|function|default|class)\b/, label: "export statement" },
2054
+ { pattern: /\brequire\s*\(/, label: "require() call" },
2055
+ { pattern: /\beval\s*\(/, label: "eval() call" },
2056
+ { pattern: /^#!/m, label: "shebang" },
2057
+ { pattern: /<script[\s>]/i, label: "script tag" },
2058
+ { pattern: /\.(ts|tsx|js|jsx)\b.*\bfile\b/i, label: "code file reference" }
2059
+ ];
2060
+ var PHASE_REQUIRED_KEYS = {
2061
+ designer: ["designLanguage", "themeTokenSeeds"],
2062
+ theme: ["tokens"],
2063
+ api: ["entities"],
2064
+ auth: ["version", "generatedBy"],
2065
+ data: ["version", "generatedBy"],
2066
+ pages: ["version", "generatedBy"],
2067
+ dashboard: ["version", "generatedBy"],
2068
+ workflow: ["version", "generatedBy"]
2069
+ };
2070
+ function handleValidateArtifact(input) {
2071
+ const cwd = input._cwd ?? process.cwd();
2072
+ const { phase, responseText } = input;
2073
+ if (!isValidPhase(phase)) {
2074
+ return {
2075
+ text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
2076
+ isError: true
2077
+ };
2078
+ }
2079
+ for (const { pattern, label } of OFF_SCRIPT_PATTERNS) {
2080
+ if (pattern.test(responseText)) {
2081
+ const result = {
2082
+ valid: false,
2083
+ phase,
2084
+ violation: "off-script",
2085
+ retryPrompt: `You returned code output (detected: ${label}). Return ONLY a JSON artifact \u2014 no code, no files.`
2086
+ };
2087
+ return { text: JSON.stringify(result), isError: false };
2088
+ }
2089
+ }
2090
+ let artifact;
2091
+ try {
2092
+ artifact = extractJsonFromResponse(responseText);
2093
+ } catch {
2094
+ const result = {
2095
+ valid: false,
2096
+ phase,
2097
+ violation: "invalid-json",
2098
+ retryPrompt: "Your response did not contain valid JSON. Return a single JSON object with no surrounding text."
2099
+ };
2100
+ return { text: JSON.stringify(result), isError: false };
2101
+ }
2102
+ if (!artifact.version || !artifact.generatedBy) {
2103
+ const result = {
2104
+ valid: false,
2105
+ phase,
2106
+ violation: "missing-fields",
2107
+ retryPrompt: 'Your JSON artifact is missing required fields. Every artifact MUST include "version" and "generatedBy" at the top level.'
2108
+ };
2109
+ return { text: JSON.stringify(result), isError: false };
2110
+ }
2111
+ const requiredKeys = PHASE_REQUIRED_KEYS[phase];
2112
+ const missingKeys = requiredKeys.filter((k) => !(k in artifact));
2113
+ if (missingKeys.length > 0) {
2114
+ const result = {
2115
+ valid: false,
2116
+ phase,
2117
+ violation: "schema-mismatch",
2118
+ retryPrompt: `Your ${phase} artifact is missing required keys: ${missingKeys.join(", ")}. Include them and try again.`
2119
+ };
2120
+ return { text: JSON.stringify(result), isError: false };
2121
+ }
2122
+ try {
2123
+ const artifactsDir = join3(cwd, ".stackwright", "artifacts");
2124
+ mkdirSync2(artifactsDir, { recursive: true });
2125
+ const artifactFile = PHASE_ARTIFACT[phase];
2126
+ const artifactPath = join3(artifactsDir, artifactFile);
2127
+ safeWriteSync(artifactPath, JSON.stringify(artifact, null, 2) + "\n");
2128
+ const state = readState(cwd);
2129
+ if (!state.phases[phase]) state.phases[phase] = defaultPhaseStatus();
2130
+ const ps = state.phases[phase];
2131
+ ps.artifactWritten = true;
2132
+ writeState(cwd, state);
2133
+ const topKeys = Object.keys(artifact).slice(0, 5).join(", ");
2134
+ const result = {
2135
+ valid: true,
2136
+ phase,
2137
+ artifactPath,
2138
+ summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})`
2139
+ };
2140
+ return { text: JSON.stringify(result), isError: false };
2141
+ } catch (err) {
2142
+ const message = err instanceof Error ? err.message : String(err);
2143
+ return { text: JSON.stringify({ error: true, phase, message }), isError: true };
2144
+ }
2145
+ }
2146
+ function registerPipelineTools(server2) {
2147
+ const DESC = "Writes state to .stackwright/ \u2014 the filesystem is the state machine.";
2148
+ const res = (r) => ({
2149
+ content: [{ type: "text", text: r.text }],
2150
+ isError: r.isError
2151
+ });
2152
+ server2.tool(
2153
+ "stackwright_pro_get_pipeline_state",
2154
+ `Read pipeline state from .stackwright/pipeline-state.json. ${DESC}`,
2155
+ {},
2156
+ async () => res(handleGetPipelineState())
2157
+ );
2158
+ server2.tool(
2159
+ "stackwright_pro_set_pipeline_state",
2160
+ `Atomic read\u2192modify\u2192write pipeline state. ${DESC}`,
2161
+ {
2162
+ phase: z10.string().optional().describe('Phase to update, e.g. "designer"'),
2163
+ field: z10.enum(["questionsCollected", "answered", "executed", "artifactWritten"]).optional().describe("Boolean field to set"),
2164
+ value: boolCoerce(z10.boolean().optional()).describe(
2165
+ 'Value for the field \u2014 must be a JSON boolean (true/false), NOT the string "true"/"false"'
2166
+ ),
2167
+ status: z10.enum(["setup", "questions", "execution", "done"]).optional().describe("Top-level status override"),
2168
+ incrementRetry: boolCoerce(z10.boolean().optional()).describe(
2169
+ "Bump retryCount by 1 \u2014 must be a JSON boolean"
2170
+ )
2171
+ },
2172
+ async (args) => res(
2173
+ handleSetPipelineState({
2174
+ ...args.phase != null ? { phase: args.phase } : {},
2175
+ ...args.field != null ? { field: args.field } : {},
2176
+ ...args.value != null ? { value: args.value } : {},
2177
+ ...args.status != null ? { status: args.status } : {},
2178
+ ...args.incrementRetry != null ? { incrementRetry: args.incrementRetry } : {}
2179
+ })
2180
+ )
2181
+ );
2182
+ server2.tool(
2183
+ "stackwright_pro_check_execution_ready",
2184
+ `Check all phases have answer files in .stackwright/answers/. ${DESC}`,
2185
+ {},
2186
+ async () => res(handleCheckExecutionReady())
2187
+ );
2188
+ server2.tool(
2189
+ "stackwright_pro_list_artifacts",
2190
+ `List phase artifacts in .stackwright/artifacts/ with completedCount/totalCount. ${DESC}`,
2191
+ {},
2192
+ async () => res(handleListArtifacts())
2193
+ );
2194
+ server2.tool(
2195
+ "stackwright_pro_write_phase_questions",
2196
+ `Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. ${DESC}`,
2197
+ {
2198
+ phase: z10.string().describe('Phase name, e.g. "designer"'),
2199
+ responseText: z10.string().describe("Raw LLM response from QUESTION_COLLECTION_MODE")
2200
+ },
2201
+ async ({ phase, responseText }) => res(handleWritePhaseQuestions({ phase, responseText }))
2202
+ );
2203
+ server2.tool(
2204
+ "stackwright_pro_build_specialist_prompt",
2205
+ `Assemble execution prompt from answers + upstream artifacts. Foreman passes verbatim. ${DESC}`,
2206
+ { phase: z10.string().describe('Phase to build prompt for, e.g. "pages"') },
2207
+ async ({ phase }) => res(handleBuildSpecialistPrompt({ phase }))
2208
+ );
2209
+ server2.tool(
2210
+ "stackwright_pro_validate_artifact",
2211
+ `Validate specialist response + write artifact to .stackwright/artifacts/. Returns retryPrompt on failure. ${DESC}`,
2212
+ {
2213
+ phase: z10.string().describe('Phase that produced this artifact, e.g. "designer"'),
2214
+ responseText: z10.string().describe("Raw response text from the specialist otter")
2215
+ },
2216
+ async ({ phase, responseText }) => res(handleValidateArtifact({ phase, responseText }))
2217
+ );
2218
+ }
2219
+
2220
+ // src/tools/safe-write.ts
2221
+ import { z as z11 } from "zod";
2222
+ import { writeFileSync as writeFileSync4, existsSync as existsSync4, mkdirSync as mkdirSync3, lstatSync as lstatSync4 } from "fs";
2223
+ import { normalize, isAbsolute, dirname, join as join4 } from "path";
2224
+ var OTTER_WRITE_ALLOWLISTS = {
2225
+ "stackwright-pro-designer-otter": [
2226
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Design language artifact" }
2227
+ ],
2228
+ "stackwright-pro-theme-otter": [
2229
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" }
2230
+ ],
2231
+ "stackwright-pro-auth-otter": [
2232
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Auth config artifact" },
2233
+ { prefix: "config/", suffix: ".yml", description: "Auth YAML config" },
2234
+ { prefix: "config/", suffix: ".yaml", description: "Auth YAML config" },
2235
+ {
2236
+ prefix: ".env",
2237
+ suffix: "",
2238
+ description: "Dotenv files (.env, .env.local, .env.production, etc.)"
2239
+ }
2240
+ ],
2241
+ "stackwright-pro-data-otter": [
2242
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Data config artifact" },
2243
+ { prefix: "stackwright.yml", suffix: "", description: "Stackwright config" }
2244
+ ],
2245
+ "stackwright-pro-page-otter": [
2246
+ { prefix: "pages/", suffix: "/content.yml", description: "Page content YAML" },
2247
+ { prefix: "pages/", suffix: "/content.yaml", description: "Page content YAML" },
2248
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Pages manifest" }
2249
+ ],
2250
+ "stackwright-pro-dashboard-otter": [
2251
+ { prefix: "pages/", suffix: "/content.yml", description: "Dashboard content YAML" },
2252
+ { prefix: "pages/", suffix: "/content.yaml", description: "Dashboard content YAML" },
2253
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Dashboard manifest" }
2254
+ ],
2255
+ "stackwright-pro-workflow-otter": [
2256
+ { prefix: "workflows/", suffix: ".yml", description: "Workflow definition" },
2257
+ { prefix: "workflows/", suffix: ".yaml", description: "Workflow definition" },
2258
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Workflow config" }
2259
+ ],
2260
+ "stackwright-pro-api-otter": [
2261
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "API config artifact" }
2262
+ ]
2263
+ };
2264
+ var PROTECTED_PATH_PREFIXES = [
2265
+ ".stackwright/pipeline-state.json",
2266
+ ".stackwright/questions/",
2267
+ ".stackwright/answers/"
2268
+ ];
2269
+ function checkPathAllowed(callerOtter, filePath) {
2270
+ const normalized = normalize(filePath);
2271
+ if (normalized.includes("..")) {
2272
+ return { allowed: false, error: 'Path traversal detected: ".." segments are not allowed' };
2273
+ }
2274
+ if (isAbsolute(normalized)) {
2275
+ return {
2276
+ allowed: false,
2277
+ error: "Absolute paths are not allowed \u2014 use paths relative to project root"
2278
+ };
2279
+ }
2280
+ if (callerOtter === "stackwright-pro-foreman-otter") {
2281
+ return {
2282
+ allowed: false,
2283
+ error: "The foreman otter coordinates \u2014 it does not write files directly"
2284
+ };
2285
+ }
2286
+ const allowlist = OTTER_WRITE_ALLOWLISTS[callerOtter];
2287
+ if (!allowlist) {
2288
+ return {
2289
+ allowed: false,
2290
+ error: `Unknown otter: "${callerOtter}" is not in the write allowlist`
2291
+ };
2292
+ }
2293
+ for (const protectedPrefix of PROTECTED_PATH_PREFIXES) {
2294
+ if (normalized === protectedPrefix || normalized.startsWith(protectedPrefix)) {
2295
+ return {
2296
+ allowed: false,
2297
+ error: `Path "${normalized}" is managed by dedicated sink tools, not safe_write`
2298
+ };
2299
+ }
2300
+ }
2301
+ for (const rule of allowlist) {
2302
+ const prefixMatch = normalized.startsWith(rule.prefix);
2303
+ const suffixMatch = rule.suffix === "" || normalized.endsWith(rule.suffix);
2304
+ if (prefixMatch && suffixMatch) {
2305
+ if (rule.prefix === ".env" && rule.suffix === "") {
2306
+ if (!/^\.env(\.[a-zA-Z0-9]{3,})*$/.test(normalized)) {
2307
+ continue;
2308
+ }
2309
+ }
2310
+ return { allowed: true, rule: rule.description };
2311
+ }
2312
+ }
2313
+ return {
2314
+ allowed: false,
2315
+ error: `Path "${normalized}" does not match any allowed write pattern for ${callerOtter}`
2316
+ };
2317
+ }
2318
+ function validateJsonContent(content) {
2319
+ try {
2320
+ JSON.parse(content);
2321
+ return null;
2322
+ } catch (err) {
2323
+ return `Invalid JSON: ${err instanceof Error ? err.message : String(err)}`;
2324
+ }
2325
+ }
2326
+ function validateYamlContent(content) {
2327
+ const trimmed = content.trimStart();
2328
+ const anchorRefPattern = /\[(\*[\w]+)\]/g;
2329
+ const matches = [...content.matchAll(anchorRefPattern)];
2330
+ if (matches.length >= 20) {
2331
+ return "YAML entity expansion pattern detected \u2014 too many anchor references";
2332
+ }
2333
+ const anchorDefPattern = /&([\w]+)/g;
2334
+ const defs = [...content.matchAll(anchorDefPattern)];
2335
+ if (defs.length >= 10) {
2336
+ const anchorNameCounts = /* @__PURE__ */ new Map();
2337
+ for (const [, name] of defs) {
2338
+ const count = (anchorNameCounts.get(name) ?? 0) + 1;
2339
+ anchorNameCounts.set(name, count);
2340
+ if (count >= 10) {
2341
+ return "YAML entity expansion: repeated anchor definitions detected";
2342
+ }
2343
+ }
2344
+ }
2345
+ if (trimmed.startsWith("import ") || trimmed.startsWith("import{")) {
2346
+ return 'Content starts with "import" \u2014 this looks like code, not YAML';
2347
+ }
2348
+ if (trimmed.startsWith("export ") || trimmed.startsWith("export{")) {
2349
+ return 'Content starts with "export" \u2014 this looks like code, not YAML';
2350
+ }
2351
+ if (trimmed.startsWith("#!"))
2352
+ return "Content starts with shebang \u2014 this looks like a script, not YAML";
2353
+ if (/!!(?:python|ruby|perl|js|java)/i.test(content))
2354
+ return "YAML deserialization attack tags detected";
2355
+ if (trimmed.startsWith("<") && !trimmed.startsWith("<<"))
2356
+ return "Content looks like markup, not YAML";
2357
+ return null;
2358
+ }
2359
+ function validateEnvContent(content) {
2360
+ const lines = content.split("\n");
2361
+ for (let i = 0; i < lines.length; i++) {
2362
+ const raw = lines[i];
2363
+ if (raw === void 0) continue;
2364
+ const line = raw.trim();
2365
+ if (line === "" || line.startsWith("#")) continue;
2366
+ if (!/^[A-Za-z_][A-Za-z0-9_]*=/.test(line)) {
2367
+ return `Line ${i + 1} is not a valid env entry (expected KEY=value): "${line}"`;
2368
+ }
2369
+ }
2370
+ return null;
2371
+ }
2372
+ function validateContent(filePath, content) {
2373
+ if (filePath.endsWith(".json")) return validateJsonContent(content);
2374
+ if (filePath.endsWith(".yml") || filePath.endsWith(".yaml")) return validateYamlContent(content);
2375
+ if (filePath === ".env" || filePath.startsWith(".env")) return validateEnvContent(content);
2376
+ return null;
2377
+ }
2378
+ function handleSafeWrite(input) {
2379
+ const cwd = input._cwd ?? process.cwd();
2380
+ const { callerOtter, filePath, content, createDirectories = true } = input;
2381
+ const check = checkPathAllowed(callerOtter, filePath);
2382
+ if (!check.allowed) {
2383
+ const allowlist = OTTER_WRITE_ALLOWLISTS[callerOtter] ?? [];
2384
+ const allowedPaths = allowlist.map((r) => `${r.prefix}*${r.suffix} (${r.description})`);
2385
+ const result = {
2386
+ success: false,
2387
+ error: check.error ?? "Path not allowed",
2388
+ callerOtter,
2389
+ attemptedPath: filePath,
2390
+ allowedPaths
2391
+ };
2392
+ return { text: JSON.stringify(result), isError: true };
2393
+ }
2394
+ const normalized = normalize(filePath);
2395
+ const fullPath = join4(cwd, normalized);
2396
+ if (existsSync4(fullPath)) {
2397
+ try {
2398
+ const stat = lstatSync4(fullPath);
2399
+ if (stat.isSymbolicLink()) {
2400
+ const result = {
2401
+ success: false,
2402
+ error: "Target path is a symlink \u2014 refusing to write through symlinks for security",
2403
+ callerOtter,
2404
+ attemptedPath: filePath,
2405
+ allowedPaths: []
2406
+ };
2407
+ return { text: JSON.stringify(result), isError: true };
2408
+ }
2409
+ } catch {
2410
+ }
2411
+ }
2412
+ const contentError = validateContent(normalized, content);
2413
+ if (contentError) {
2414
+ const result = {
2415
+ success: false,
2416
+ error: `Content validation failed: ${contentError}`,
2417
+ callerOtter,
2418
+ attemptedPath: filePath,
2419
+ allowedPaths: []
2420
+ };
2421
+ return { text: JSON.stringify(result), isError: true };
2422
+ }
2423
+ try {
2424
+ if (createDirectories) {
2425
+ mkdirSync3(dirname(fullPath), { recursive: true });
2426
+ }
2427
+ writeFileSync4(fullPath, content, { encoding: "utf-8" });
2428
+ const result = {
2429
+ success: true,
2430
+ path: normalized,
2431
+ bytesWritten: Buffer.byteLength(content, "utf-8"),
2432
+ allowRule: check.rule ?? "unknown"
2433
+ };
2434
+ return { text: JSON.stringify(result), isError: false };
2435
+ } catch (err) {
2436
+ const message = err instanceof Error ? err.message : String(err);
2437
+ const result = {
2438
+ success: false,
2439
+ error: `Write failed: ${message}`,
2440
+ callerOtter,
2441
+ attemptedPath: filePath,
2442
+ allowedPaths: []
2443
+ };
2444
+ return { text: JSON.stringify(result), isError: true };
2445
+ }
2446
+ }
2447
+ function registerSafeWriteTools(server2) {
2448
+ 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.";
2449
+ server2.tool(
2450
+ "stackwright_pro_safe_write",
2451
+ DESC,
2452
+ {
2453
+ callerOtter: z11.string().describe('The otter agent name requesting the write, e.g. "stackwright-pro-page-otter"'),
2454
+ filePath: z11.string().describe('Relative path from project root, e.g. "pages/dashboard/content.yml"'),
2455
+ content: z11.string().describe("File content to write"),
2456
+ createDirectories: z11.boolean().optional().describe("Create parent directories if they don't exist. Default: true")
2457
+ },
2458
+ async ({ callerOtter, filePath, content, createDirectories }) => {
2459
+ const result = handleSafeWrite({
2460
+ callerOtter,
2461
+ filePath,
2462
+ content,
2463
+ ...createDirectories != null ? { createDirectories } : {}
2464
+ });
2465
+ return { content: [{ type: "text", text: result.text }], isError: result.isError };
2466
+ }
2467
+ );
2468
+ }
2469
+
2470
+ // src/tools/auth.ts
2471
+ import { z as z12 } from "zod";
2472
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync5, existsSync as existsSync5 } from "fs";
2473
+ import { join as join5 } from "path";
2474
+ function buildHierarchy(roles) {
2475
+ const h = {};
2476
+ for (let i = 0; i < roles.length - 1; i++) {
2477
+ h[roles[i]] = roles.slice(i + 1);
2478
+ }
2479
+ return h;
2480
+ }
2481
+ function hierarchyToYaml(hierarchy, indent) {
2482
+ const entries = Object.entries(hierarchy);
2483
+ if (entries.length === 0) return `${indent}{}`;
2484
+ return entries.map(([role, subs]) => `${indent}${role}: [${subs.join(", ")}]`).join("\n");
2485
+ }
2486
+ function rolesToYaml(roles, indent) {
2487
+ return roles.map((r) => `${indent}- ${r}`).join("\n");
2488
+ }
2489
+ function routesToYaml(routes, defaultRole, indent) {
2490
+ return routes.map((r) => `${indent}- pattern: ${r}
2491
+ ${indent} requiredRole: ${defaultRole}`).join("\n");
2492
+ }
2493
+ function upsertAuthBlock(existing, authYaml) {
2494
+ const lines = existing.split("\n");
2495
+ let authStart = -1;
2496
+ let authEnd = lines.length;
2497
+ for (let i = 0; i < lines.length; i++) {
2498
+ if (/^auth:/.test(lines[i])) {
2499
+ authStart = i;
2500
+ } else if (authStart >= 0 && i > authStart && /^\S/.test(lines[i]) && lines[i].trim() !== "") {
2501
+ authEnd = i;
2502
+ break;
2503
+ }
2504
+ }
2505
+ if (authStart < 0) {
2506
+ return existing.trimEnd() + "\n" + authYaml + "\n";
2507
+ }
2508
+ const before = lines.slice(0, authStart);
2509
+ const after = lines.slice(authEnd);
2510
+ return [...before, ...authYaml.trimEnd().split("\n"), ...after.length ? after : []].join("\n");
2511
+ }
2512
+ function generateMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
2513
+ const rbacBlock = ` rbac: {
2514
+ roles: ${JSON.stringify(roles)},
2515
+ defaultRole: '${defaultRole}',
2516
+ hierarchy: ${JSON.stringify(hierarchy, null, 4)},
2517
+ },`;
2518
+ const auditBlock = ` audit: {
2519
+ enabled: ${auditEnabled},
2520
+ retentionDays: ${auditRetentionDays},
2521
+ },`;
2522
+ const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
2523
+ const configBlock = `export const config = {
2524
+ matcher: ${JSON.stringify(protectedRoutes)},
2525
+ };`;
2526
+ if (method === "cac") {
2527
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
2528
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
2529
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
2530
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
2531
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth
2532
+ // \u26A0\uFE0F SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
2533
+ // DoD security officer review required before production deployment.
2534
+ // Verify: CA bundle completeness, EDIPI lookup endpoint, OCSP accessibility.
2535
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
2536
+
2537
+ export const middleware = createProMiddleware({
2538
+ method: 'cac',
2539
+ cac: {
2540
+ caBundle: process.env.CAC_CA_BUNDLE ?? '${caBundle}',
2541
+ edipiLookup: '${edipiLookup}',
2542
+ ocspEndpoint: process.env.CAC_OCSP_ENDPOINT ?? '${ocspEndpoint}',
2543
+ certHeader: '${certHeader}',
2544
+ },
2545
+ ${rbacBlock}
2546
+ ${auditBlock}
2547
+ ${routesBlock}
2548
+ });
2549
+
2550
+ ${configBlock}
2551
+ `;
2552
+ }
2553
+ if (method === "oidc") {
2554
+ const scopes2 = params.oidcScopes ?? "openid profile email";
2555
+ const roleClaim = params.oidcRoleClaim ?? "roles";
2556
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
2557
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
2558
+
2559
+ export const middleware = createProMiddleware({
2560
+ method: 'oidc',
2561
+ oidc: {
2562
+ discoveryUrl: process.env.OIDC_DISCOVERY_URL!,
2563
+ clientId: process.env.OIDC_CLIENT_ID!,
2564
+ clientSecret: process.env.OIDC_CLIENT_SECRET!,
2565
+ scopes: '${scopes2}',
2566
+ roleClaim: '${roleClaim}',
2567
+ },
2568
+ ${rbacBlock}
2569
+ ${auditBlock}
2570
+ ${routesBlock}
2571
+ });
2572
+
2573
+ ${configBlock}
2574
+ `;
2575
+ }
2576
+ const scopes = params.oauth2Scopes ?? "read write";
2577
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
2578
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
2579
+
2580
+ export const middleware = createProMiddleware({
2581
+ method: 'oauth2',
2582
+ oauth2: {
2583
+ authorizationUrl: process.env.OAUTH2_AUTH_URL!,
2584
+ tokenUrl: process.env.OAUTH2_TOKEN_URL!,
2585
+ clientId: process.env.OAUTH2_CLIENT_ID!,
2586
+ clientSecret: process.env.OAUTH2_CLIENT_SECRET!,
2587
+ scopes: '${scopes}',
2588
+ },
2589
+ ${rbacBlock}
2590
+ ${auditBlock}
2591
+ ${routesBlock}
2592
+ });
2593
+
2594
+ ${configBlock}
2595
+ `;
2596
+ }
2597
+ function generateEnvBlock(method, params) {
2598
+ if (method === "cac") {
2599
+ return `# Authentication (CAC/PKI \u2014 DoD)
2600
+ # \u26A0\uFE0F SECURITY REVIEW REQUIRED before production deployment
2601
+ CAC_CA_BUNDLE=./certs/dod-ca-bundle.pem
2602
+ CAC_OCSP_ENDPOINT=https://ocsp.disa.mil
2603
+ `;
2604
+ }
2605
+ if (method === "oidc") {
2606
+ const label = params.provider ?? "OIDC";
2607
+ const discoveryUrl = params.oidcDiscoveryUrl ?? "https://your-provider/.well-known/openid-configuration";
2608
+ return `# Authentication (OIDC \u2014 ${label})
2609
+ OIDC_DISCOVERY_URL=${discoveryUrl}
2610
+ OIDC_CLIENT_ID=your-client-id
2611
+ OIDC_CLIENT_SECRET=your-client-secret
2612
+ `;
2613
+ }
2614
+ const authUrl = params.oauth2AuthUrl ?? "https://your-auth-server/authorize";
2615
+ const tokenUrl = params.oauth2TokenUrl ?? "https://your-auth-server/token";
2616
+ return `# Authentication (OAuth2)
2617
+ OAUTH2_AUTH_URL=${authUrl}
2618
+ OAUTH2_TOKEN_URL=${tokenUrl}
2619
+ OAUTH2_CLIENT_ID=your-client-id
2620
+ OAUTH2_CLIENT_SECRET=your-client-secret
2621
+ `;
2622
+ }
2623
+ function generateYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
2624
+ const rbacSection = ` rbac:
2625
+ roles:
2626
+ ${rolesToYaml(roles, " ")}
2627
+ defaultRole: ${defaultRole}
2628
+ hierarchy:
2629
+ ${hierarchyToYaml(hierarchy, " ")}`;
2630
+ const auditSection = ` audit:
2631
+ enabled: ${auditEnabled}
2632
+ retentionDays: ${auditRetentionDays}`;
2633
+ const routesSection = ` protectedRoutes:
2634
+ ${routesToYaml(protectedRoutes, " ", defaultRole)}`.replace(/\n\s+,/g, "");
2635
+ const routeLines = protectedRoutes.map((r) => ` - pattern: ${r}
2636
+ requiredRole: ${defaultRole}`).join("\n");
2637
+ const providerLine = params.provider ? ` provider: ${params.provider}
2638
+ ` : "";
2639
+ if (method === "cac") {
2640
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
2641
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
2642
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
2643
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
2644
+ return `auth:
2645
+ method: cac
2646
+ ${providerLine} middleware: ./middleware.ts
2647
+ cac:
2648
+ caBundle: \${CAC_CA_BUNDLE}
2649
+ edipiLookup: ${edipiLookup}
2650
+ ocspEndpoint: \${CAC_OCSP_ENDPOINT}
2651
+ certHeader: ${certHeader}
2652
+ ${rbacSection}
2653
+ protectedRoutes:
2654
+ ${routeLines}
2655
+ ${auditSection}
2656
+ `;
2657
+ }
2658
+ if (method === "oidc") {
2659
+ const scopes2 = params.oidcScopes ?? "openid profile email";
2660
+ const roleClaim = params.oidcRoleClaim ?? "roles";
2661
+ return `auth:
2662
+ method: oidc
2663
+ ${providerLine} middleware: ./middleware.ts
2664
+ oidc:
2665
+ discoveryUrl: \${OIDC_DISCOVERY_URL}
2666
+ clientId: \${OIDC_CLIENT_ID}
2667
+ clientSecret: \${OIDC_CLIENT_SECRET}
2668
+ scopes: ${scopes2}
2669
+ roleClaim: ${roleClaim}
2670
+ ${rbacSection}
2671
+ protectedRoutes:
2672
+ ${routeLines}
2673
+ ${auditSection}
2674
+ `;
2675
+ }
2676
+ const scopes = params.oauth2Scopes ?? "read write";
2677
+ return `auth:
2678
+ method: oauth2
2679
+ ${providerLine} middleware: ./middleware.ts
2680
+ oauth2:
2681
+ authorizationUrl: \${OAUTH2_AUTH_URL}
2682
+ tokenUrl: \${OAUTH2_TOKEN_URL}
2683
+ clientId: \${OAUTH2_CLIENT_ID}
2684
+ clientSecret: \${OAUTH2_CLIENT_SECRET}
2685
+ scopes: ${scopes}
2686
+ ${rbacSection}
2687
+ protectedRoutes:
2688
+ ${routeLines}
2689
+ ${auditSection}
2690
+ `;
2691
+ }
2692
+ async function configureAuthHandler(params, cwd) {
2693
+ const {
2694
+ method,
2695
+ provider,
2696
+ rbacRoles = ["SUPER_ADMIN", "ADMIN", "ANALYST"],
2697
+ auditEnabled = true,
2698
+ auditRetentionDays = 90,
2699
+ protectedRoutes = ["/dashboard/:path*"]
2700
+ } = params;
2701
+ const roles = rbacRoles;
2702
+ const defaultRole = params.rbacDefaultRole ?? roles[roles.length - 1];
2703
+ const hierarchy = buildHierarchy(roles);
2704
+ if (method === "none") {
2705
+ return {
2706
+ content: [
2707
+ {
2708
+ type: "text",
2709
+ text: JSON.stringify({
2710
+ success: true,
2711
+ method: "none",
2712
+ provider: null,
2713
+ rbacRoles: roles,
2714
+ rbacDefaultRole: defaultRole,
2715
+ protectedRoutesCount: protectedRoutes.length,
2716
+ filesWritten: [],
2717
+ securityWarning: null
2718
+ })
2719
+ }
2720
+ ]
2721
+ };
2722
+ }
2723
+ const filesWritten = [];
2724
+ try {
2725
+ const middlewareContent = generateMiddlewareContent(
2726
+ method,
2727
+ params,
2728
+ roles,
2729
+ defaultRole,
2730
+ hierarchy,
2731
+ auditEnabled,
2732
+ auditRetentionDays,
2733
+ protectedRoutes
2734
+ );
2735
+ writeFileSync5(join5(cwd, "middleware.ts"), middlewareContent, "utf8");
2736
+ filesWritten.push("middleware.ts");
2737
+ } catch (err) {
2738
+ const msg = err instanceof Error ? err.message : String(err);
2739
+ return {
2740
+ content: [
2741
+ {
2742
+ type: "text",
2743
+ text: JSON.stringify({ success: false, error: `Failed writing middleware.ts: ${msg}` })
2744
+ }
2745
+ ],
2746
+ isError: true
2747
+ };
2748
+ }
2749
+ try {
2750
+ const envBlock = generateEnvBlock(method, params);
2751
+ const envPath = join5(cwd, ".env.example");
2752
+ if (existsSync5(envPath)) {
2753
+ const existing = readFileSync4(envPath, "utf8");
2754
+ writeFileSync5(envPath, existing.trimEnd() + "\n\n" + envBlock, "utf8");
2755
+ } else {
2756
+ writeFileSync5(envPath, envBlock, "utf8");
2757
+ }
2758
+ filesWritten.push(".env.example");
2759
+ } catch (err) {
2760
+ const msg = err instanceof Error ? err.message : String(err);
2761
+ return {
2762
+ content: [
2763
+ {
2764
+ type: "text",
2765
+ text: JSON.stringify({ success: false, error: `Failed writing .env.example: ${msg}` })
2766
+ }
2767
+ ],
2768
+ isError: true
2769
+ };
2770
+ }
2771
+ try {
2772
+ const authYaml = generateYamlBlock(
2773
+ method,
2774
+ params,
2775
+ roles,
2776
+ defaultRole,
2777
+ hierarchy,
2778
+ auditEnabled,
2779
+ auditRetentionDays,
2780
+ protectedRoutes
2781
+ );
2782
+ const ymlPath = join5(cwd, "stackwright.yml");
2783
+ if (!existsSync5(ymlPath)) {
2784
+ writeFileSync5(ymlPath, authYaml, "utf8");
2785
+ } else {
2786
+ const existing = readFileSync4(ymlPath, "utf8");
2787
+ writeFileSync5(ymlPath, upsertAuthBlock(existing, authYaml), "utf8");
2788
+ }
2789
+ filesWritten.push("stackwright.yml");
2790
+ } catch (err) {
2791
+ const msg = err instanceof Error ? err.message : String(err);
2792
+ return {
2793
+ content: [
2794
+ {
2795
+ type: "text",
2796
+ text: JSON.stringify({ success: false, error: `Failed writing stackwright.yml: ${msg}` })
2797
+ }
2798
+ ],
2799
+ isError: true
2800
+ };
2801
+ }
2802
+ const securityWarning = method === "cac" ? "SECURITY REVIEW REQUIRED \u2014 CAC certificate chain must be verified before production deployment" : null;
2803
+ return {
2804
+ content: [
2805
+ {
2806
+ type: "text",
2807
+ text: JSON.stringify({
2808
+ success: true,
2809
+ method,
2810
+ provider: provider ?? null,
2811
+ rbacRoles: roles,
2812
+ rbacDefaultRole: defaultRole,
2813
+ protectedRoutesCount: protectedRoutes.length,
2814
+ filesWritten,
2815
+ securityWarning
2816
+ })
2817
+ }
2818
+ ]
2819
+ };
2820
+ }
2821
+ function registerAuthTools(server2) {
2822
+ server2.tool(
2823
+ "stackwright_pro_configure_auth",
2824
+ "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.",
2825
+ {
2826
+ method: z12.enum(["cac", "oidc", "oauth2", "none"]),
2827
+ provider: z12.enum(["azure-ad", "okta", "ping", "cognito", "custom"]).optional(),
2828
+ // CAC
2829
+ cacCaBundle: z12.string().optional(),
2830
+ cacEdipiLookup: z12.string().optional(),
2831
+ cacOcspEndpoint: z12.string().optional(),
2832
+ cacCertHeader: z12.string().optional(),
2833
+ // OIDC
2834
+ oidcDiscoveryUrl: z12.string().optional(),
2835
+ oidcClientId: z12.string().optional(),
2836
+ oidcClientSecret: z12.string().optional(),
2837
+ oidcScopes: z12.string().optional(),
2838
+ oidcRoleClaim: z12.string().optional(),
2839
+ // OAuth2
2840
+ oauth2AuthUrl: z12.string().optional(),
2841
+ oauth2TokenUrl: z12.string().optional(),
2842
+ oauth2ClientId: z12.string().optional(),
2843
+ oauth2ClientSecret: z12.string().optional(),
2844
+ oauth2Scopes: z12.string().optional(),
2845
+ // RBAC
2846
+ rbacRoles: jsonCoerce(z12.array(z12.string()).optional()),
2847
+ rbacDefaultRole: z12.string().optional(),
2848
+ // Audit
2849
+ auditEnabled: boolCoerce(z12.boolean().optional()),
2850
+ auditRetentionDays: numCoerce(z12.number().int().positive().optional()),
2851
+ // Routes
2852
+ protectedRoutes: jsonCoerce(z12.array(z12.string()).optional()),
2853
+ // Injection for tests
2854
+ _cwd: z12.string().optional()
2855
+ },
2856
+ async (params) => {
2857
+ const cwd = params._cwd ?? process.cwd();
2858
+ return configureAuthHandler(params, cwd);
2859
+ }
2860
+ );
2861
+ }
2862
+
2863
+ // src/integrity.ts
2864
+ import { createHash as createHash2, timingSafeEqual } from "crypto";
2865
+ import { readFileSync as readFileSync5, readdirSync, lstatSync as lstatSync5 } from "fs";
2866
+ import { join as join6, basename } from "path";
2867
+ var _checksums = /* @__PURE__ */ new Map([
2868
+ [
2869
+ "stackwright-pro-api-otter.json",
2870
+ "f1cc9edf2dd1df3ebcea1d0ab33d17a358faaf8aa97ee232cd7994042f2eac0d"
2871
+ ],
2872
+ [
2873
+ "stackwright-pro-auth-otter.json",
2874
+ "a19e06c503209a8a35fe321d30448623545b36b48c47a6ec064d13406ad1f725"
2875
+ ],
2876
+ [
2877
+ "stackwright-pro-dashboard-otter.json",
2878
+ "b3cb3d7554f2e9eed3b57d5e0e3bf85d6ba5b4db5d3af5514391cf0575fcc001"
2879
+ ],
2880
+ [
2881
+ "stackwright-pro-data-otter.json",
2882
+ "bfacb87ae82867472a75982215554336a105a658d6cd3dd2c8b819fa1e11d7ac"
2883
+ ],
2884
+ [
2885
+ "stackwright-pro-designer-otter.json",
2886
+ "c58fa7c7ead9e6398074e1c7ce3f31a8ef4eb3679f5fa18cc03cae3a87878c88"
2887
+ ],
2888
+ [
2889
+ "stackwright-pro-foreman-otter.json",
2890
+ "f52264c1f6297b72f3da6d92d41b6d63356db776242caeab25571e6a8df628e4"
2891
+ ],
2892
+ [
2893
+ "stackwright-pro-page-otter.json",
2894
+ "65bec3a3a0dda6b7591bba2de9399f1e3a4fb99cfe1075342f4f4be98d917b67"
2895
+ ],
2896
+ [
2897
+ "stackwright-pro-theme-otter.json",
2898
+ "1f182326f1acd3d4091a38c7012085cbb4945893e95be4ca3de72318ad092767"
2899
+ ],
2900
+ [
2901
+ "stackwright-pro-workflow-otter.json",
2902
+ "0eec9d6a731678cf547c2a7b0b6fc338ca143c35501365a1e4e5dd2779dd5510"
2903
+ ]
2904
+ ]);
2905
+ Object.freeze(_checksums);
2906
+ var CANONICAL_CHECKSUMS = _checksums;
2907
+ var SHA256_HEX_RE = /^[0-9a-f]{64}$/;
2908
+ for (const [name, digest] of CANONICAL_CHECKSUMS) {
2909
+ if (!SHA256_HEX_RE.test(digest)) {
2910
+ throw new Error(
2911
+ `Malformed SHA-256 in CANONICAL_CHECKSUMS for "${name}": expected 64 hex chars, got ${digest.length}: "${digest}"`
2912
+ );
2913
+ }
2914
+ }
2915
+ var MAX_OTTER_BYTES = 1 * 1024 * 1024;
2916
+ function computeSha256(data) {
2917
+ return createHash2("sha256").update(data).digest("hex");
2918
+ }
2919
+ function safeEqual(a, b) {
2920
+ if (a.length !== b.length) return false;
2921
+ return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
2922
+ }
2923
+ function verifyOtterFile(filePath) {
2924
+ const filename = basename(filePath);
2925
+ const expected = CANONICAL_CHECKSUMS.get(filename);
2926
+ if (expected === void 0) {
2927
+ return { verified: false, filename, error: `Unknown otter file: not in canonical set` };
2928
+ }
2929
+ let stat;
2930
+ try {
2931
+ stat = lstatSync5(filePath);
2932
+ } catch (err) {
2933
+ const msg = err instanceof Error ? err.message : String(err);
2934
+ return { verified: false, filename, error: `Cannot stat file: ${msg}` };
2935
+ }
2936
+ if (stat.isSymbolicLink()) {
2937
+ return { verified: false, filename, error: "Refusing to verify symlink" };
2938
+ }
2939
+ const size = stat.size;
2940
+ if (size > MAX_OTTER_BYTES) {
2941
+ return {
2942
+ verified: false,
2943
+ filename,
2944
+ error: `File exceeds size limit (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${size.toLocaleString()})`
2945
+ };
2946
+ }
2947
+ let raw;
2948
+ try {
2949
+ raw = readFileSync5(filePath);
2950
+ } catch (err) {
2951
+ const msg = err instanceof Error ? err.message : String(err);
2952
+ return { verified: false, filename, error: `Cannot read file: ${msg}` };
2953
+ }
2954
+ if (raw.length > MAX_OTTER_BYTES) {
2955
+ return {
2956
+ verified: false,
2957
+ filename,
2958
+ error: `File exceeds size limit after read (${MAX_OTTER_BYTES.toLocaleString()} bytes, got ${raw.length.toLocaleString()})`
2959
+ };
2960
+ }
2961
+ const actual = computeSha256(raw);
2962
+ if (!safeEqual(actual, expected)) {
2963
+ return {
2964
+ verified: false,
2965
+ filename,
2966
+ error: `SHA-256 mismatch: expected ${expected.substring(0, 8)}\u2026, got ${actual.substring(0, 8)}\u2026`
2967
+ };
2968
+ }
2969
+ try {
2970
+ const decoder = new TextDecoder("utf-8", { fatal: true });
2971
+ decoder.decode(raw);
2972
+ } catch {
2973
+ return {
2974
+ verified: false,
2975
+ filename,
2976
+ error: "File is not valid UTF-8 \u2014 may be corrupted or contain binary injection"
2977
+ };
2978
+ }
2979
+ return { verified: true, filename };
2980
+ }
2981
+ function verifyAllOtters(otterDir) {
2982
+ const verified = [];
2983
+ const failed = [];
2984
+ const unknown = [];
2985
+ let entries;
2986
+ try {
2987
+ entries = readdirSync(otterDir);
2988
+ } catch (err) {
2989
+ const msg = err instanceof Error ? err.message : String(err);
2990
+ return {
2991
+ verified: [],
2992
+ failed: [{ filename: "<directory>", error: `Cannot read directory: ${msg}` }],
2993
+ unknown: []
2994
+ };
2995
+ }
2996
+ const otterFiles = entries.filter((f) => f.endsWith("-otter.json"));
2997
+ for (const filename of otterFiles) {
2998
+ const filePath = join6(otterDir, filename);
2999
+ try {
3000
+ if (lstatSync5(filePath).isSymbolicLink()) {
3001
+ failed.push({ filename, error: "Skipped: symlink" });
3002
+ continue;
3003
+ }
3004
+ } catch {
3005
+ }
3006
+ const result = verifyOtterFile(filePath);
3007
+ if (result.verified) {
3008
+ verified.push(result.filename);
3009
+ } else if (result.error?.startsWith("Unknown otter file")) {
3010
+ unknown.push(result.filename);
3011
+ } else {
3012
+ failed.push({ filename: result.filename, error: result.error ?? "Unknown error" });
3013
+ }
3014
+ }
3015
+ for (const canonicalName of CANONICAL_CHECKSUMS.keys()) {
3016
+ if (!otterFiles.includes(canonicalName)) {
3017
+ failed.push({ filename: canonicalName, error: "Missing from directory" });
3018
+ }
3019
+ }
3020
+ return { verified, failed, unknown };
3021
+ }
3022
+ var DEFAULT_SEARCH_PATHS = ["node_modules/@stackwright-pro/otters/src/", "packages/otters/src/"];
3023
+ function resolveOtterDir() {
3024
+ const cwd = process.cwd();
3025
+ for (const relative of DEFAULT_SEARCH_PATHS) {
3026
+ const candidate = join6(cwd, relative);
3027
+ try {
3028
+ lstatSync5(candidate);
3029
+ return candidate;
3030
+ } catch {
3031
+ }
3032
+ }
3033
+ return null;
3034
+ }
3035
+ function registerIntegrityTools(server2) {
3036
+ server2.tool(
3037
+ "stackwright_pro_verify_otter_integrity",
3038
+ "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.",
3039
+ {},
3040
+ async () => {
3041
+ const resolved = resolveOtterDir();
3042
+ if (!resolved) {
3043
+ return {
3044
+ content: [
3045
+ {
3046
+ type: "text",
3047
+ text: JSON.stringify({
3048
+ error: true,
3049
+ message: "Could not locate otter directory. Searched: " + DEFAULT_SEARCH_PATHS.join(", ")
3050
+ })
3051
+ }
3052
+ ],
3053
+ isError: true
3054
+ };
3055
+ }
3056
+ const result = verifyAllOtters(resolved);
3057
+ const allGood = result.failed.length === 0 && result.unknown.length === 0;
3058
+ return {
3059
+ content: [
3060
+ {
3061
+ type: "text",
3062
+ text: JSON.stringify({
3063
+ otterDir: resolved,
3064
+ totalCanonical: CANONICAL_CHECKSUMS.size,
3065
+ verifiedCount: result.verified.length,
3066
+ failedCount: result.failed.length,
3067
+ unknownCount: result.unknown.length,
3068
+ verified: result.verified,
3069
+ failed: result.failed,
3070
+ unknown: result.unknown,
3071
+ warning: result.failed.length > 0 ? "SHA-256 mismatches detected (non-blocking). PKI-signed manifest support coming soon." : void 0
3072
+ })
3073
+ }
3074
+ ],
3075
+ isError: false
3076
+ };
3077
+ }
3078
+ );
3079
+ }
3080
+
3081
+ // src/tools/domain.ts
3082
+ import { z as z13 } from "zod";
3083
+ import { readFileSync as readFileSync6, existsSync as existsSync6 } from "fs";
3084
+ import { join as join7 } from "path";
3085
+ function handleListCollections(input) {
3086
+ const cwd = input._cwd ?? process.cwd();
3087
+ const sources = [
3088
+ {
3089
+ path: join7(cwd, ".stackwright", "artifacts", "data-config.json"),
3090
+ source: "data-config.json",
3091
+ parse: (raw) => {
3092
+ const parsed = JSON.parse(raw);
3093
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
3094
+ return [];
3095
+ }
3096
+ return extractCollectionsFromArtifact(parsed);
3097
+ }
3098
+ },
3099
+ {
3100
+ path: join7(cwd, "stackwright.yml"),
3101
+ source: "stackwright.yml",
3102
+ parse: extractCollectionsFromYaml
3103
+ }
3104
+ ];
3105
+ for (const { path: path3, source, parse } of sources) {
3106
+ if (!existsSync6(path3)) continue;
3107
+ try {
3108
+ const collections = parse(readFileSync6(path3, "utf8"));
3109
+ return {
3110
+ text: JSON.stringify({ collections, source, collectionCount: collections.length }),
3111
+ isError: false
3112
+ };
3113
+ } catch {
3114
+ }
3115
+ }
3116
+ return {
3117
+ text: JSON.stringify({
3118
+ collections: [],
3119
+ source: "none",
3120
+ collectionCount: 0,
3121
+ hint: "Run API Otter and Data Otter first"
3122
+ }),
3123
+ isError: false
3124
+ };
3125
+ }
3126
+ function extractCollectionsFromArtifact(raw) {
3127
+ const collections = [];
3128
+ const integrations = raw.integrations ?? raw.collections ?? [];
3129
+ if (!Array.isArray(integrations)) return collections;
3130
+ for (const item of integrations) {
3131
+ if (!item || typeof item !== "object") continue;
3132
+ const obj = item;
3133
+ if (typeof obj.name === "string" && typeof obj.endpoint === "string") {
3134
+ collections.push(makeCollectionInfo(obj.name, obj.endpoint, obj.type));
3135
+ continue;
3136
+ }
3137
+ if (!Array.isArray(obj.collections)) continue;
3138
+ for (const col of obj.collections) {
3139
+ if (!col || typeof col !== "object") continue;
3140
+ const c = col;
3141
+ if (typeof c.name === "string" && typeof c.endpoint === "string") {
3142
+ collections.push(makeCollectionInfo(c.name, c.endpoint, c.type ?? obj.type));
3143
+ }
3144
+ }
3145
+ }
3146
+ return collections;
3147
+ }
3148
+ function makeCollectionInfo(name, endpoint, type) {
3149
+ return { name, endpoint, ...typeof type === "string" ? { type } : {} };
3150
+ }
3151
+ function extractCollectionsFromYaml(yamlText) {
3152
+ const collections = [];
3153
+ const lines = yamlText.split("\n");
3154
+ let inIntegrations = false;
3155
+ let currentName = null;
3156
+ let currentEndpoint = null;
3157
+ let currentType = null;
3158
+ for (const line of lines) {
3159
+ if (line.length > 1e3) continue;
3160
+ if (/^integrations:\s*$/.test(line)) {
3161
+ inIntegrations = true;
3162
+ continue;
3163
+ }
3164
+ if (inIntegrations && /^[a-z]/.test(line) && !line.startsWith(" ")) {
3165
+ inIntegrations = false;
3166
+ }
3167
+ if (!inIntegrations) continue;
3168
+ const stripQuotes = (s) => s.trim().replace(/^['"]|['"]$/g, "");
3169
+ const typeMatch = line.match(/^\s+type:\s*(.+)$/);
3170
+ if (typeMatch?.[1]) currentType = stripQuotes(typeMatch[1]);
3171
+ const nameMatch = line.match(/^[\s-]+name:\s*(.+)$/);
3172
+ if (nameMatch?.[1]) {
3173
+ if (currentName && currentEndpoint) {
3174
+ collections.push(makeCollectionInfo(currentName, currentEndpoint, currentType));
3175
+ }
3176
+ currentName = stripQuotes(nameMatch[1]);
3177
+ currentEndpoint = null;
3178
+ }
3179
+ const endpointMatch = line.match(/^\s+endpoint:\s*(.+)$/);
3180
+ if (endpointMatch?.[1]) currentEndpoint = stripQuotes(endpointMatch[1]);
3181
+ }
3182
+ if (currentName && currentEndpoint) {
3183
+ collections.push(makeCollectionInfo(currentName, currentEndpoint, currentType));
3184
+ }
3185
+ return collections;
3186
+ }
3187
+ var DATA_STRATEGIES = {
3188
+ "pulse-fast": {
3189
+ strategy: "pulse-fast",
3190
+ mechanism: "Client-side polling via @stackwright-pro/pulse",
3191
+ mechanismPackage: "@stackwright-pro/pulse",
3192
+ pulse: true,
3193
+ requiredPackages: { "@stackwright-pro/pulse": "latest", "@tanstack/react-query": "^5.0.0" },
3194
+ handoffFlags: ["PULSE_MODE=true"],
3195
+ description: "Real-time updates every few seconds. Uses client-side polling. Dashboard Otter should use *_pulse component variants."
3196
+ },
3197
+ "isr-fast": {
3198
+ strategy: "isr-fast",
3199
+ mechanism: "Next.js ISR",
3200
+ revalidateSeconds: 60,
3201
+ pulse: false,
3202
+ requiredPackages: {},
3203
+ handoffFlags: [],
3204
+ description: "Near real-time with 60-second ISR revalidation. Good for dashboards that need minute-level freshness."
3205
+ },
3206
+ "isr-standard": {
3207
+ strategy: "isr-standard",
3208
+ mechanism: "Next.js ISR",
3209
+ revalidateSeconds: 3600,
3210
+ pulse: false,
3211
+ requiredPackages: {},
3212
+ handoffFlags: [],
3213
+ description: "Standard hourly revalidation. Good for most API-backed pages."
3214
+ },
3215
+ "isr-slow": {
3216
+ strategy: "isr-slow",
3217
+ mechanism: "Next.js ISR",
3218
+ revalidateSeconds: 86400,
3219
+ pulse: false,
3220
+ requiredPackages: {},
3221
+ handoffFlags: [],
3222
+ description: "Daily revalidation. Good for infrequently changing data."
3223
+ }
3224
+ };
3225
+ function handleResolveDataStrategy(input) {
3226
+ const key = input.strategy.trim().toLowerCase();
3227
+ const match = DATA_STRATEGIES[key];
3228
+ if (!match) {
3229
+ const validKeys = Object.keys(DATA_STRATEGIES).join(", ");
3230
+ return {
3231
+ text: JSON.stringify({
3232
+ error: true,
3233
+ message: `Unknown strategy: "${input.strategy}". Valid strategies: ${validKeys}`,
3234
+ validStrategies: Object.keys(DATA_STRATEGIES)
3235
+ }),
3236
+ isError: true
3237
+ };
3238
+ }
3239
+ const configureIsrCall = match.pulse ? null : {
3240
+ tool: "stackwright_pro_configure_isr_batch",
3241
+ args: {
3242
+ collections: [{ name: "$COLLECTION", revalidateSeconds: match.revalidateSeconds }]
3243
+ }
3244
+ };
3245
+ return {
3246
+ text: JSON.stringify({ ...match, configureIsrCall }),
3247
+ isError: false
3248
+ };
3249
+ }
3250
+ function fail(errors) {
3251
+ return { text: JSON.stringify({ valid: false, errors, warnings: [] }), isError: true };
3252
+ }
3253
+ function handleValidateWorkflow(input) {
3254
+ const cwd = input._cwd ?? process.cwd();
3255
+ let raw;
3256
+ if (input.workflow && Object.keys(input.workflow).length > 0) {
3257
+ raw = input.workflow;
3258
+ } else {
3259
+ const artifactPath = join7(cwd, ".stackwright", "artifacts", "workflow-config.json");
3260
+ if (!existsSync6(artifactPath)) {
3261
+ return fail([
3262
+ {
3263
+ code: "NO_WORKFLOW",
3264
+ message: "No workflow provided and .stackwright/artifacts/workflow-config.json not found. Pass a workflow object or run the workflow otter first."
3265
+ }
3266
+ ]);
3267
+ }
3268
+ try {
3269
+ raw = JSON.parse(readFileSync6(artifactPath, "utf8"));
3270
+ } catch (err) {
3271
+ return fail([{ code: "INVALID_JSON", message: `Failed to parse workflow artifact: ${err}` }]);
3272
+ }
3273
+ }
3274
+ const workflow = raw.workflow && typeof raw.workflow === "object" ? raw.workflow : raw;
3275
+ const errors = [];
3276
+ const warnings = [];
3277
+ if (typeof workflow.id !== "string" || !workflow.id) {
3278
+ errors.push({ code: "MISSING_ID", message: "workflow.id is required", path: "workflow.id" });
3279
+ } else if (!/^[a-z0-9-]+$/.test(workflow.id)) {
3280
+ errors.push({
3281
+ code: "INVALID_ID",
3282
+ message: `workflow.id "${workflow.id}" must match ^[a-z0-9-]+$`,
3283
+ path: "workflow.id"
3284
+ });
3285
+ }
3286
+ if (typeof workflow.label !== "string" || !workflow.label) {
3287
+ errors.push({
3288
+ code: "MISSING_LABEL",
3289
+ message: "workflow.label is required",
3290
+ path: "workflow.label"
3291
+ });
3292
+ }
3293
+ const steps = workflow.steps;
3294
+ if (!Array.isArray(steps)) {
3295
+ errors.push({
3296
+ code: "MISSING_STEPS",
3297
+ message: "workflow.steps must be an array",
3298
+ path: "workflow.steps"
3299
+ });
3300
+ return { text: JSON.stringify({ valid: false, errors, warnings }), isError: false };
3301
+ }
3302
+ if (steps.length < 2) {
3303
+ errors.push({
3304
+ code: "TOO_FEW_STEPS",
3305
+ message: "A workflow must have at least 2 steps",
3306
+ path: "workflow.steps"
3307
+ });
3308
+ }
3309
+ const stepIds = /* @__PURE__ */ new Set();
3310
+ const duplicateIds = [];
3311
+ for (const step of steps) {
3312
+ if (!step || typeof step !== "object") continue;
3313
+ const id = step.id;
3314
+ if (typeof id !== "string" || !id) {
3315
+ errors.push({
3316
+ code: "MISSING_STEP_ID",
3317
+ message: "Every step must have an id",
3318
+ path: "workflow.steps"
3319
+ });
3320
+ continue;
3321
+ }
3322
+ if (!/^[a-z0-9_]+$/.test(id)) {
3323
+ errors.push({
3324
+ code: "INVALID_STEP_ID",
3325
+ message: `Step ID "${id}" must match ^[a-z0-9_]+$`,
3326
+ path: `workflow.steps[${id}].id`
3327
+ });
3328
+ }
3329
+ if (stepIds.has(id)) duplicateIds.push(id);
3330
+ stepIds.add(id);
3331
+ }
3332
+ if (duplicateIds.length > 0) {
3333
+ errors.push({
3334
+ code: "DUPLICATE_STEP_IDS",
3335
+ message: `Duplicate step IDs: ${duplicateIds.join(", ")}`,
3336
+ path: "workflow.steps"
3337
+ });
3338
+ }
3339
+ const initialStep = workflow.initial_step;
3340
+ if (typeof initialStep !== "string" || !initialStep) {
3341
+ errors.push({
3342
+ code: "MISSING_INITIAL_STEP",
3343
+ message: "workflow.initial_step is required",
3344
+ path: "workflow.initial_step"
3345
+ });
3346
+ } else if (!stepIds.has(initialStep)) {
3347
+ errors.push({
3348
+ code: "INVALID_INITIAL_STEP",
3349
+ message: `initial_step "${initialStep}" does not reference an existing step. Valid: ${[...stepIds].join(", ")}`,
3350
+ path: "workflow.initial_step"
3351
+ });
3352
+ }
3353
+ for (const step of steps) {
3354
+ if (!step || typeof step !== "object") continue;
3355
+ const s = step;
3356
+ const stepId = String(s.id ?? "??");
3357
+ validateTransitionTargets(s, stepId, stepIds, errors);
3358
+ collectServiceWarnings(s, stepId, warnings);
3359
+ }
3360
+ if (typeof workflow.persistence === "string" && workflow.persistence.startsWith("service:")) {
3361
+ warnings.push({
3362
+ code: "WARN_SERVICE_REFERENCE",
3363
+ message: 'service: reference at "workflow.persistence" requires @stackwright-pro/services. Prism mock fallback will be used until services layer is configured.',
3364
+ path: "workflow.persistence"
3365
+ });
3366
+ }
3367
+ const hasTerminal = steps.some((step) => {
3368
+ if (!step || typeof step !== "object") return false;
3369
+ return step.type === "terminal";
3370
+ });
3371
+ if (!hasTerminal) {
3372
+ errors.push({
3373
+ code: "NO_TERMINAL_STATE",
3374
+ message: "Workflow must have at least one step with type: terminal",
3375
+ path: "workflow.steps"
3376
+ });
3377
+ }
3378
+ return { text: JSON.stringify({ valid: errors.length === 0, errors, warnings }), isError: false };
3379
+ }
3380
+ function validateTransitionTargets(step, stepId, stepIds, errors) {
3381
+ const check = (target, path3) => {
3382
+ if (typeof target === "string" && !stepIds.has(target)) {
3383
+ errors.push({
3384
+ code: "ORPHANED_TRANSITION",
3385
+ message: `Step "${stepId}" transitions to "${target}" which does not exist`,
3386
+ path: path3
3387
+ });
3388
+ }
3389
+ };
3390
+ const onSubmit = step.on_submit;
3391
+ if (onSubmit && typeof onSubmit === "object") {
3392
+ check(onSubmit.transition, `workflow.steps[${stepId}].on_submit.transition`);
3393
+ }
3394
+ if (Array.isArray(step.actions)) {
3395
+ for (const action of step.actions) {
3396
+ if (!action || typeof action !== "object") continue;
3397
+ const a = action;
3398
+ check(a.transition, `workflow.steps[${stepId}].actions[${a.id ?? "??"}].transition`);
3399
+ }
3400
+ }
3401
+ if (Array.isArray(step.conditions)) {
3402
+ for (const cond of step.conditions) {
3403
+ if (!cond || typeof cond !== "object") continue;
3404
+ const then = cond.then;
3405
+ if (then && typeof then === "object") {
3406
+ check(then.transition, `workflow.steps[${stepId}].conditions`);
3407
+ }
3408
+ }
3409
+ }
3410
+ if (Array.isArray(step.show_fields_from)) {
3411
+ for (const ref of step.show_fields_from)
3412
+ check(ref, `workflow.steps[${stepId}].show_fields_from`);
3413
+ }
3414
+ const display = step.display;
3415
+ if (display && typeof display === "object") {
3416
+ check(display.source_step, `workflow.steps[${stepId}].display.source_step`);
3417
+ if (Array.isArray(display.source_steps)) {
3418
+ for (const ref of display.source_steps)
3419
+ check(ref, `workflow.steps[${stepId}].display.source_steps`);
3420
+ }
3421
+ }
3422
+ }
3423
+ function collectServiceWarnings(step, stepId, warnings) {
3424
+ const isService = (val) => typeof val === "string" && val.startsWith("service:");
3425
+ const warn = (path3) => {
3426
+ warnings.push({
3427
+ code: "WARN_SERVICE_REFERENCE",
3428
+ message: `service: reference at "${path3}" requires @stackwright-pro/services. Prism mock fallback will be used until services layer is configured.`,
3429
+ path: path3
3430
+ });
3431
+ };
3432
+ const onSubmit = step.on_submit;
3433
+ if (onSubmit && typeof onSubmit === "object" && isService(onSubmit.action))
3434
+ warn(`${stepId}.on_submit.action`);
3435
+ const onEnter = step.on_enter;
3436
+ if (onEnter && typeof onEnter === "object" && isService(onEnter.action))
3437
+ warn(`${stepId}.on_enter.action`);
3438
+ if (Array.isArray(step.actions)) {
3439
+ for (const action of step.actions) {
3440
+ if (!action || typeof action !== "object") continue;
3441
+ const a = action;
3442
+ if (isService(a.action)) warn(`${stepId}.actions.${a.id ?? "??"}.action`);
3443
+ }
3444
+ }
3445
+ if (Array.isArray(step.fields)) {
3446
+ for (const field of step.fields) {
3447
+ if (!field || typeof field !== "object") continue;
3448
+ const f = field;
3449
+ if (isService(f.data_source)) warn(`${stepId}.fields.${f.name ?? "??"}.data_source`);
3450
+ }
3451
+ }
3452
+ }
3453
+ function registerDomainTools(server2) {
3454
+ const res = (r) => ({
3455
+ content: [{ type: "text", text: r.text }],
3456
+ isError: r.isError
3457
+ });
3458
+ server2.tool(
3459
+ "stackwright_pro_list_collections",
3460
+ "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.",
3461
+ {},
3462
+ async () => res(handleListCollections({}))
3463
+ );
3464
+ server2.tool(
3465
+ "stackwright_pro_resolve_data_strategy",
3466
+ "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.",
3467
+ {
3468
+ strategy: z13.string().describe(
3469
+ 'The data-1 answer value: "pulse-fast", "isr-fast", "isr-standard", or "isr-slow"'
3470
+ )
3471
+ },
3472
+ async ({ strategy }) => res(handleResolveDataStrategy({ strategy }))
3473
+ );
3474
+ server2.tool(
3475
+ "stackwright_pro_validate_workflow",
3476
+ "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.",
3477
+ {
3478
+ workflow: jsonCoerce(z13.record(z13.string(), z13.unknown()).optional()).describe(
3479
+ "Parsed workflow object. If omitted, reads from .stackwright/artifacts/workflow-config.json"
3480
+ )
3481
+ },
3482
+ async ({ workflow }) => res(handleValidateWorkflow(workflow ? { workflow } : {}))
3483
+ );
3484
+ }
3485
+
3486
+ // package.json
3487
+ var package_default = {
3488
+ dependencies: {
3489
+ "@modelcontextprotocol/sdk": "^1.10.0",
3490
+ "@stackwright-pro/cli-data-explorer": "workspace:*",
3491
+ zod: "^4.3.6"
3492
+ },
3493
+ devDependencies: {
3494
+ "@types/node": "^24.1.0",
3495
+ tsup: "^8.5.0",
3496
+ typescript: "^5.8.3",
3497
+ vitest: "^4.0.18"
3498
+ },
3499
+ scripts: {
3500
+ prepublishOnly: "node scripts/verify-integrity-sync.js",
3501
+ build: "tsup",
3502
+ dev: "tsup --watch",
3503
+ start: "node dist/server.js",
3504
+ test: "vitest run",
3505
+ "test:coverage": "vitest run --coverage"
3506
+ },
3507
+ name: "@stackwright-pro/mcp",
3508
+ version: "0.2.0-alpha.13",
3509
+ description: "MCP tools for Stackwright Pro - Data Explorer, Security, ISR, and Dashboard generation",
3510
+ license: "PROPRIETARY",
3511
+ main: "./dist/server.js",
3512
+ module: "./dist/server.mjs",
3513
+ types: "./dist/server.d.ts",
3514
+ exports: {
3515
+ ".": {
3516
+ types: "./dist/server.d.ts",
3517
+ import: "./dist/server.mjs",
3518
+ require: "./dist/server.js"
3519
+ },
3520
+ "./integrity": {
3521
+ types: "./dist/integrity.d.ts",
3522
+ import: "./dist/integrity.mjs",
3523
+ require: "./dist/integrity.js"
1213
3524
  }
1214
3525
  },
1215
3526
  files: [
@@ -1231,6 +3542,13 @@ registerIsrTools(server);
1231
3542
  registerDashboardTools(server);
1232
3543
  registerClarificationTools(server);
1233
3544
  registerPackageTools(server);
3545
+ registerQuestionTools(server);
3546
+ registerOrchestrationTools(server);
3547
+ registerPipelineTools(server);
3548
+ registerSafeWriteTools(server);
3549
+ registerAuthTools(server);
3550
+ registerIntegrityTools(server);
3551
+ registerDomainTools(server);
1234
3552
  async function main() {
1235
3553
  const transport = new StdioServerTransport();
1236
3554
  await server.connect(transport);