@stackwright-pro/mcp 0.2.0-alpha.4 → 0.2.0-alpha.5

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