@stackwright-pro/mcp 0.2.0-alpha.6 → 0.2.0-alpha.61

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.js CHANGED
@@ -27,15 +27,44 @@ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
27
27
  var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
28
28
 
29
29
  // src/tools/data-explorer.ts
30
- var import_zod = require("zod");
30
+ var import_zod2 = require("zod");
31
31
  var import_cli_data_explorer = require("@stackwright-pro/cli-data-explorer");
32
+
33
+ // src/coerce.ts
34
+ var import_zod = require("zod");
35
+ function jsonCoerce(schema) {
36
+ return import_zod.z.preprocess((v) => {
37
+ if (typeof v === "string") {
38
+ try {
39
+ return JSON.parse(v);
40
+ } catch {
41
+ return v;
42
+ }
43
+ }
44
+ return v;
45
+ }, schema);
46
+ }
47
+ function boolCoerce(schema) {
48
+ return import_zod.z.preprocess((v) => v === "true" ? true : v === "false" ? false : v, schema);
49
+ }
50
+ function numCoerce(schema) {
51
+ return import_zod.z.preprocess((v) => {
52
+ if (typeof v === "string" && v.trim() !== "") {
53
+ const n = Number(v);
54
+ if (!Number.isNaN(n)) return n;
55
+ }
56
+ return v;
57
+ }, schema);
58
+ }
59
+
60
+ // src/tools/data-explorer.ts
32
61
  function registerDataExplorerTools(server2) {
33
62
  server2.tool(
34
63
  "stackwright_pro_list_entities",
35
64
  "List all available API entities from OpenAPI specs or generated Zod schemas. Use this to discover what entities are available before generating endpoint filters. Returns entity names, endpoints, and field counts. Part of the Pro Otter Raft for building API-integrated Stackwright applications.",
36
65
  {
37
- specPath: import_zod.z.string().optional().describe("Path to OpenAPI spec file (YAML or JSON)"),
38
- projectRoot: import_zod.z.string().optional().describe("Project root directory (auto-detected if omitted)")
66
+ specPath: import_zod2.z.string().optional().describe("Path to OpenAPI spec file (YAML or JSON)"),
67
+ projectRoot: import_zod2.z.string().optional().describe("Project root directory (auto-detected if omitted)")
39
68
  },
40
69
  async ({ specPath, projectRoot }) => {
41
70
  const result = (0, import_cli_data_explorer.listEntities)({
@@ -83,9 +112,13 @@ function registerDataExplorerTools(server2) {
83
112
  "stackwright_pro_generate_filter",
84
113
  "Generate endpoint filter configuration from selected entities. Creates include/exclude patterns for stackwright.yml OpenAPI integration. Use this after stackwright_pro_list_entities to select which API endpoints the application needs. Only selected endpoints will generate client code, reducing bundle size and improving security.",
85
114
  {
86
- selectedEntities: import_zod.z.array(import_zod.z.string()).describe('Entity slugs to include (e.g., ["equipment", "supplies"])'),
87
- excludePatterns: import_zod.z.array(import_zod.z.string()).optional().describe('Glob patterns to exclude (e.g., ["/admin/**", "/reports/**"])'),
88
- projectRoot: import_zod.z.string().optional().describe("Project root directory")
115
+ selectedEntities: jsonCoerce(import_zod2.z.array(import_zod2.z.string())).describe(
116
+ 'Entity slugs to include (e.g., ["equipment", "supplies"])'
117
+ ),
118
+ excludePatterns: jsonCoerce(import_zod2.z.array(import_zod2.z.string()).optional()).describe(
119
+ 'Glob patterns to exclude (e.g., ["/admin/**", "/reports/**"])'
120
+ ),
121
+ projectRoot: import_zod2.z.string().optional().describe("Project root directory")
89
122
  },
90
123
  async ({ selectedEntities, excludePatterns, projectRoot }) => {
91
124
  const result = (0, import_cli_data_explorer.generateFilter)({
@@ -141,7 +174,7 @@ function registerDataExplorerTools(server2) {
141
174
  }
142
175
 
143
176
  // src/tools/security.ts
144
- var import_zod2 = require("zod");
177
+ var import_zod3 = require("zod");
145
178
  var import_crypto = require("crypto");
146
179
  var import_fs = __toESM(require("fs"));
147
180
  var import_path = __toESM(require("path"));
@@ -150,8 +183,8 @@ function registerSecurityTools(server2) {
150
183
  "stackwright_pro_validate_spec",
151
184
  "Validate an OpenAPI spec against the enterprise approved-specs configuration. Checks if the spec URL is on the allowlist and verifies SHA-256 hash integrity. Use this in enterprise environments where only pre-approved API specs are allowed. Fails build if spec is not approved or has been modified.",
152
185
  {
153
- specPath: import_zod2.z.string().describe("URL or file path to the OpenAPI spec to validate"),
154
- configPath: import_zod2.z.string().optional().describe("Path to stackwright.yml with prebuild.security config")
186
+ specPath: import_zod3.z.string().describe("URL or file path to the OpenAPI spec to validate"),
187
+ configPath: import_zod3.z.string().optional().describe("Path to stackwright.yml with prebuild.security config")
155
188
  },
156
189
  async ({ specPath, configPath }) => {
157
190
  let securityEnabled = false;
@@ -259,16 +292,15 @@ Status: Valid (${allowlist.length} specs on allowlist)`
259
292
  "stackwright_pro_add_approved_spec",
260
293
  "Add an OpenAPI spec to the approved-specs allowlist in stackwright.yml. Computes the SHA-256 hash of the spec and adds it to the security configuration. Use this when onboarding a new API in enterprise environments.",
261
294
  {
262
- name: import_zod2.z.string().describe("Human-readable name for the spec"),
263
- url: import_zod2.z.string().describe("URL or file path to the OpenAPI spec"),
264
- configPath: import_zod2.z.string().optional().describe("Path to stackwright.yml")
295
+ name: import_zod3.z.string().describe("Human-readable name for the spec"),
296
+ url: import_zod3.z.string().describe("URL or file path to the OpenAPI spec"),
297
+ configPath: import_zod3.z.string().optional().describe("Path to stackwright.yml")
265
298
  },
266
299
  async ({ name, url, configPath }) => {
267
300
  const configFile = configPath || import_path.default.join(process.cwd(), "stackwright.yml");
268
301
  let sha256 = "<computed-at-build>";
269
302
  try {
270
303
  if (url.startsWith("http://") || url.startsWith("https://")) {
271
- sha256 = "<computed-at-build>";
272
304
  } else if (import_fs.default.existsSync(url)) {
273
305
  const specContent = import_fs.default.readFileSync(url, "utf8");
274
306
  sha256 = (0, import_crypto.createHash)("sha256").update(specContent).digest("hex");
@@ -315,7 +347,7 @@ SHA-256 computed: ${sha256}`
315
347
  "stackwright_pro_list_approved_specs",
316
348
  "List all specs currently on the approved-specs allowlist. Shows spec names, URLs, and hash prefixes. Use this to audit what APIs are approved in the project.",
317
349
  {
318
- configPath: import_zod2.z.string().optional().describe("Path to stackwright.yml")
350
+ configPath: import_zod3.z.string().optional().describe("Path to stackwright.yml")
319
351
  },
320
352
  async ({ configPath }) => {
321
353
  const configFile = configPath || import_path.default.join(process.cwd(), "stackwright.yml");
@@ -384,16 +416,18 @@ SHA-256 computed: ${sha256}`
384
416
  }
385
417
 
386
418
  // src/tools/isr.ts
387
- var import_zod3 = require("zod");
419
+ var import_zod4 = require("zod");
388
420
  function registerIsrTools(server2) {
389
421
  server2.tool(
390
422
  "stackwright_pro_configure_isr",
391
423
  "Configure Incremental Static Regeneration (ISR) for an API-backed collection. ISR allows API data to be cached and refreshed on a schedule, providing real-time data with the performance of static generation. Use this after stackwright_pro_generate_filter to set revalidation intervals.",
392
424
  {
393
- collection: import_zod3.z.string().describe('Collection name (e.g., "equipment", "supplies")'),
394
- revalidateSeconds: import_zod3.z.number().optional().describe("Revalidation interval in seconds (default: 60)"),
395
- fallback: import_zod3.z.enum(["blocking", "true", "false"]).optional().describe("Fallback behavior for new pages"),
396
- configPath: import_zod3.z.string().optional().describe("Path to stackwright.yml")
425
+ collection: import_zod4.z.string().describe('Collection name (e.g., "equipment", "supplies")'),
426
+ revalidateSeconds: numCoerce(import_zod4.z.number().optional()).describe(
427
+ "Revalidation interval in seconds (default: 60)"
428
+ ),
429
+ fallback: import_zod4.z.enum(["blocking", "true", "false"]).optional().describe("Fallback behavior for new pages"),
430
+ configPath: import_zod4.z.string().optional().describe("Path to stackwright.yml")
397
431
  },
398
432
  async ({ collection, revalidateSeconds = 60, fallback = "blocking", configPath }) => {
399
433
  const revalidate = revalidateSeconds;
@@ -404,7 +438,7 @@ function registerIsrTools(server2) {
404
438
  isr:
405
439
  revalidate: ${revalidate}
406
440
  fallback: ${fallback}`;
407
- let description = "";
441
+ let description;
408
442
  if (revalidate < 60) {
409
443
  description = "\u26A1 Very fresh data (revalidate every " + revalidate + "s)";
410
444
  } else if (revalidate < 300) {
@@ -436,14 +470,16 @@ ${yamlSnippet}
436
470
  "stackwright_pro_configure_isr_batch",
437
471
  "Configure ISR for multiple collections at once. More efficient than calling stackwright_pro_configure_isr multiple times. Provide different revalidation intervals based on data freshness requirements.",
438
472
  {
439
- collections: import_zod3.z.array(
440
- import_zod3.z.object({
441
- name: import_zod3.z.string().describe("Collection name"),
442
- revalidateSeconds: import_zod3.z.number().optional().describe("Revalidation interval")
443
- })
473
+ collections: jsonCoerce(
474
+ import_zod4.z.array(
475
+ import_zod4.z.object({
476
+ name: import_zod4.z.string().describe("Collection name"),
477
+ revalidateSeconds: numCoerce(import_zod4.z.number().optional()).describe("Revalidation interval")
478
+ })
479
+ )
444
480
  ).describe("Array of collection configurations"),
445
- defaultFallback: import_zod3.z.enum(["blocking", "true", "false"]).optional().describe("Default fallback behavior"),
446
- configPath: import_zod3.z.string().optional().describe("Path to stackwright.yml")
481
+ defaultFallback: import_zod4.z.enum(["blocking", "true", "false"]).optional().describe("Default fallback behavior"),
482
+ configPath: import_zod4.z.string().optional().describe("Path to stackwright.yml")
447
483
  },
448
484
  async ({ collections, defaultFallback = "blocking", configPath }) => {
449
485
  const lines = [`\u2699\uFE0F Batch ISR Configuration:
@@ -471,17 +507,17 @@ Fallback: ${defaultFallback}`);
471
507
  }
472
508
 
473
509
  // src/tools/dashboard.ts
474
- var import_zod4 = require("zod");
510
+ var import_zod5 = require("zod");
475
511
  var import_cli_data_explorer2 = require("@stackwright-pro/cli-data-explorer");
476
512
  function registerDashboardTools(server2) {
477
513
  server2.tool(
478
514
  "stackwright_pro_generate_dashboard",
479
515
  "Generate a dashboard page configuration for displaying API data. Creates YAML content for a Stackwright page with grid, metric_card, data_table, and collection_list content types. Use this after stackwright_pro_generate_filter to create pages for your API collections.",
480
516
  {
481
- entities: import_zod4.z.array(import_zod4.z.string()).describe("Entity slugs to include in dashboard"),
482
- layout: import_zod4.z.enum(["grid", "table", "mixed"]).optional().describe("Dashboard layout style"),
483
- pageTitle: import_zod4.z.string().optional().describe("Page title"),
484
- specPath: import_zod4.z.string().optional().describe("Path to OpenAPI spec for entity details")
517
+ entities: jsonCoerce(import_zod5.z.array(import_zod5.z.string())).describe("Entity slugs to include in dashboard"),
518
+ layout: import_zod5.z.enum(["grid", "table", "mixed"]).optional().describe("Dashboard layout style"),
519
+ pageTitle: import_zod5.z.string().optional().describe("Page title"),
520
+ specPath: import_zod5.z.string().optional().describe("Path to OpenAPI spec for entity details")
485
521
  },
486
522
  async ({ entities, layout = "mixed", pageTitle, specPath }) => {
487
523
  let entityDetails = [];
@@ -567,9 +603,9 @@ ${yaml}
567
603
  "stackwright_pro_generate_detail_page",
568
604
  "Generate a detail view page for a single API entity. Creates YAML content for displaying all fields of an individual record. Use this to create detail pages that complement collection listing pages.",
569
605
  {
570
- entity: import_zod4.z.string().describe('Entity slug (e.g., "equipment")'),
571
- slugField: import_zod4.z.string().optional().describe('Field to use as URL slug (default: "id")'),
572
- specPath: import_zod4.z.string().optional().describe("Path to OpenAPI spec for field details")
606
+ entity: import_zod5.z.string().describe('Entity slug (e.g., "equipment")'),
607
+ slugField: import_zod5.z.string().optional().describe('Field to use as URL slug (default: "id")'),
608
+ specPath: import_zod5.z.string().optional().describe("Path to OpenAPI spec for field details")
573
609
  },
574
610
  async ({ entity, slugField = "id", specPath }) => {
575
611
  let fields = [];
@@ -592,39 +628,49 @@ ${yaml}
592
628
  ` title: "${entityName} Details | {{ ${entity}.${slugField} }}"`,
593
629
  "",
594
630
  " content_items:",
595
- " - main:",
596
- ' label: "detail-header"',
597
- " heading:",
598
- ` text: "{{ ${entity}.${slugField} }}"`,
599
- ' textSize: "h1"',
600
- " textBlocks:",
601
- ` - text: "Details for this ${entity}"`,
602
- ' textSize: "body1"',
603
- ' background: "primary"',
604
- ' color: "text"',
631
+ " - type: text_block",
632
+ ' label: "detail-header"',
633
+ " heading:",
634
+ ` text: "{{ ${entity}.${slugField} }}"`,
635
+ ' textSize: "h1"',
636
+ " textBlocks:",
637
+ ` - text: "Details for this ${entity}"`,
638
+ ' textSize: "body1"',
605
639
  "",
606
- " - grid:",
607
- ' label: "detail-fields"',
608
- " columns: 2",
609
- " items:"
640
+ " - type: grid",
641
+ ' label: "detail-fields"',
642
+ " columns:"
610
643
  ];
611
644
  const displayFields = fields.length > 0 ? fields.slice(0, 8) : [
612
645
  { name: slugField, type: "string" },
613
646
  { name: "created_at", type: "datetime" },
614
647
  { name: "updated_at", type: "datetime" }
615
648
  ];
616
- for (const field of displayFields) {
617
- const label = field.name.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
618
- yamlLines.push(` - card:`);
619
- yamlLines.push(` label: "${field.name}-field"`);
620
- yamlLines.push(` heading:`);
621
- yamlLines.push(` text: "${label}"`);
622
- yamlLines.push(` textSize: "h4"`);
623
- yamlLines.push(` content:`);
624
- yamlLines.push(` - text: "{{ ${entity}.${field.name} }}"`);
625
- yamlLines.push(` textSize: "body1"`);
626
- }
627
- yamlLines.push(' background: "background"');
649
+ const mid = Math.ceil(displayFields.length / 2);
650
+ const col1 = displayFields.slice(0, mid);
651
+ const col2 = displayFields.slice(mid);
652
+ for (const [colIndex, colFields] of [col1, col2].entries()) {
653
+ yamlLines.push(" - width: 1");
654
+ yamlLines.push(" content_items:");
655
+ for (const field of colFields) {
656
+ const label = field.name.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
657
+ yamlLines.push(" - type: text_block");
658
+ yamlLines.push(` label: "${field.name}-field"`);
659
+ yamlLines.push(" heading:");
660
+ yamlLines.push(` text: "${label}"`);
661
+ yamlLines.push(' textSize: "h4"');
662
+ yamlLines.push(" textBlocks:");
663
+ yamlLines.push(` - text: "{{ ${entity}.${field.name} }}"`);
664
+ yamlLines.push(' textSize: "body1"');
665
+ }
666
+ }
667
+ yamlLines.push("");
668
+ yamlLines.push(" - type: action_bar");
669
+ yamlLines.push(" actions:");
670
+ yamlLines.push(` - label: "<- Back to ${entityName}"`);
671
+ yamlLines.push(" action: navigate");
672
+ yamlLines.push(` href: "/${entity}"`);
673
+ yamlLines.push(" style: secondary");
628
674
  const yaml = yamlLines.join("\n");
629
675
  return {
630
676
  content: [
@@ -645,7 +691,7 @@ ${yaml}
645
691
  }
646
692
 
647
693
  // src/tools/clarification.ts
648
- var import_zod5 = require("zod");
694
+ var import_zod6 = require("zod");
649
695
  var CONTRADICTION_PATTERNS = [
650
696
  {
651
697
  keywords: ["minimal", "clean", "simple"],
@@ -733,12 +779,14 @@ function registerClarificationTools(server2) {
733
779
  "stackwright_pro_clarify",
734
780
  "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).",
735
781
  {
736
- context: import_zod5.z.string().optional().describe("Context about what the otter is trying to do"),
737
- question_type: import_zod5.z.enum(["closed_choice", "open_text"]).describe("Type of question being asked"),
738
- question: import_zod5.z.string().describe("The clarification question to ask the user"),
739
- choices: import_zod5.z.array(import_zod5.z.string()).optional().describe("Options for closed_choice questions"),
740
- priority: import_zod5.z.enum(["blocking", "preferred", "optional"]).optional().default("preferred").describe("How critical is this clarification? Default: preferred"),
741
- target_field: import_zod5.z.string().optional().describe("What field/config does this clarify?")
782
+ context: import_zod6.z.string().optional().describe("Context about what the otter is trying to do"),
783
+ question_type: import_zod6.z.enum(["closed_choice", "open_text"]).describe("Type of question being asked"),
784
+ question: import_zod6.z.string().describe("The clarification question to ask the user"),
785
+ choices: jsonCoerce(import_zod6.z.array(import_zod6.z.string()).optional()).describe(
786
+ "Options for closed_choice questions"
787
+ ),
788
+ priority: import_zod6.z.enum(["blocking", "preferred", "optional"]).optional().default("preferred").describe("How critical is this clarification? Default: preferred"),
789
+ target_field: import_zod6.z.string().optional().describe("What field/config does this clarify?")
742
790
  },
743
791
  async ({ context, question_type, question, choices, priority, target_field }) => {
744
792
  const result = handleClarify({
@@ -767,8 +815,10 @@ function registerClarificationTools(server2) {
767
815
  "stackwright_pro_detect_conflict",
768
816
  "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.",
769
817
  {
770
- stated_preference: import_zod5.z.string().describe("What the user said they wanted"),
771
- selected_values: import_zod5.z.record(import_zod5.z.string(), import_zod5.z.string()).describe("What the user actually selected (field \u2192 value)")
818
+ stated_preference: import_zod6.z.string().describe("What the user said they wanted"),
819
+ selected_values: jsonCoerce(import_zod6.z.record(import_zod6.z.string(), import_zod6.z.string())).describe(
820
+ "What the user actually selected (field \u2192 value)"
821
+ )
772
822
  },
773
823
  async ({ stated_preference, selected_values }) => {
774
824
  const result = handleDetectConflict({ stated_preference, selected_values });
@@ -813,7 +863,7 @@ ${result.resolution_options?.map((o) => ` \u2022 ${o}`).join("\n")}
813
863
  }
814
864
 
815
865
  // src/tools/packages.ts
816
- var import_zod6 = require("zod");
866
+ var import_zod7 = require("zod");
817
867
  var import_fs2 = require("fs");
818
868
  var import_child_process = require("child_process");
819
869
  var import_path2 = __toESM(require("path"));
@@ -834,17 +884,23 @@ function registerPackageTools(server2) {
834
884
  "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.",
835
885
  {
836
886
  // FIX 3 (B-new-1): Zod v4 requires two-arg z.record(keySchema, valueSchema)
837
- packages: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.string()).describe(
838
- 'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }'
887
+ packages: jsonCoerce(import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional().default({})).describe(
888
+ 'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }. Omit or pass {} when using includeBaseline: true.'
839
889
  ),
840
- devPackages: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.string()).optional().describe("devDependencies to add. Same format as packages."),
841
- scripts: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.string()).optional().describe("npm scripts to add. Only adds if key does not already exist."),
842
- targetDir: import_zod6.z.string().optional().describe(
890
+ devPackages: jsonCoerce(import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional()).describe(
891
+ "devDependencies to add. Same format as packages."
892
+ ),
893
+ scripts: jsonCoerce(import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional()).describe(
894
+ "npm scripts to add. Only adds if key does not already exist."
895
+ ),
896
+ targetDir: import_zod7.z.string().optional().describe(
843
897
  "Project directory containing package.json. Defaults to process.cwd(). Must be an absolute path within the current working directory."
844
898
  ),
845
- runInstall: import_zod6.z.boolean().optional().default(true).describe("Run pnpm install after writing package.json. Defaults to true."),
846
- includeBaseline: import_zod6.z.boolean().optional().default(false).describe(
847
- "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."
899
+ runInstall: boolCoerce(import_zod7.z.boolean().optional().default(true)).describe(
900
+ "Run pnpm install after writing package.json. Defaults to true. Pass boolean true/false."
901
+ ),
902
+ includeBaseline: boolCoerce(import_zod7.z.boolean().optional().default(false)).describe(
903
+ "When true, automatically merges BASELINE_DEPS and BASELINE_DEV_DEPS before applying packages/devPackages args. Safe to call on existing projects \u2014 never overwrites pinned versions. Pass boolean true/false."
848
904
  )
849
905
  },
850
906
  async ({ packages, devPackages, scripts, targetDir, runInstall, includeBaseline }) => {
@@ -1002,11 +1058,11 @@ function setupPackages(opts) {
1002
1058
  }
1003
1059
  }
1004
1060
  const raw = (0, import_fs2.readFileSync)(realPackageJsonPath, "utf8");
1005
- const PackageJsonSchema = import_zod6.z.object({
1061
+ const PackageJsonSchema = import_zod7.z.object({
1006
1062
  // Zod v4: z.record(keySchema, valueSchema) — two-arg form required
1007
- dependencies: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.string()).optional(),
1008
- devDependencies: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.string()).optional(),
1009
- scripts: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.string()).optional()
1063
+ dependencies: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional(),
1064
+ devDependencies: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional(),
1065
+ scripts: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional()
1010
1066
  }).passthrough();
1011
1067
  const schemaResult = PackageJsonSchema.safeParse(JSON.parse(raw));
1012
1068
  if (!schemaResult.success) {
@@ -1088,8 +1144,9 @@ function setupPackages(opts) {
1088
1144
 
1089
1145
  // src/tools/questions.ts
1090
1146
  var import_promises = require("fs/promises");
1147
+ var import_node_fs = require("fs");
1091
1148
  var import_node_path = require("path");
1092
- var import_zod7 = require("zod");
1149
+ var import_zod8 = require("zod");
1093
1150
 
1094
1151
  // src/question-adapter.ts
1095
1152
  function truncate(str, maxLength) {
@@ -1275,22 +1332,22 @@ function answersToManifestFormat(answers, questions) {
1275
1332
  }
1276
1333
 
1277
1334
  // src/tools/questions.ts
1278
- var ManifestQuestionSchema = import_zod7.z.object({
1279
- id: import_zod7.z.string(),
1280
- question: import_zod7.z.string(),
1281
- type: import_zod7.z.enum(["text", "select", "multi-select", "confirm"]),
1282
- required: import_zod7.z.boolean().optional(),
1283
- options: import_zod7.z.array(
1284
- import_zod7.z.object({
1285
- label: import_zod7.z.string(),
1286
- value: import_zod7.z.string()
1335
+ var ManifestQuestionSchema = import_zod8.z.object({
1336
+ id: import_zod8.z.string(),
1337
+ question: import_zod8.z.string(),
1338
+ type: import_zod8.z.enum(["text", "select", "multi-select", "confirm"]),
1339
+ required: import_zod8.z.boolean().optional(),
1340
+ options: import_zod8.z.array(
1341
+ import_zod8.z.object({
1342
+ label: import_zod8.z.string(),
1343
+ value: import_zod8.z.string()
1287
1344
  })
1288
1345
  ).optional(),
1289
- default: import_zod7.z.union([import_zod7.z.string(), import_zod7.z.boolean(), import_zod7.z.array(import_zod7.z.string())]).optional(),
1290
- help: import_zod7.z.string().optional(),
1291
- dependsOn: import_zod7.z.object({
1292
- questionId: import_zod7.z.string(),
1293
- value: import_zod7.z.union([import_zod7.z.string(), import_zod7.z.array(import_zod7.z.string())])
1346
+ default: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.boolean(), import_zod8.z.array(import_zod8.z.string())]).optional(),
1347
+ help: import_zod8.z.string().optional(),
1348
+ dependsOn: import_zod8.z.object({
1349
+ questionId: import_zod8.z.string(),
1350
+ value: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.array(import_zod8.z.string())])
1294
1351
  }).optional()
1295
1352
  });
1296
1353
  function registerQuestionTools(server2) {
@@ -1298,11 +1355,13 @@ function registerQuestionTools(server2) {
1298
1355
  "stackwright_pro_present_phase_questions",
1299
1356
  "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.",
1300
1357
  {
1301
- phase: import_zod7.z.string().describe('Phase name for display context, e.g. "designer", "api", "auth"'),
1302
- questions: import_zod7.z.array(ManifestQuestionSchema).optional().describe(
1358
+ phase: import_zod8.z.string().describe('Phase name for display context, e.g. "designer", "api", "auth"'),
1359
+ questions: jsonCoerce(import_zod8.z.array(ManifestQuestionSchema).optional()).describe(
1303
1360
  "Questions in Question Manifest format. If omitted, questions are read from .stackwright/question-manifest.json using the phase name."
1304
1361
  ),
1305
- answers: import_zod7.z.record(import_zod7.z.union([import_zod7.z.string(), import_zod7.z.array(import_zod7.z.string()), import_zod7.z.boolean()])).optional().describe("Previously collected answers used to resolve dependsOn conditions")
1362
+ answers: jsonCoerce(
1363
+ import_zod8.z.record(import_zod8.z.string(), import_zod8.z.union([import_zod8.z.string(), import_zod8.z.array(import_zod8.z.string()), import_zod8.z.boolean()])).optional()
1364
+ ).describe("Previously collected answers used to resolve dependsOn conditions")
1306
1365
  },
1307
1366
  async ({ phase, questions, answers }) => {
1308
1367
  let resolvedQuestions;
@@ -1353,17 +1412,36 @@ function registerQuestionTools(server2) {
1353
1412
  }
1354
1413
  }
1355
1414
  const adapted = adaptQuestions(resolvedQuestions, answers ?? {});
1415
+ const labelSchema = import_zod8.z.string().max(50, "Value should have at most 50 characters");
1416
+ for (const q of adapted) {
1417
+ for (const opt of q.options) {
1418
+ const check = labelSchema.safeParse(opt.label);
1419
+ if (!check.success) {
1420
+ return {
1421
+ content: [
1422
+ {
1423
+ type: "text",
1424
+ text: JSON.stringify({
1425
+ error: `Option label for phase "${phase}" exceeds 50 characters: ${check.error.issues[0]?.message ?? "label too long"}. Truncate option labels to \u226450 characters before calling this tool.`
1426
+ })
1427
+ }
1428
+ ],
1429
+ isError: true
1430
+ };
1431
+ }
1432
+ }
1433
+ }
1356
1434
  if (adapted.length === 0) {
1357
1435
  return {
1358
1436
  content: [
1359
1437
  {
1360
1438
  type: "text",
1361
- text: JSON.stringify({
1362
- phase,
1363
- skipped: true,
1364
- reason: "No questions to present (all filtered by dependsOn conditions)",
1365
- answers: []
1366
- })
1439
+ text: `Phase "${phase}" has no questions to present. Do NOT call ask_user_question. Call stackwright_pro_save_phase_answers({ phase: "${phase}", rawAnswers: [] }) directly, then proceed to the execution step for this phase.`
1440
+ },
1441
+ {
1442
+ type: "text",
1443
+ // Empty array — second block always present so the foreman's two-block contract holds
1444
+ text: JSON.stringify([])
1367
1445
  }
1368
1446
  ],
1369
1447
  isError: false
@@ -1384,10 +1462,148 @@ function registerQuestionTools(server2) {
1384
1462
  };
1385
1463
  }
1386
1464
  );
1465
+ server2.tool(
1466
+ "stackwright_pro_get_next_question",
1467
+ "Returns the next unanswered question for a phase as a plain JSON object \u2014 one question at a time. Returns { done: true } when all questions are answered or the phase has no questions. Call this in a loop: present the question in plain chat, get user reply, call record_answer, repeat.",
1468
+ { phase: import_zod8.z.string().describe('Phase name e.g. "designer", "api", "auth"') },
1469
+ async ({ phase }) => {
1470
+ const SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
1471
+ if (!SAFE_PHASE.test(phase)) {
1472
+ return {
1473
+ content: [
1474
+ {
1475
+ type: "text",
1476
+ text: JSON.stringify({ error: `Invalid phase name: "${phase.slice(0, 50)}"` })
1477
+ }
1478
+ ],
1479
+ isError: true
1480
+ };
1481
+ }
1482
+ const cwd = process.cwd();
1483
+ const questionsPath = (0, import_node_path.join)(cwd, ".stackwright", "questions", `${phase}.json`);
1484
+ let questions = [];
1485
+ try {
1486
+ const raw = await (0, import_promises.readFile)(questionsPath, "utf-8");
1487
+ const parsed = JSON.parse(raw);
1488
+ questions = parsed.questions ?? [];
1489
+ } catch {
1490
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1491
+ }
1492
+ if (questions.length === 0) {
1493
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1494
+ }
1495
+ const answersPath = (0, import_node_path.join)(cwd, ".stackwright", "answers", `${phase}.json`);
1496
+ let answeredIds = /* @__PURE__ */ new Set();
1497
+ try {
1498
+ const raw = await (0, import_promises.readFile)(answersPath, "utf-8");
1499
+ const parsed = JSON.parse(raw);
1500
+ answeredIds = new Set(Object.keys(parsed.answers ?? {}));
1501
+ } catch {
1502
+ }
1503
+ const next = questions.find((q) => !answeredIds.has(q.id));
1504
+ if (!next) {
1505
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1506
+ }
1507
+ return {
1508
+ content: [
1509
+ {
1510
+ type: "text",
1511
+ text: JSON.stringify({
1512
+ done: false,
1513
+ questionId: next.id,
1514
+ question: next.question,
1515
+ type: next.type,
1516
+ options: next.options ?? null,
1517
+ help: next.help ?? null,
1518
+ index: questions.indexOf(next) + 1,
1519
+ total: questions.length
1520
+ })
1521
+ }
1522
+ ]
1523
+ };
1524
+ }
1525
+ );
1526
+ server2.tool(
1527
+ "stackwright_pro_record_answer",
1528
+ "Records a single answer to a phase question. Appends to .stackwright/answers/{phase}.json incrementally. Idempotent \u2014 calling twice for the same questionId overwrites. Call after receiving each user reply in the conversational question loop.",
1529
+ {
1530
+ phase: import_zod8.z.string().describe('Phase name e.g. "designer"'),
1531
+ questionId: import_zod8.z.string().describe('The question ID from get_next_question, e.g. "designer-1"'),
1532
+ answer: import_zod8.z.string().describe("The user's free-text answer")
1533
+ },
1534
+ async ({ phase, questionId, answer }) => {
1535
+ const SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
1536
+ if (!SAFE_PHASE.test(phase)) {
1537
+ return {
1538
+ content: [
1539
+ { type: "text", text: JSON.stringify({ error: "Invalid phase name" }) }
1540
+ ],
1541
+ isError: true
1542
+ };
1543
+ }
1544
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(questionId)) {
1545
+ return {
1546
+ content: [
1547
+ { type: "text", text: JSON.stringify({ error: "Invalid questionId" }) }
1548
+ ],
1549
+ isError: true
1550
+ };
1551
+ }
1552
+ const safeAnswer = answer.slice(0, 2e3);
1553
+ const cwd = process.cwd();
1554
+ const answersDir = (0, import_node_path.join)(cwd, ".stackwright", "answers");
1555
+ const answersPath = (0, import_node_path.join)(answersDir, `${phase}.json`);
1556
+ if ((0, import_node_fs.existsSync)(answersDir) && (0, import_node_fs.lstatSync)(answersDir).isSymbolicLink()) {
1557
+ return {
1558
+ content: [
1559
+ {
1560
+ type: "text",
1561
+ text: JSON.stringify({ error: "answers dir is a symlink \u2014 refusing to write" })
1562
+ }
1563
+ ],
1564
+ isError: true
1565
+ };
1566
+ }
1567
+ (0, import_node_fs.mkdirSync)(answersDir, { recursive: true });
1568
+ let existing = {
1569
+ version: "1.0",
1570
+ phase,
1571
+ answers: {}
1572
+ };
1573
+ try {
1574
+ if ((0, import_node_fs.existsSync)(answersPath)) {
1575
+ if ((0, import_node_fs.lstatSync)(answersPath).isSymbolicLink()) {
1576
+ return {
1577
+ content: [
1578
+ {
1579
+ type: "text",
1580
+ text: JSON.stringify({ error: "answers file is a symlink \u2014 refusing to write" })
1581
+ }
1582
+ ],
1583
+ isError: true
1584
+ };
1585
+ }
1586
+ const raw = await (0, import_promises.readFile)(answersPath, "utf-8");
1587
+ existing = JSON.parse(raw);
1588
+ }
1589
+ } catch {
1590
+ }
1591
+ existing.answers[questionId] = safeAnswer;
1592
+ existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1593
+ const tmp = `${answersPath}.tmp`;
1594
+ await (0, import_promises.writeFile)(tmp, JSON.stringify(existing, null, 2), "utf-8");
1595
+ (0, import_node_fs.renameSync)(tmp, answersPath);
1596
+ return {
1597
+ content: [
1598
+ { type: "text", text: JSON.stringify({ recorded: true, phase, questionId }) }
1599
+ ]
1600
+ };
1601
+ }
1602
+ );
1387
1603
  }
1388
1604
 
1389
1605
  // src/tools/orchestration.ts
1390
- var import_zod8 = require("zod");
1606
+ var import_zod9 = require("zod");
1391
1607
  var import_fs3 = require("fs");
1392
1608
  var import_path3 = require("path");
1393
1609
  var OTTER_NAME_TO_PHASE = [
@@ -1398,7 +1614,9 @@ var OTTER_NAME_TO_PHASE = [
1398
1614
  ["dashboard", "dashboard"],
1399
1615
  ["data", "data"],
1400
1616
  ["page", "pages"],
1401
- ["workflow", "workflow"]
1617
+ ["workflow", "workflow"],
1618
+ ["polish", "polish"],
1619
+ ["geo", "geo"]
1402
1620
  ];
1403
1621
  var PHASE_TO_OTTER = {
1404
1622
  designer: "stackwright-pro-designer-otter",
@@ -1408,7 +1626,9 @@ var PHASE_TO_OTTER = {
1408
1626
  pages: "stackwright-pro-page-otter",
1409
1627
  dashboard: "stackwright-pro-dashboard-otter",
1410
1628
  data: "stackwright-pro-data-otter",
1411
- workflow: "stackwright-pro-workflow-otter"
1629
+ workflow: "stackwright-pro-workflow-otter",
1630
+ polish: "stackwright-pro-polish-otter",
1631
+ geo: "stackwright-pro-geo-otter"
1412
1632
  };
1413
1633
  function detectPhase(otterName) {
1414
1634
  const lower = otterName.toLowerCase();
@@ -1555,13 +1775,63 @@ function handleGetOtterName(input) {
1555
1775
  isError: false
1556
1776
  };
1557
1777
  }
1778
+ function handleSaveBuildContext(input) {
1779
+ const cwd = input._cwd ?? process.cwd();
1780
+ const dir = (0, import_path3.join)(cwd, ".stackwright");
1781
+ const filePath = (0, import_path3.join)(dir, "build-context.json");
1782
+ try {
1783
+ (0, import_fs3.mkdirSync)(dir, { recursive: true });
1784
+ if ((0, import_fs3.existsSync)(filePath)) {
1785
+ const stat = (0, import_fs3.lstatSync)(filePath);
1786
+ if (stat.isSymbolicLink()) {
1787
+ return {
1788
+ text: JSON.stringify({
1789
+ success: false,
1790
+ error: `Refusing to write to symlink: ${filePath}`
1791
+ }),
1792
+ isError: true
1793
+ };
1794
+ }
1795
+ }
1796
+ const payload = {
1797
+ version: "1.0",
1798
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
1799
+ buildContext: input.buildContext
1800
+ };
1801
+ (0, import_fs3.writeFileSync)(filePath, JSON.stringify(payload, null, 2) + "\n");
1802
+ return {
1803
+ text: JSON.stringify({ success: true, path: filePath }),
1804
+ isError: false
1805
+ };
1806
+ } catch (err) {
1807
+ const message = err instanceof Error ? err.message : String(err);
1808
+ return {
1809
+ text: JSON.stringify({ success: false, error: message }),
1810
+ isError: true
1811
+ };
1812
+ }
1813
+ }
1558
1814
  function registerOrchestrationTools(server2) {
1815
+ server2.tool(
1816
+ "stackwright_pro_save_build_context",
1817
+ `Save the user's initial build description to .stackwright/build-context.json. Call this once at startup after the user answers the opening "what are you building" question. The saved context is automatically prepended to specialist prompts by stackwright_pro_build_specialist_prompt.`,
1818
+ {
1819
+ buildContext: import_zod9.z.string().describe("Free-text description of what the user wants to build")
1820
+ },
1821
+ async ({ buildContext }) => {
1822
+ const { text, isError } = handleSaveBuildContext({ buildContext });
1823
+ return {
1824
+ content: [{ type: "text", text }],
1825
+ isError
1826
+ };
1827
+ }
1828
+ );
1559
1829
  server2.tool(
1560
1830
  "stackwright_pro_parse_otter_response",
1561
1831
  "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.",
1562
1832
  {
1563
- otterName: import_zod8.z.string().describe('The agent name, e.g. "stackwright-pro-api-otter"'),
1564
- responseText: import_zod8.z.string().describe("Raw text response from the otter's QUESTION_COLLECTION_MODE invocation")
1833
+ otterName: import_zod9.z.string().describe('The agent name, e.g. "stackwright-pro-api-otter"'),
1834
+ responseText: import_zod9.z.string().describe("Raw text response from the otter's QUESTION_COLLECTION_MODE invocation")
1565
1835
  },
1566
1836
  async ({ otterName, responseText }) => {
1567
1837
  const { result, isError } = handleParseOtterResponse({ otterName, responseText });
@@ -1575,16 +1845,18 @@ function registerOrchestrationTools(server2) {
1575
1845
  "stackwright_pro_save_manifest",
1576
1846
  "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.",
1577
1847
  {
1578
- phases: import_zod8.z.array(
1579
- import_zod8.z.object({
1580
- phase: import_zod8.z.string(),
1581
- otter: import_zod8.z.string(),
1582
- questions: import_zod8.z.array(import_zod8.z.any()),
1583
- requiredPackages: import_zod8.z.object({
1584
- dependencies: import_zod8.z.record(import_zod8.z.string(), import_zod8.z.string()).optional(),
1585
- devPackages: import_zod8.z.record(import_zod8.z.string(), import_zod8.z.string()).optional()
1586
- }).optional()
1587
- })
1848
+ phases: jsonCoerce(
1849
+ import_zod9.z.array(
1850
+ import_zod9.z.object({
1851
+ phase: import_zod9.z.string(),
1852
+ otter: import_zod9.z.string(),
1853
+ questions: import_zod9.z.array(import_zod9.z.any()),
1854
+ requiredPackages: import_zod9.z.object({
1855
+ dependencies: import_zod9.z.record(import_zod9.z.string(), import_zod9.z.string()).optional(),
1856
+ devPackages: import_zod9.z.record(import_zod9.z.string(), import_zod9.z.string()).optional()
1857
+ }).optional()
1858
+ })
1859
+ )
1588
1860
  ).describe("Array of parsed phase objects from stackwright_pro_parse_otter_response")
1589
1861
  },
1590
1862
  async ({ phases }) => {
@@ -1599,15 +1871,21 @@ function registerOrchestrationTools(server2) {
1599
1871
  "stackwright_pro_save_phase_answers",
1600
1872
  "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.",
1601
1873
  {
1602
- phase: import_zod8.z.string().describe('Phase name, e.g. "designer"'),
1603
- rawAnswers: import_zod8.z.array(
1604
- import_zod8.z.object({
1605
- question_header: import_zod8.z.string(),
1606
- selected_options: import_zod8.z.array(import_zod8.z.string()),
1607
- other_text: import_zod8.z.string().nullable().optional()
1608
- })
1609
- ).describe("Answers as returned by ask_user_question"),
1610
- questions: import_zod8.z.array(import_zod8.z.any()).optional().describe("Original manifest questions for label\u2192value reverse-mapping")
1874
+ phase: import_zod9.z.string().describe('Phase name, e.g. "designer"'),
1875
+ rawAnswers: jsonCoerce(
1876
+ import_zod9.z.array(
1877
+ import_zod9.z.object({
1878
+ question_header: import_zod9.z.string(),
1879
+ selected_options: import_zod9.z.array(import_zod9.z.string()),
1880
+ other_text: import_zod9.z.string().nullable().optional()
1881
+ })
1882
+ )
1883
+ ).describe(
1884
+ "Answers as returned by ask_user_question \u2014 pass the native array, not a JSON string"
1885
+ ),
1886
+ questions: jsonCoerce(import_zod9.z.array(import_zod9.z.any()).optional()).describe(
1887
+ "Original manifest questions for label\u2192value reverse-mapping \u2014 pass the native array, not a JSON string"
1888
+ )
1611
1889
  },
1612
1890
  async ({ phase, rawAnswers, questions }) => {
1613
1891
  const { text, isError } = handleSavePhaseAnswers({
@@ -1625,7 +1903,7 @@ function registerOrchestrationTools(server2) {
1625
1903
  "stackwright_pro_read_phase_answers",
1626
1904
  "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.",
1627
1905
  {
1628
- phase: import_zod8.z.string().describe('Phase name, e.g. "designer"')
1906
+ phase: import_zod9.z.string().describe('Phase name, e.g. "designer"')
1629
1907
  },
1630
1908
  async ({ phase }) => {
1631
1909
  const { text, isError } = handleReadPhaseAnswers({ phase });
@@ -1639,7 +1917,7 @@ function registerOrchestrationTools(server2) {
1639
1917
  "stackwright_pro_get_otter_name",
1640
1918
  "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.",
1641
1919
  {
1642
- phase: import_zod8.z.string().describe('Phase name, e.g. "designer", "api", "pages"')
1920
+ phase: import_zod9.z.string().describe('Phase name, e.g. "designer", "api", "pages"')
1643
1921
  },
1644
1922
  async ({ phase }) => {
1645
1923
  const { text, isError } = handleGetOtterName({ phase });
@@ -1652,28 +1930,375 @@ function registerOrchestrationTools(server2) {
1652
1930
  }
1653
1931
 
1654
1932
  // src/tools/pipeline.ts
1655
- var import_zod9 = require("zod");
1933
+ var import_zod11 = require("zod");
1934
+ var import_fs5 = require("fs");
1935
+ var import_path5 = require("path");
1936
+ var import_crypto3 = require("crypto");
1937
+
1938
+ // src/artifact-signing.ts
1939
+ var import_crypto2 = require("crypto");
1656
1940
  var import_fs4 = require("fs");
1657
1941
  var import_path4 = require("path");
1942
+ var import_zod10 = require("zod");
1943
+ var ALGORITHM = "ECDSA-P384-SHA384";
1944
+ var KEY_FILE = "pipeline-keys.json";
1945
+ var KEY_DIR = ".stackwright";
1946
+ var SIGNATURE_MANIFEST = "signatures.json";
1947
+ var ARTIFACTS_DIR = ".stackwright/artifacts";
1948
+ function rejectSymlink(filePath, context) {
1949
+ if (!(0, import_fs4.existsSync)(filePath)) return;
1950
+ const stat = (0, import_fs4.lstatSync)(filePath);
1951
+ if (stat.isSymbolicLink()) {
1952
+ throw new Error(`Security: refusing to follow symlink at ${context}: ${filePath}`);
1953
+ }
1954
+ }
1955
+ function computeSha384(data) {
1956
+ return (0, import_crypto2.createHash)("sha384").update(data).digest("hex");
1957
+ }
1958
+ function safeDigestEqual(a, b) {
1959
+ if (a.length !== b.length) return false;
1960
+ return (0, import_crypto2.timingSafeEqual)(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
1961
+ }
1962
+ function emptyManifest() {
1963
+ return {
1964
+ version: "1.0",
1965
+ algorithm: ALGORITHM,
1966
+ signatures: {}
1967
+ };
1968
+ }
1969
+ function initPipelineKeys(cwd) {
1970
+ const keyDir = (0, import_path4.join)(cwd, KEY_DIR);
1971
+ const keyPath = (0, import_path4.join)(keyDir, KEY_FILE);
1972
+ rejectSymlink(keyPath, "pipeline-keys.json");
1973
+ (0, import_fs4.mkdirSync)(keyDir, { recursive: true });
1974
+ const { publicKey, privateKey } = (0, import_crypto2.generateKeyPairSync)("ec", {
1975
+ namedCurve: "P-384"
1976
+ });
1977
+ const publicKeyPem = publicKey.export({ type: "spki", format: "pem" });
1978
+ const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" });
1979
+ const fingerprint = (0, import_crypto2.createHash)("sha256").update(publicKeyPem).digest("hex");
1980
+ const keyFile = {
1981
+ version: "1.0",
1982
+ algorithm: ALGORITHM,
1983
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1984
+ publicKeyPem,
1985
+ privateKeyPem
1986
+ };
1987
+ (0, import_fs4.writeFileSync)(keyPath, JSON.stringify(keyFile, null, 2), { encoding: "utf-8" });
1988
+ return { publicKeyPem, fingerprint };
1989
+ }
1990
+ function loadPipelineKeys(cwd) {
1991
+ const keyPath = (0, import_path4.join)(cwd, KEY_DIR, KEY_FILE);
1992
+ rejectSymlink(keyPath, "pipeline-keys.json");
1993
+ if (!(0, import_fs4.existsSync)(keyPath)) {
1994
+ throw new Error("Pipeline keys not found \u2014 call initPipelineKeys() first");
1995
+ }
1996
+ let raw;
1997
+ try {
1998
+ raw = (0, import_fs4.readFileSync)(keyPath, "utf-8");
1999
+ } catch (err) {
2000
+ const msg = err instanceof Error ? err.message : String(err);
2001
+ throw new Error(`Cannot read pipeline keys: ${msg}`, { cause: err });
2002
+ }
2003
+ let parsed;
2004
+ try {
2005
+ parsed = JSON.parse(raw);
2006
+ } catch {
2007
+ throw new Error("Pipeline keys file is not valid JSON");
2008
+ }
2009
+ if (typeof parsed.publicKeyPem !== "string" || !parsed.publicKeyPem.includes("-----BEGIN PUBLIC KEY-----")) {
2010
+ throw new Error("Invalid public key PEM in pipeline keys file");
2011
+ }
2012
+ if (typeof parsed.privateKeyPem !== "string" || !parsed.privateKeyPem.includes("-----BEGIN")) {
2013
+ throw new Error("Invalid private key PEM in pipeline keys file");
2014
+ }
2015
+ const publicKey = (0, import_crypto2.createPublicKey)(parsed.publicKeyPem);
2016
+ const privateKey = (0, import_crypto2.createPrivateKey)(parsed.privateKeyPem);
2017
+ return { privateKey, publicKey };
2018
+ }
2019
+ function signArtifact(artifactBytes, privateKey) {
2020
+ const digest = computeSha384(artifactBytes);
2021
+ const sig = (0, import_crypto2.sign)("SHA384", artifactBytes, privateKey);
2022
+ return {
2023
+ digest,
2024
+ signature: sig.toString("base64"),
2025
+ algorithm: ALGORITHM,
2026
+ signedAt: (/* @__PURE__ */ new Date()).toISOString()
2027
+ };
2028
+ }
2029
+ function verifyArtifact(artifactBytes, signature, publicKey) {
2030
+ const sigValid = (0, import_crypto2.verify)(
2031
+ "SHA384",
2032
+ artifactBytes,
2033
+ publicKey,
2034
+ Buffer.from(signature.signature, "base64")
2035
+ );
2036
+ if (!sigValid) return false;
2037
+ const actualDigest = computeSha384(artifactBytes);
2038
+ return safeDigestEqual(actualDigest, signature.digest);
2039
+ }
2040
+ function loadSignatureManifest(cwd) {
2041
+ const manifestPath = (0, import_path4.join)(cwd, ARTIFACTS_DIR, SIGNATURE_MANIFEST);
2042
+ rejectSymlink(manifestPath, "signatures.json");
2043
+ if (!(0, import_fs4.existsSync)(manifestPath)) return emptyManifest();
2044
+ let raw;
2045
+ try {
2046
+ raw = (0, import_fs4.readFileSync)(manifestPath, "utf-8");
2047
+ } catch (err) {
2048
+ const msg = err instanceof Error ? err.message : String(err);
2049
+ throw new Error(`Cannot read signature manifest: ${msg}`, { cause: err });
2050
+ }
2051
+ try {
2052
+ const parsed = JSON.parse(raw);
2053
+ if (parsed.version !== "1.0" || typeof parsed.signatures !== "object") {
2054
+ throw new Error("Malformed signature manifest: invalid version or missing signatures object");
2055
+ }
2056
+ return parsed;
2057
+ } catch (err) {
2058
+ if (err instanceof Error && err.message.startsWith("Malformed")) throw err;
2059
+ throw new Error("Signature manifest is not valid JSON", { cause: err });
2060
+ }
2061
+ }
2062
+ function saveArtifactSignature(cwd, artifactFilename, sig, signerOtter) {
2063
+ const artifactsDir = (0, import_path4.join)(cwd, ARTIFACTS_DIR);
2064
+ const manifestPath = (0, import_path4.join)(artifactsDir, SIGNATURE_MANIFEST);
2065
+ rejectSymlink(manifestPath, "signatures.json (save)");
2066
+ (0, import_fs4.mkdirSync)(artifactsDir, { recursive: true });
2067
+ const manifest = loadSignatureManifest(cwd);
2068
+ manifest.signatures[artifactFilename] = {
2069
+ ...sig,
2070
+ signedBy: signerOtter
2071
+ };
2072
+ (0, import_fs4.writeFileSync)(manifestPath, JSON.stringify(manifest, null, 2), { encoding: "utf-8" });
2073
+ }
2074
+ function getArtifactSignature(cwd, artifactFilename) {
2075
+ const manifest = loadSignatureManifest(cwd);
2076
+ const entry = manifest.signatures[artifactFilename];
2077
+ if (!entry) return null;
2078
+ return {
2079
+ digest: entry.digest,
2080
+ signature: entry.signature,
2081
+ algorithm: entry.algorithm,
2082
+ signedAt: entry.signedAt
2083
+ };
2084
+ }
2085
+ function emitSignatureAuditEvent(params) {
2086
+ const record = JSON.stringify({
2087
+ level: "AUDIT",
2088
+ event: "ARTIFACT_SIGNATURE_FAIL",
2089
+ timestamp: params.timestamp,
2090
+ source: params.source,
2091
+ artifactFilename: params.artifactFilename,
2092
+ expectedDigest: params.expectedDigest,
2093
+ actualDigest: params.actualDigest,
2094
+ phase: params.phase
2095
+ });
2096
+ process.stderr.write(`ARTIFACT_SIGNATURE_FAIL ${record}
2097
+ `);
2098
+ }
2099
+ function registerArtifactSigningTools(server2) {
2100
+ server2.tool(
2101
+ "stackwright_pro_verify_artifact_signatures",
2102
+ "Verify ECDSA P-384 signatures for all pipeline artifacts in .stackwright/artifacts/. Auto-discovers keys from .stackwright/pipeline-keys.json. Returns per-artifact verification status.",
2103
+ {
2104
+ cwd: import_zod10.z.string().optional().describe("Project root directory. Defaults to process.cwd().")
2105
+ },
2106
+ async ({ cwd: cwdParam }) => {
2107
+ const cwd = cwdParam ?? process.cwd();
2108
+ let publicKey;
2109
+ try {
2110
+ const keys = loadPipelineKeys(cwd);
2111
+ publicKey = keys.publicKey;
2112
+ } catch (err) {
2113
+ const msg = err instanceof Error ? err.message : String(err);
2114
+ return {
2115
+ content: [
2116
+ {
2117
+ type: "text",
2118
+ text: JSON.stringify({
2119
+ error: true,
2120
+ message: `Cannot load pipeline keys: ${msg}`
2121
+ })
2122
+ }
2123
+ ],
2124
+ isError: true
2125
+ };
2126
+ }
2127
+ let manifest;
2128
+ try {
2129
+ manifest = loadSignatureManifest(cwd);
2130
+ } catch (err) {
2131
+ const msg = err instanceof Error ? err.message : String(err);
2132
+ return {
2133
+ content: [
2134
+ {
2135
+ type: "text",
2136
+ text: JSON.stringify({
2137
+ error: true,
2138
+ message: `Cannot load signature manifest: ${msg}`
2139
+ })
2140
+ }
2141
+ ],
2142
+ isError: true
2143
+ };
2144
+ }
2145
+ const artifactsPath = (0, import_path4.join)(cwd, ARTIFACTS_DIR);
2146
+ let artifactFiles = [];
2147
+ try {
2148
+ if ((0, import_fs4.existsSync)(artifactsPath)) {
2149
+ artifactFiles = (0, import_fs4.readdirSync)(artifactsPath).filter(
2150
+ (f) => f.endsWith(".json") && f !== SIGNATURE_MANIFEST
2151
+ );
2152
+ }
2153
+ } catch {
2154
+ }
2155
+ const results = [];
2156
+ let hasFailure = false;
2157
+ for (const filename of artifactFiles) {
2158
+ const filePath = (0, import_path4.join)(artifactsPath, filename);
2159
+ try {
2160
+ rejectSymlink(filePath, `artifact ${filename}`);
2161
+ } catch {
2162
+ results.push({
2163
+ filename,
2164
+ verified: false,
2165
+ error: "Refusing to verify symlink"
2166
+ });
2167
+ hasFailure = true;
2168
+ continue;
2169
+ }
2170
+ let artifactBytes;
2171
+ try {
2172
+ artifactBytes = (0, import_fs4.readFileSync)(filePath);
2173
+ } catch (err) {
2174
+ const msg = err instanceof Error ? err.message : String(err);
2175
+ results.push({
2176
+ filename,
2177
+ verified: false,
2178
+ error: `Cannot read artifact: ${msg}`
2179
+ });
2180
+ hasFailure = true;
2181
+ continue;
2182
+ }
2183
+ const entry = manifest.signatures[filename];
2184
+ if (!entry) {
2185
+ results.push({
2186
+ filename,
2187
+ verified: false,
2188
+ error: "No signature found in manifest"
2189
+ });
2190
+ hasFailure = true;
2191
+ continue;
2192
+ }
2193
+ const sig = {
2194
+ digest: entry.digest,
2195
+ signature: entry.signature,
2196
+ algorithm: entry.algorithm,
2197
+ signedAt: entry.signedAt
2198
+ };
2199
+ const verified = verifyArtifact(artifactBytes, sig, publicKey);
2200
+ if (!verified) {
2201
+ const actualDigest = computeSha384(artifactBytes);
2202
+ emitSignatureAuditEvent({
2203
+ artifactFilename: filename,
2204
+ expectedDigest: sig.digest,
2205
+ actualDigest,
2206
+ phase: entry.signedBy ?? "unknown",
2207
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2208
+ source: "stackwright_pro_verify_artifact_signatures"
2209
+ });
2210
+ results.push({
2211
+ filename,
2212
+ verified: false,
2213
+ error: `Signature verification failed \u2014 artifact may have been tampered with`,
2214
+ signedBy: entry.signedBy,
2215
+ signedAt: entry.signedAt
2216
+ });
2217
+ hasFailure = true;
2218
+ } else {
2219
+ results.push({
2220
+ filename,
2221
+ verified: true,
2222
+ signedBy: entry.signedBy,
2223
+ signedAt: entry.signedAt
2224
+ });
2225
+ }
2226
+ }
2227
+ for (const manifestFilename of Object.keys(manifest.signatures)) {
2228
+ if (!artifactFiles.includes(manifestFilename)) {
2229
+ results.push({
2230
+ filename: manifestFilename,
2231
+ verified: false,
2232
+ error: "Artifact referenced in manifest but missing from disk"
2233
+ });
2234
+ hasFailure = true;
2235
+ }
2236
+ }
2237
+ const verifiedCount = results.filter((r) => r.verified).length;
2238
+ const failedCount = results.filter((r) => !r.verified).length;
2239
+ return {
2240
+ content: [
2241
+ {
2242
+ type: "text",
2243
+ text: JSON.stringify({
2244
+ totalArtifacts: artifactFiles.length,
2245
+ verifiedCount,
2246
+ failedCount,
2247
+ results,
2248
+ ...hasFailure ? {
2249
+ error: "SIGNATURE VERIFICATION FAILED: One or more artifact signatures are invalid. Do not proceed \u2014 artifacts may have been tampered with."
2250
+ } : {}
2251
+ })
2252
+ }
2253
+ ],
2254
+ isError: hasFailure
2255
+ };
2256
+ }
2257
+ );
2258
+ }
2259
+
2260
+ // src/tools/pipeline.ts
2261
+ var import_types = require("@stackwright-pro/types");
1658
2262
  var PHASE_ORDER = [
1659
2263
  "designer",
1660
2264
  "theme",
1661
2265
  "api",
1662
- "auth",
1663
2266
  "data",
2267
+ "geo",
2268
+ "workflow",
2269
+ "services",
1664
2270
  "pages",
1665
2271
  "dashboard",
1666
- "workflow"
2272
+ "auth",
2273
+ "polish"
1667
2274
  ];
1668
2275
  var PHASE_DEPENDENCIES = {
1669
2276
  designer: [],
1670
2277
  theme: ["designer"],
1671
2278
  api: [],
1672
- auth: [],
1673
2279
  data: ["api"],
1674
- pages: ["designer", "theme", "api", "data", "auth"],
1675
- dashboard: ["designer", "theme", "api", "data"],
1676
- workflow: ["auth"]
2280
+ geo: ["data"],
2281
+ // workflow: no hard deps — uses service: references with Prism mock fallback
2282
+ // when API artifacts aren't available; roles come from user answers
2283
+ workflow: [],
2284
+ // services: needs API endpoints to know what to wire, and optionally
2285
+ // workflow states as trigger sources. Produces OpenAPI specs consumed
2286
+ // by pages and dashboard for typed data wiring.
2287
+ services: ["api", "workflow"],
2288
+ // pages/dashboard: now also depend on services for typed endpoint wiring
2289
+ // via the OpenAPI specs that services produces.
2290
+ // 'api' is still transitive through 'data'; auth removed — page-otter has
2291
+ // graceful fallback and reads role names from workflow artifacts instead
2292
+ pages: ["designer", "theme", "data", "services"],
2293
+ dashboard: ["designer", "theme", "data", "services"],
2294
+ // auth is the penultimate phase — runs after all content-producing phases
2295
+ // so it can read pages, dashboard, workflow, and geo artifacts for route
2296
+ // protection and RBAC wiring. Skipped upstream phases still satisfy deps
2297
+ // (the foreman marks them executed=true), so auth always runs.
2298
+ auth: ["pages", "dashboard", "workflow", "geo"],
2299
+ // polish is the terminal phase — runs after auth so the landing page and
2300
+ // nav reflect the final set of protected routes and all generated pages.
2301
+ polish: ["auth"]
1677
2302
  };
1678
2303
  var PHASE_ARTIFACT = {
1679
2304
  designer: "design-language.json",
@@ -1683,7 +2308,10 @@ var PHASE_ARTIFACT = {
1683
2308
  data: "data-config.json",
1684
2309
  pages: "pages-manifest.json",
1685
2310
  dashboard: "dashboard-manifest.json",
1686
- workflow: "workflow-config.json"
2311
+ workflow: "workflow-config.json",
2312
+ services: "services-config.json",
2313
+ polish: "polish-manifest.json",
2314
+ geo: "geo-manifest.json"
1687
2315
  };
1688
2316
  var PHASE_TO_OTTER2 = {
1689
2317
  designer: "stackwright-pro-designer-otter",
@@ -1693,7 +2321,10 @@ var PHASE_TO_OTTER2 = {
1693
2321
  data: "stackwright-pro-data-otter",
1694
2322
  pages: "stackwright-pro-page-otter",
1695
2323
  dashboard: "stackwright-pro-dashboard-otter",
1696
- workflow: "stackwright-pro-workflow-otter"
2324
+ workflow: "stackwright-pro-workflow-otter",
2325
+ services: "stackwright-services-otter",
2326
+ polish: "stackwright-pro-polish-otter",
2327
+ geo: "stackwright-pro-geo-otter"
1697
2328
  };
1698
2329
  function isValidPhase(phase) {
1699
2330
  return PHASE_ORDER.includes(phase);
@@ -1723,11 +2354,11 @@ function createDefaultState() {
1723
2354
  };
1724
2355
  }
1725
2356
  function statePath(cwd) {
1726
- return (0, import_path4.join)(cwd, ".stackwright", "pipeline-state.json");
2357
+ return (0, import_path5.join)(cwd, ".stackwright", "pipeline-state.json");
1727
2358
  }
1728
2359
  function readState(cwd) {
1729
2360
  const p = statePath(cwd);
1730
- if (!(0, import_fs4.existsSync)(p)) return createDefaultState();
2361
+ if (!(0, import_fs5.existsSync)(p)) return createDefaultState();
1731
2362
  const raw = JSON.parse(safeReadSync(p));
1732
2363
  if (typeof raw !== "object" || raw === null || raw.version !== "1.0") {
1733
2364
  return createDefaultState();
@@ -1735,26 +2366,26 @@ function readState(cwd) {
1735
2366
  return raw;
1736
2367
  }
1737
2368
  function safeWriteSync(filePath, content) {
1738
- if ((0, import_fs4.existsSync)(filePath)) {
1739
- const stat = (0, import_fs4.lstatSync)(filePath);
2369
+ if ((0, import_fs5.existsSync)(filePath)) {
2370
+ const stat = (0, import_fs5.lstatSync)(filePath);
1740
2371
  if (stat.isSymbolicLink()) {
1741
2372
  throw new Error(`Refusing to write to symlink: ${filePath}`);
1742
2373
  }
1743
2374
  }
1744
- (0, import_fs4.writeFileSync)(filePath, content);
2375
+ (0, import_fs5.writeFileSync)(filePath, content);
1745
2376
  }
1746
2377
  function safeReadSync(filePath) {
1747
- if ((0, import_fs4.existsSync)(filePath)) {
1748
- const stat = (0, import_fs4.lstatSync)(filePath);
2378
+ if ((0, import_fs5.existsSync)(filePath)) {
2379
+ const stat = (0, import_fs5.lstatSync)(filePath);
1749
2380
  if (stat.isSymbolicLink()) {
1750
2381
  throw new Error(`Refusing to read symlink: ${filePath}`);
1751
2382
  }
1752
2383
  }
1753
- return (0, import_fs4.readFileSync)(filePath, "utf-8");
2384
+ return (0, import_fs5.readFileSync)(filePath, "utf-8");
1754
2385
  }
1755
2386
  function writeState(cwd, state) {
1756
- const dir = (0, import_path4.join)(cwd, ".stackwright");
1757
- (0, import_fs4.mkdirSync)(dir, { recursive: true });
2387
+ const dir = (0, import_path5.join)(cwd, ".stackwright");
2388
+ (0, import_fs5.mkdirSync)(dir, { recursive: true });
1758
2389
  state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1759
2390
  safeWriteSync(statePath(cwd), JSON.stringify(state, null, 2) + "\n");
1760
2391
  }
@@ -1775,6 +2406,15 @@ function handleGetPipelineState(_cwd) {
1775
2406
  const cwd = _cwd ?? process.cwd();
1776
2407
  try {
1777
2408
  const state = readState(cwd);
2409
+ const keyPath = (0, import_path5.join)(cwd, ".stackwright", "pipeline-keys.json");
2410
+ if (!(0, import_fs5.existsSync)(keyPath)) {
2411
+ try {
2412
+ const { fingerprint } = initPipelineKeys(cwd);
2413
+ state["signingKeyFingerprint"] = fingerprint;
2414
+ writeState(cwd, state);
2415
+ } catch {
2416
+ }
2417
+ }
1778
2418
  return { text: JSON.stringify(state), isError: false };
1779
2419
  } catch (err) {
1780
2420
  return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
@@ -1826,55 +2466,145 @@ function handleSetPipelineState(input) {
1826
2466
  return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
1827
2467
  }
1828
2468
  }
1829
- function handleCheckExecutionReady(_cwd) {
2469
+ function handleCheckExecutionReady(_cwd, phase) {
1830
2470
  const cwd = _cwd ?? process.cwd();
2471
+ if (phase) {
2472
+ if (!isValidPhase(phase)) {
2473
+ return {
2474
+ text: JSON.stringify({
2475
+ error: true,
2476
+ message: `Invalid phase: ${phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
2477
+ }),
2478
+ isError: true
2479
+ };
2480
+ }
2481
+ const answerFile = (0, import_path5.join)(cwd, ".stackwright", "answers", `${phase}.json`);
2482
+ if (!(0, import_fs5.existsSync)(answerFile)) {
2483
+ return {
2484
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file not found" }),
2485
+ isError: false
2486
+ };
2487
+ }
2488
+ try {
2489
+ const raw = safeReadSync(answerFile);
2490
+ const parsed = JSON.parse(raw);
2491
+ if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
2492
+ return {
2493
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file is malformed" }),
2494
+ isError: false
2495
+ };
2496
+ }
2497
+ return { text: JSON.stringify({ ready: true, phase }), isError: false };
2498
+ } catch {
2499
+ return {
2500
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file could not be parsed" }),
2501
+ isError: false
2502
+ };
2503
+ }
2504
+ }
1831
2505
  try {
1832
- const answersDir = (0, import_path4.join)(cwd, ".stackwright", "answers");
2506
+ const answersDir = (0, import_path5.join)(cwd, ".stackwright", "answers");
1833
2507
  const answeredPhases = [];
1834
2508
  const missingPhases = [];
2509
+ for (const phase2 of PHASE_ORDER) {
2510
+ const answerFile = (0, import_path5.join)(answersDir, `${phase2}.json`);
2511
+ if ((0, import_fs5.existsSync)(answerFile)) {
2512
+ try {
2513
+ const raw = safeReadSync(answerFile);
2514
+ const parsed = JSON.parse(raw);
2515
+ if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
2516
+ missingPhases.push(phase2);
2517
+ continue;
2518
+ }
2519
+ answeredPhases.push(phase2);
2520
+ } catch {
2521
+ missingPhases.push(phase2);
2522
+ }
2523
+ } else {
2524
+ missingPhases.push(phase2);
2525
+ }
2526
+ }
2527
+ return {
2528
+ text: JSON.stringify({
2529
+ ready: missingPhases.length === 0,
2530
+ answeredPhases,
2531
+ missingPhases,
2532
+ totalPhases: PHASE_ORDER.length
2533
+ }),
2534
+ isError: false
2535
+ };
2536
+ } catch (err) {
2537
+ return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
2538
+ }
2539
+ }
2540
+ function handleGetReadyPhases(_cwd) {
2541
+ const cwd = _cwd ?? process.cwd();
2542
+ try {
2543
+ const state = readState(cwd);
2544
+ const completed = [];
2545
+ const ready = [];
2546
+ const blocked = [];
1835
2547
  for (const phase of PHASE_ORDER) {
1836
- const answerFile = (0, import_path4.join)(answersDir, `${phase}.json`);
1837
- if ((0, import_fs4.existsSync)(answerFile)) {
1838
- try {
1839
- const raw = safeReadSync(answerFile);
1840
- const parsed = JSON.parse(raw);
1841
- if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
1842
- missingPhases.push(phase);
1843
- continue;
1844
- }
1845
- answeredPhases.push(phase);
1846
- } catch {
1847
- missingPhases.push(phase);
1848
- }
2548
+ const ps = state.phases[phase];
2549
+ if (ps?.executed) {
2550
+ completed.push(phase);
2551
+ continue;
2552
+ }
2553
+ const deps = PHASE_DEPENDENCIES[phase];
2554
+ const unmetDeps = deps.filter((dep) => !state.phases[dep]?.executed);
2555
+ if (unmetDeps.length === 0) {
2556
+ ready.push(phase);
1849
2557
  } else {
1850
- missingPhases.push(phase);
2558
+ blocked.push(phase);
1851
2559
  }
1852
2560
  }
1853
2561
  return {
1854
2562
  text: JSON.stringify({
1855
- ready: missingPhases.length === 0,
1856
- answeredPhases,
1857
- missingPhases,
1858
- totalPhases: PHASE_ORDER.length
2563
+ readyPhases: ready,
2564
+ completedPhases: completed,
2565
+ blockedPhases: blocked,
2566
+ waveSize: ready.length,
2567
+ allComplete: ready.length === 0 && blocked.length === 0
1859
2568
  }),
1860
2569
  isError: false
1861
2570
  };
1862
2571
  } catch (err) {
1863
- return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
2572
+ const message = err instanceof Error ? err.message : String(err);
2573
+ return { text: JSON.stringify({ error: true, message }), isError: true };
1864
2574
  }
1865
2575
  }
1866
2576
  function handleListArtifacts(_cwd) {
1867
2577
  const cwd = _cwd ?? process.cwd();
1868
2578
  try {
1869
- const artifactsDir = (0, import_path4.join)(cwd, ".stackwright", "artifacts");
2579
+ const artifactsDir = (0, import_path5.join)(cwd, ".stackwright", "artifacts");
2580
+ let manifest = null;
2581
+ try {
2582
+ manifest = loadSignatureManifest(cwd);
2583
+ } catch {
2584
+ }
1870
2585
  const artifacts = [];
1871
2586
  let completedCount = 0;
1872
2587
  for (const phase of PHASE_ORDER) {
1873
2588
  const expectedFile = PHASE_ARTIFACT[phase];
1874
- const fullPath = (0, import_path4.join)(artifactsDir, expectedFile);
1875
- const exists = (0, import_fs4.existsSync)(fullPath);
2589
+ const fullPath = (0, import_path5.join)(artifactsDir, expectedFile);
2590
+ const exists = (0, import_fs5.existsSync)(fullPath);
1876
2591
  if (exists) completedCount++;
1877
- artifacts.push({ phase, expectedFile, exists, path: fullPath });
2592
+ let signed = false;
2593
+ let signatureValid = null;
2594
+ if (exists && manifest) {
2595
+ const entry = manifest.signatures[expectedFile];
2596
+ if (entry) {
2597
+ signed = true;
2598
+ try {
2599
+ const rawBytes = Buffer.from(safeReadSync(fullPath), "utf-8");
2600
+ const { publicKey } = loadPipelineKeys(cwd);
2601
+ signatureValid = verifyArtifact(rawBytes, entry, publicKey);
2602
+ } catch {
2603
+ signatureValid = null;
2604
+ }
2605
+ }
2606
+ }
2607
+ artifacts.push({ phase, expectedFile, exists, path: fullPath, signed, signatureValid });
1878
2608
  }
1879
2609
  return {
1880
2610
  text: JSON.stringify({ artifacts, completedCount, totalCount: PHASE_ORDER.length }),
@@ -1910,9 +2640,9 @@ function handleWritePhaseQuestions(input) {
1910
2640
  }
1911
2641
  } catch {
1912
2642
  }
1913
- const questionsDir = (0, import_path4.join)(cwd, ".stackwright", "questions");
1914
- (0, import_fs4.mkdirSync)(questionsDir, { recursive: true });
1915
- const filePath = (0, import_path4.join)(questionsDir, `${phase}.json`);
2643
+ const questionsDir = (0, import_path5.join)(cwd, ".stackwright", "questions");
2644
+ (0, import_fs5.mkdirSync)(questionsDir, { recursive: true });
2645
+ const filePath = (0, import_path5.join)(questionsDir, `${phase}.json`);
1916
2646
  const payload = {
1917
2647
  version: "1.0",
1918
2648
  phase,
@@ -1952,36 +2682,81 @@ function handleBuildSpecialistPrompt(input) {
1952
2682
  };
1953
2683
  }
1954
2684
  try {
1955
- const answersPath = (0, import_path4.join)(cwd, ".stackwright", "answers", `${phase}.json`);
2685
+ const answersPath = (0, import_path5.join)(cwd, ".stackwright", "answers", `${phase}.json`);
1956
2686
  let answers = {};
1957
- if ((0, import_fs4.existsSync)(answersPath)) {
2687
+ if ((0, import_fs5.existsSync)(answersPath)) {
1958
2688
  answers = JSON.parse(safeReadSync(answersPath));
1959
2689
  }
2690
+ let buildContextText = "";
2691
+ const buildContextPath = (0, import_path5.join)(cwd, ".stackwright", "build-context.json");
2692
+ if ((0, import_fs5.existsSync)(buildContextPath)) {
2693
+ try {
2694
+ const bcRaw = JSON.parse(safeReadSync(buildContextPath));
2695
+ if (typeof bcRaw.buildContext === "string" && bcRaw.buildContext.trim().length > 0) {
2696
+ buildContextText = bcRaw.buildContext.trim();
2697
+ }
2698
+ } catch {
2699
+ }
2700
+ }
1960
2701
  const deps = PHASE_DEPENDENCIES[phase];
1961
2702
  const artifactSections = [];
1962
2703
  const missingDependencies = [];
1963
2704
  for (const dep of deps) {
1964
2705
  const artifactFile = PHASE_ARTIFACT[dep];
1965
- const artifactPath = (0, import_path4.join)(cwd, ".stackwright", "artifacts", artifactFile);
1966
- if ((0, import_fs4.existsSync)(artifactPath)) {
1967
- const content = JSON.parse(safeReadSync(artifactPath));
2706
+ const artifactPath = (0, import_path5.join)(cwd, ".stackwright", "artifacts", artifactFile);
2707
+ if ((0, import_fs5.existsSync)(artifactPath)) {
2708
+ const rawContent = safeReadSync(artifactPath);
2709
+ const rawBytes = Buffer.from(rawContent, "utf-8");
2710
+ const content = JSON.parse(rawContent);
2711
+ let signatureVerified = false;
2712
+ let signatureAvailable = false;
2713
+ try {
2714
+ const sig = getArtifactSignature(cwd, artifactFile);
2715
+ if (sig) {
2716
+ signatureAvailable = true;
2717
+ const { publicKey } = loadPipelineKeys(cwd);
2718
+ signatureVerified = verifyArtifact(rawBytes, sig, publicKey);
2719
+ if (!signatureVerified) {
2720
+ const actualDigest = (0, import_crypto3.createHash)("sha384").update(rawBytes).digest("hex");
2721
+ emitSignatureAuditEvent({
2722
+ artifactFilename: artifactFile,
2723
+ expectedDigest: sig.digest,
2724
+ actualDigest,
2725
+ phase: dep,
2726
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2727
+ source: "stackwright_pro_build_specialist_prompt"
2728
+ });
2729
+ missingDependencies.push(dep);
2730
+ artifactSections.push(
2731
+ `[${artifactFile}]:
2732
+ (integrity check failed: ECDSA-P384 signature verification failed \u2014 artifact may have been tampered with)`
2733
+ );
2734
+ continue;
2735
+ }
2736
+ }
2737
+ } catch {
2738
+ }
1968
2739
  const expectedOtter = PHASE_TO_OTTER2[dep];
1969
2740
  const artifactOtter = content["generatedBy"];
2741
+ const normalizedOtter = artifactOtter?.replace(/-[a-f0-9]{6}$/, "");
1970
2742
  if (!artifactOtter) {
1971
2743
  missingDependencies.push(dep);
1972
2744
  artifactSections.push(
1973
2745
  `[${artifactFile}]:
1974
2746
  (integrity check failed: missing generatedBy field)`
1975
2747
  );
1976
- } else if (artifactOtter !== expectedOtter) {
2748
+ } else if (normalizedOtter !== expectedOtter) {
1977
2749
  missingDependencies.push(dep);
1978
2750
  artifactSections.push(
1979
2751
  `[${artifactFile}]:
1980
2752
  (integrity check failed: artifact claims generatedBy="${artifactOtter}" but expected="${expectedOtter}")`
1981
2753
  );
1982
2754
  } else {
1983
- artifactSections.push(`[${artifactFile}]:
1984
- ${JSON.stringify(content, null, 2)}`);
2755
+ const sigStatus = signatureAvailable ? signatureVerified ? " [signature verified]" : " [signature check skipped]" : " [unsigned]";
2756
+ artifactSections.push(
2757
+ `[${artifactFile}]${sigStatus}:
2758
+ ${JSON.stringify(content, null, 2)}`
2759
+ );
1985
2760
  }
1986
2761
  } else {
1987
2762
  missingDependencies.push(dep);
@@ -1989,10 +2764,17 @@ ${JSON.stringify(content, null, 2)}`);
1989
2764
  (not yet available)`);
1990
2765
  }
1991
2766
  }
1992
- const parts = ["ANSWERS:", JSON.stringify(answers, null, 2)];
2767
+ const parts = [];
2768
+ if (buildContextText) {
2769
+ parts.push("BUILD_CONTEXT:", buildContextText, "");
2770
+ }
2771
+ parts.push("ANSWERS:", JSON.stringify(answers, null, 2));
1993
2772
  if (artifactSections.length > 0) {
1994
2773
  parts.push("", "UPSTREAM ARTIFACTS:", "", ...artifactSections);
1995
2774
  }
2775
+ const artifactSchema = PHASE_ARTIFACT_SCHEMA[phase];
2776
+ parts.push("", "REQUIRED_ARTIFACT_SCHEMA:");
2777
+ parts.push(artifactSchema);
1996
2778
  parts.push("", "Execute using these answers and the upstream artifacts provided.");
1997
2779
  const prompt = parts.join("\n");
1998
2780
  const dependenciesSatisfied = missingDependencies.length === 0;
@@ -2027,45 +2809,301 @@ var OFF_SCRIPT_PATTERNS = [
2027
2809
  var PHASE_REQUIRED_KEYS = {
2028
2810
  designer: ["designLanguage", "themeTokenSeeds"],
2029
2811
  theme: ["tokens"],
2030
- api: ["entities"],
2812
+ api: ["entities", "version", "generatedBy"],
2031
2813
  auth: ["version", "generatedBy"],
2032
- data: ["version", "generatedBy"],
2814
+ data: ["version", "generatedBy", "strategy", "collections"],
2033
2815
  pages: ["version", "generatedBy"],
2034
2816
  dashboard: ["version", "generatedBy"],
2035
- workflow: ["version", "generatedBy"]
2817
+ workflow: ["version", "generatedBy"],
2818
+ services: ["version", "generatedBy", "flows"],
2819
+ polish: ["version", "generatedBy"],
2820
+ geo: ["version", "generatedBy", "geoCollections"]
2821
+ };
2822
+ var PHASE_ARTIFACT_SCHEMA = {
2823
+ designer: JSON.stringify(
2824
+ {
2825
+ version: "1.0",
2826
+ generatedBy: "stackwright-pro-designer-otter",
2827
+ application: {
2828
+ type: "<operational|data-explorer|admin|logistics|general>",
2829
+ environment: "<workstation|field|control-room|mixed>",
2830
+ density: "<compact|balanced|spacious>",
2831
+ accessibility: "<wcag-aa|section-508|none>",
2832
+ colorScheme: "<light|dark|both>"
2833
+ },
2834
+ designLanguage: {
2835
+ rationale: "<design rationale>",
2836
+ spacingScale: { base: 8, scale: [0, 4, 8, 16, 24, 32, 48, 64] },
2837
+ colorSemantics: { primary: "#1a365d", accent: "#e53e3e" },
2838
+ typography: {
2839
+ dataFont: "Inter",
2840
+ headingFont: "Inter",
2841
+ monoFont: "monospace",
2842
+ dataSizePx: 12,
2843
+ bodySizePx: 14
2844
+ },
2845
+ contrastRatio: "4.5",
2846
+ borderRadius: "4",
2847
+ shadowElevation: "standard"
2848
+ },
2849
+ themeTokenSeeds: {
2850
+ light: {
2851
+ background: "#ffffff",
2852
+ foreground: "#1a1a1a",
2853
+ primary: "#1a365d",
2854
+ surface: "#f7f7f7",
2855
+ border: "#e2e8f0"
2856
+ },
2857
+ dark: {
2858
+ background: "#1a1a1a",
2859
+ foreground: "#ffffff",
2860
+ primary: "#90cdf4",
2861
+ surface: "#2d2d2d",
2862
+ border: "#4a5568"
2863
+ }
2864
+ },
2865
+ conformsTo: null,
2866
+ operationalNotes: []
2867
+ },
2868
+ null,
2869
+ 2
2870
+ ),
2871
+ theme: JSON.stringify(
2872
+ {
2873
+ version: "1.0",
2874
+ generatedBy: "stackwright-pro-theme-otter",
2875
+ componentLibrary: "shadcn",
2876
+ colorScheme: "<light|dark|both>",
2877
+ tokens: {
2878
+ colors: { "primary-500": "#1a365d", background: "#ffffff" },
2879
+ spacing: { "spacing-1": "8px", "spacing-2": "16px" },
2880
+ typography: { "font-data": "Inter", "text-sm": "12px" },
2881
+ shape: { "radius-sm": "4px", "radius-md": "8px" },
2882
+ shadows: { "shadow-sm": "0 1px 2px rgba(0,0,0,0.08)" }
2883
+ },
2884
+ cssVariables: {
2885
+ "--background": "0 0% 100%",
2886
+ "--foreground": "222.2 84% 4.9%",
2887
+ "--primary": "222.2 47.4% 11.2%",
2888
+ "--primary-foreground": "210 40% 98%",
2889
+ "--surface": "210 40% 98%",
2890
+ "--border": "214.3 31.8% 91.4%"
2891
+ },
2892
+ dark: { "--background": "222.2 84% 4.9%", "--foreground": "210 40% 98%" }
2893
+ },
2894
+ null,
2895
+ 2
2896
+ ),
2897
+ api: JSON.stringify(
2898
+ {
2899
+ version: "1.0",
2900
+ generatedBy: "stackwright-pro-api-otter",
2901
+ entities: [
2902
+ {
2903
+ name: "Shipment",
2904
+ endpoint: "/shipments",
2905
+ method: "GET",
2906
+ revalidate: 60,
2907
+ mutationType: null
2908
+ }
2909
+ ],
2910
+ auth: { type: "bearer", header: "Authorization", envVar: "API_TOKEN" },
2911
+ baseUrl: "https://api.example.mil/v2",
2912
+ specPath: "./specs/api.yaml"
2913
+ },
2914
+ null,
2915
+ 2
2916
+ ),
2917
+ data: JSON.stringify(
2918
+ {
2919
+ version: "1.0",
2920
+ generatedBy: "stackwright-pro-data-otter",
2921
+ strategy: "<pulse-fast|isr-fast|isr-standard|isr-slow>",
2922
+ pulseMode: false,
2923
+ collections: [{ name: "equipment", revalidate: 60, pulse: false }],
2924
+ endpoints: { included: ["/equipment/**"], excluded: ["/admin/**"] },
2925
+ requiredPackages: { dependencies: {}, devPackages: {} }
2926
+ },
2927
+ null,
2928
+ 2
2929
+ ),
2930
+ geo: JSON.stringify(
2931
+ {
2932
+ version: "1.0",
2933
+ generatedBy: "stackwright-pro-geo-otter",
2934
+ geoCollections: [
2935
+ {
2936
+ collection: "vessels",
2937
+ latField: "latitude",
2938
+ lngField: "longitude",
2939
+ labelField: "vesselName",
2940
+ colorField: "navigationStatus"
2941
+ }
2942
+ ],
2943
+ pages: [
2944
+ {
2945
+ slug: "fleet-tracker",
2946
+ type: "<tracker|zone|route|combined>",
2947
+ collections: ["vessels"],
2948
+ hasLayers: false
2949
+ }
2950
+ ]
2951
+ },
2952
+ null,
2953
+ 2
2954
+ ),
2955
+ workflow: JSON.stringify(
2956
+ {
2957
+ version: "1.0",
2958
+ generatedBy: "stackwright-pro-workflow-otter",
2959
+ workflowConfig: {
2960
+ id: "procurement-approval",
2961
+ route: "/procurement",
2962
+ files: ["workflows/procurement-approval.yml"],
2963
+ serviceDependencies: ["service:workflow-state"],
2964
+ warnings: []
2965
+ }
2966
+ },
2967
+ null,
2968
+ 2
2969
+ ),
2970
+ services: JSON.stringify(
2971
+ {
2972
+ version: "1.0",
2973
+ generatedBy: "stackwright-services-otter",
2974
+ flows: [
2975
+ {
2976
+ name: "at-risk-patients",
2977
+ trigger: "<http|event|schedule|queue>",
2978
+ steps: 3,
2979
+ outputSpec: "at-risk-patients.openapi.json"
2980
+ }
2981
+ ],
2982
+ workflows: [
2983
+ {
2984
+ name: "evacuation-coordination",
2985
+ states: 4,
2986
+ transitions: 5
2987
+ }
2988
+ ],
2989
+ openApiSpecs: ["at-risk-patients.openapi.json"],
2990
+ capabilitiesUsed: ["service.call", "collection.join", "collection.filter"]
2991
+ },
2992
+ null,
2993
+ 2
2994
+ ),
2995
+ pages: JSON.stringify(
2996
+ {
2997
+ version: "1.0",
2998
+ generatedBy: "stackwright-pro-page-otter",
2999
+ pages: [
3000
+ {
3001
+ slug: "catalog",
3002
+ type: "collection_listing",
3003
+ collection: "products",
3004
+ themeApplied: true,
3005
+ authRequired: false
3006
+ },
3007
+ {
3008
+ slug: "admin",
3009
+ type: "protected",
3010
+ collection: null,
3011
+ themeApplied: true,
3012
+ authRequired: true
3013
+ }
3014
+ ]
3015
+ },
3016
+ null,
3017
+ 2
3018
+ ),
3019
+ dashboard: JSON.stringify(
3020
+ {
3021
+ version: "1.0",
3022
+ generatedBy: "stackwright-pro-dashboard-otter",
3023
+ pages: [
3024
+ {
3025
+ slug: "dashboard",
3026
+ layout: "<grid|table|mixed>",
3027
+ collections: ["equipment", "supplies"],
3028
+ mode: "<ISR|Pulse>"
3029
+ }
3030
+ ]
3031
+ },
3032
+ null,
3033
+ 2
3034
+ ),
3035
+ // type: 'pki' = CAC/DoD certificate auth | 'oidc' = enterprise SSO
3036
+ // For dev-only mock auth: use type: 'oidc' with devOnly: true (Zod strips devOnly — it's a convention only)
3037
+ auth: JSON.stringify(
3038
+ {
3039
+ version: "1.0",
3040
+ generatedBy: "stackwright-pro-auth-otter",
3041
+ authConfig: {
3042
+ type: "<pki|oidc>",
3043
+ // OIDC-only fields (omit for pki):
3044
+ provider: "<azure_ad|okta|cognito|auth0|authentik|keycloak|custom>",
3045
+ discoveryUrl: "<IdP OIDC discovery URL>",
3046
+ clientId: "<OIDC client ID>",
3047
+ clientSecret: "<OIDC client secret>",
3048
+ rbacRoles: ["ADMIN", "ANALYST"],
3049
+ rbacDefaultRole: "ANALYST",
3050
+ protectedRoutes: ["/dashboard/:path*", "/procurement/:path*"],
3051
+ auditEnabled: true,
3052
+ auditRetentionDays: 90
3053
+ }
3054
+ },
3055
+ null,
3056
+ 2
3057
+ ),
3058
+ polish: JSON.stringify(
3059
+ {
3060
+ version: "1.0",
3061
+ generatedBy: "stackwright-pro-polish-otter",
3062
+ landingPage: { slug: "", rewritten: true },
3063
+ navigation: { itemCount: 5, items: ["/dashboard", "/equipment", "/workflows"] },
3064
+ gettingStarted: "<rewritten|redirected|not-found>"
3065
+ },
3066
+ null,
3067
+ 2
3068
+ )
2036
3069
  };
2037
3070
  function handleValidateArtifact(input) {
2038
3071
  const cwd = input._cwd ?? process.cwd();
2039
- const { phase, responseText } = input;
3072
+ const { phase, responseText, artifact: directArtifact } = input;
2040
3073
  if (!isValidPhase(phase)) {
2041
3074
  return {
2042
3075
  text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
2043
3076
  isError: true
2044
3077
  };
2045
3078
  }
2046
- for (const { pattern, label } of OFF_SCRIPT_PATTERNS) {
2047
- if (pattern.test(responseText)) {
3079
+ let artifact;
3080
+ if (directArtifact) {
3081
+ artifact = directArtifact;
3082
+ } else {
3083
+ const text = responseText ?? "";
3084
+ for (const { pattern, label } of OFF_SCRIPT_PATTERNS) {
3085
+ if (pattern.test(text)) {
3086
+ const result = {
3087
+ valid: false,
3088
+ phase,
3089
+ violation: "off-script",
3090
+ retryPrompt: `You returned code output (detected: ${label}). Return ONLY a JSON artifact \u2014 no code, no files.`
3091
+ };
3092
+ return { text: JSON.stringify(result), isError: false };
3093
+ }
3094
+ }
3095
+ try {
3096
+ artifact = extractJsonFromResponse(text);
3097
+ } catch {
2048
3098
  const result = {
2049
3099
  valid: false,
2050
3100
  phase,
2051
- violation: "off-script",
2052
- retryPrompt: `You returned code output (detected: ${label}). Return ONLY a JSON artifact \u2014 no code, no files.`
3101
+ violation: "invalid-json",
3102
+ retryPrompt: "Your response did not contain valid JSON. Return a single JSON object with no surrounding text."
2053
3103
  };
2054
3104
  return { text: JSON.stringify(result), isError: false };
2055
3105
  }
2056
3106
  }
2057
- let artifact;
2058
- try {
2059
- artifact = extractJsonFromResponse(responseText);
2060
- } catch {
2061
- const result = {
2062
- valid: false,
2063
- phase,
2064
- violation: "invalid-json",
2065
- retryPrompt: "Your response did not contain valid JSON. Return a single JSON object with no surrounding text."
2066
- };
2067
- return { text: JSON.stringify(result), isError: false };
2068
- }
2069
3107
  if (!artifact.version || !artifact.generatedBy) {
2070
3108
  const result = {
2071
3109
  valid: false,
@@ -2086,12 +3124,58 @@ function handleValidateArtifact(input) {
2086
3124
  };
2087
3125
  return { text: JSON.stringify(result), isError: false };
2088
3126
  }
3127
+ const PHASE_ZOD_VALIDATORS = {
3128
+ workflow: (artifact2) => {
3129
+ const workflowConfig = artifact2["workflowConfig"];
3130
+ if (!workflowConfig) return { success: true };
3131
+ const result = import_types.WorkflowFileSchema.safeParse(workflowConfig);
3132
+ if (!result.success) {
3133
+ const issues = result.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
3134
+ return { success: false, error: { message: issues } };
3135
+ }
3136
+ return { success: true };
3137
+ },
3138
+ auth: (artifact2) => {
3139
+ const authConfig = artifact2["authConfig"];
3140
+ if (!authConfig) return { success: true };
3141
+ const result = import_types.authConfigSchema.safeParse(authConfig);
3142
+ if (!result.success) {
3143
+ const issues = result.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
3144
+ return { success: false, error: { message: issues } };
3145
+ }
3146
+ return { success: true };
3147
+ }
3148
+ };
3149
+ const zodValidator = PHASE_ZOD_VALIDATORS[phase];
3150
+ if (zodValidator) {
3151
+ const zodResult = zodValidator(artifact);
3152
+ if (!zodResult.success) {
3153
+ const result = {
3154
+ valid: false,
3155
+ phase,
3156
+ violation: "schema-mismatch",
3157
+ retryPrompt: `Your artifact failed schema validation: ${zodResult.error?.message}. Fix these fields and return the corrected JSON artifact.`
3158
+ };
3159
+ return { text: JSON.stringify(result), isError: false };
3160
+ }
3161
+ }
2089
3162
  try {
2090
- const artifactsDir = (0, import_path4.join)(cwd, ".stackwright", "artifacts");
2091
- (0, import_fs4.mkdirSync)(artifactsDir, { recursive: true });
3163
+ const artifactsDir = (0, import_path5.join)(cwd, ".stackwright", "artifacts");
3164
+ (0, import_fs5.mkdirSync)(artifactsDir, { recursive: true });
2092
3165
  const artifactFile = PHASE_ARTIFACT[phase];
2093
- const artifactPath = (0, import_path4.join)(artifactsDir, artifactFile);
2094
- safeWriteSync(artifactPath, JSON.stringify(artifact, null, 2) + "\n");
3166
+ const artifactPath = (0, import_path5.join)(artifactsDir, artifactFile);
3167
+ const serialized = JSON.stringify(artifact, null, 2) + "\n";
3168
+ const artifactBytes = Buffer.from(serialized, "utf-8");
3169
+ safeWriteSync(artifactPath, serialized);
3170
+ let signed = false;
3171
+ try {
3172
+ const { privateKey } = loadPipelineKeys(cwd);
3173
+ const sig = signArtifact(artifactBytes, privateKey);
3174
+ const signerOtter = PHASE_TO_OTTER2[phase];
3175
+ saveArtifactSignature(cwd, artifactFile, sig, signerOtter);
3176
+ signed = true;
3177
+ } catch {
3178
+ }
2095
3179
  const state = readState(cwd);
2096
3180
  if (!state.phases[phase]) state.phases[phase] = defaultPhaseStatus();
2097
3181
  const ps = state.phases[phase];
@@ -2102,7 +3186,7 @@ function handleValidateArtifact(input) {
2102
3186
  valid: true,
2103
3187
  phase,
2104
3188
  artifactPath,
2105
- summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})`
3189
+ summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})${signed ? " [signed]" : ""}`
2106
3190
  };
2107
3191
  return { text: JSON.stringify(result), isError: false };
2108
3192
  } catch (err) {
@@ -2126,11 +3210,15 @@ function registerPipelineTools(server2) {
2126
3210
  "stackwright_pro_set_pipeline_state",
2127
3211
  `Atomic read\u2192modify\u2192write pipeline state. ${DESC}`,
2128
3212
  {
2129
- phase: import_zod9.z.string().optional().describe('Phase to update, e.g. "designer"'),
2130
- field: import_zod9.z.enum(["questionsCollected", "answered", "executed", "artifactWritten"]).optional().describe("Boolean field to set"),
2131
- value: import_zod9.z.boolean().optional().describe("Value for the field"),
2132
- status: import_zod9.z.enum(["setup", "questions", "execution", "done"]).optional().describe("Top-level status override"),
2133
- incrementRetry: import_zod9.z.boolean().optional().describe("Bump retryCount by 1")
3213
+ phase: import_zod11.z.string().optional().describe('Phase to update, e.g. "designer"'),
3214
+ field: import_zod11.z.enum(["questionsCollected", "answered", "executed", "artifactWritten"]).optional().describe("Boolean field to set"),
3215
+ value: boolCoerce(import_zod11.z.boolean().optional()).describe(
3216
+ 'Value for the field \u2014 must be a JSON boolean (true/false), NOT the string "true"/"false"'
3217
+ ),
3218
+ status: import_zod11.z.enum(["setup", "questions", "execution", "done"]).optional().describe("Top-level status override"),
3219
+ incrementRetry: boolCoerce(import_zod11.z.boolean().optional()).describe(
3220
+ "Bump retryCount by 1 \u2014 must be a JSON boolean"
3221
+ )
2134
3222
  },
2135
3223
  async (args) => res(
2136
3224
  handleSetPipelineState({
@@ -2144,9 +3232,17 @@ function registerPipelineTools(server2) {
2144
3232
  );
2145
3233
  server2.tool(
2146
3234
  "stackwright_pro_check_execution_ready",
2147
- `Check all phases have answer files in .stackwright/answers/. ${DESC}`,
3235
+ `Check all phases have answer files in .stackwright/answers/. If phase is provided, check only that phase. ${DESC}`,
3236
+ {
3237
+ phase: import_zod11.z.string().optional().describe("If provided, check only this phase's readiness. Omit to check all phases.")
3238
+ },
3239
+ async ({ phase }) => res(handleCheckExecutionReady(void 0, phase))
3240
+ );
3241
+ server2.tool(
3242
+ "stackwright_pro_get_ready_phases",
3243
+ `Return phases whose dependencies are all satisfied (executed=true). Use to determine which phases can run next \u2014 enables wave-based execution. ${DESC}`,
2148
3244
  {},
2149
- async () => res(handleCheckExecutionReady())
3245
+ async () => res(handleGetReadyPhases())
2150
3246
  );
2151
3247
  server2.tool(
2152
3248
  "stackwright_pro_list_artifacts",
@@ -2156,40 +3252,92 @@ function registerPipelineTools(server2) {
2156
3252
  );
2157
3253
  server2.tool(
2158
3254
  "stackwright_pro_write_phase_questions",
2159
- `Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. ${DESC}`,
3255
+ `Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. Specialists may also call this directly with a parsed questions array. ${DESC}`,
2160
3256
  {
2161
- phase: import_zod9.z.string().describe('Phase name, e.g. "designer"'),
2162
- responseText: import_zod9.z.string().describe("Raw LLM response from QUESTION_COLLECTION_MODE")
3257
+ phase: import_zod11.z.string().optional().describe('Phase name, e.g. "designer" (required for direct write)'),
3258
+ responseText: import_zod11.z.string().optional().describe("Raw LLM response from QUESTION_COLLECTION_MODE"),
3259
+ questions: jsonCoerce(import_zod11.z.array(import_zod11.z.any()).optional()).describe(
3260
+ "Questions array for direct specialist write"
3261
+ )
2163
3262
  },
2164
- async ({ phase, responseText }) => res(handleWritePhaseQuestions({ phase, responseText }))
3263
+ async ({ phase, responseText, questions }) => {
3264
+ if (phase && questions && Array.isArray(questions)) {
3265
+ const SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
3266
+ if (!SAFE_PHASE.test(phase)) {
3267
+ return {
3268
+ content: [
3269
+ { type: "text", text: JSON.stringify({ error: `Invalid phase name` }) }
3270
+ ],
3271
+ isError: true
3272
+ };
3273
+ }
3274
+ const questionsDir = (0, import_path5.join)(process.cwd(), ".stackwright", "questions");
3275
+ (0, import_fs5.mkdirSync)(questionsDir, { recursive: true });
3276
+ const outPath = (0, import_path5.join)(questionsDir, `${phase}.json`);
3277
+ (0, import_fs5.writeFileSync)(
3278
+ outPath,
3279
+ JSON.stringify({ phase, questions, writtenAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2)
3280
+ );
3281
+ return {
3282
+ content: [
3283
+ {
3284
+ type: "text",
3285
+ text: JSON.stringify({
3286
+ written: true,
3287
+ phase,
3288
+ count: questions.length
3289
+ })
3290
+ }
3291
+ ]
3292
+ };
3293
+ }
3294
+ return res(
3295
+ handleWritePhaseQuestions({ phase: phase ?? "", responseText: responseText ?? "" })
3296
+ );
3297
+ }
2165
3298
  );
2166
3299
  server2.tool(
2167
3300
  "stackwright_pro_build_specialist_prompt",
2168
3301
  `Assemble execution prompt from answers + upstream artifacts. Foreman passes verbatim. ${DESC}`,
2169
- { phase: import_zod9.z.string().describe('Phase to build prompt for, e.g. "pages"') },
3302
+ { phase: import_zod11.z.string().describe('Phase to build prompt for, e.g. "pages"') },
2170
3303
  async ({ phase }) => res(handleBuildSpecialistPrompt({ phase }))
2171
3304
  );
2172
3305
  server2.tool(
2173
3306
  "stackwright_pro_validate_artifact",
2174
- `Validate specialist response + write artifact to .stackwright/artifacts/. Returns retryPrompt on failure. ${DESC}`,
3307
+ `Validate and write artifact to .stackwright/artifacts/. Returns retryPrompt on failure. ${DESC}`,
2175
3308
  {
2176
- phase: import_zod9.z.string().describe('Phase that produced this artifact, e.g. "designer"'),
2177
- responseText: import_zod9.z.string().describe("Raw response text from the specialist otter")
3309
+ phase: import_zod11.z.string().describe('Phase that produced this artifact, e.g. "designer"'),
3310
+ responseText: import_zod11.z.string().optional().describe("Raw response text from the specialist otter (Foreman-mediated path, legacy)"),
3311
+ artifact: jsonCoerce(import_zod11.z.record(import_zod11.z.string(), import_zod11.z.unknown()).optional()).describe(
3312
+ "Artifact object to validate and write directly (specialist direct path \u2014 skips off-script detection and JSON parsing)"
3313
+ )
2178
3314
  },
2179
- async ({ phase, responseText }) => res(handleValidateArtifact({ phase, responseText }))
3315
+ async ({ phase, responseText, artifact }) => {
3316
+ if (artifact) {
3317
+ return res(
3318
+ handleValidateArtifact({ phase, artifact })
3319
+ );
3320
+ }
3321
+ return res(handleValidateArtifact({ phase, responseText: responseText ?? "" }));
3322
+ }
2180
3323
  );
2181
3324
  }
2182
3325
 
2183
3326
  // src/tools/safe-write.ts
2184
- var import_zod10 = require("zod");
2185
- var import_fs5 = require("fs");
2186
- var import_path5 = require("path");
3327
+ var import_zod12 = require("zod");
3328
+ var import_fs6 = require("fs");
3329
+ var import_path6 = require("path");
2187
3330
  var OTTER_WRITE_ALLOWLISTS = {
2188
3331
  "stackwright-pro-designer-otter": [
2189
3332
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Design language artifact" }
2190
3333
  ],
2191
3334
  "stackwright-pro-theme-otter": [
2192
- { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" }
3335
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" },
3336
+ {
3337
+ prefix: "stackwright.theme.",
3338
+ suffix: ".yml",
3339
+ description: "Theme config YAML (merged at build time)"
3340
+ }
2193
3341
  ],
2194
3342
  "stackwright-pro-auth-otter": [
2195
3343
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Auth config artifact" },
@@ -2222,19 +3370,60 @@ var OTTER_WRITE_ALLOWLISTS = {
2222
3370
  ],
2223
3371
  "stackwright-pro-api-otter": [
2224
3372
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "API config artifact" }
3373
+ ],
3374
+ "stackwright-pro-geo-otter": [
3375
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Geo manifest artifact" },
3376
+ { prefix: "pages/", suffix: "/content.yml", description: "Map page content" },
3377
+ { prefix: "pages/", suffix: "/content.yaml", description: "Map page content" }
3378
+ ],
3379
+ "stackwright-pro-polish-otter": [
3380
+ {
3381
+ prefix: "stackwright.yml",
3382
+ suffix: "",
3383
+ description: "Stackwright config (navigation updates)"
3384
+ },
3385
+ { prefix: "pages/", suffix: "/content.yml", description: "Landing page content" },
3386
+ { prefix: "pages/", suffix: "/content.yaml", description: "Landing page content" },
3387
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Polish artifact" }
3388
+ ],
3389
+ "stackwright-services-otter": [
3390
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Services config artifact" },
3391
+ { prefix: "services/", suffix: ".ts", description: "Service implementation files" },
3392
+ { prefix: "services/", suffix: ".yaml", description: "Service flow definitions" },
3393
+ { prefix: "services/", suffix: ".yml", description: "Service flow definitions" },
3394
+ { prefix: "lib/seeds/", suffix: ".ts", description: "Seed data files" },
3395
+ { prefix: "specs/", suffix: ".json", description: "Generated OpenAPI specs" },
3396
+ { prefix: "specs/", suffix: ".yaml", description: "Generated OpenAPI specs" },
3397
+ { prefix: "stackwright-generated/", suffix: ".json", description: "Services manifest" }
2225
3398
  ]
2226
3399
  };
2227
3400
  var PROTECTED_PATH_PREFIXES = [
2228
3401
  ".stackwright/pipeline-state.json",
3402
+ ".stackwright/pipeline-keys.json",
3403
+ // ephemeral signing keys
3404
+ ".stackwright/artifacts/signatures.json",
3405
+ // artifact signature manifest
2229
3406
  ".stackwright/questions/",
2230
3407
  ".stackwright/answers/"
2231
3408
  ];
3409
+ var MAX_SAFE_WRITE_BYTES_JSON = 512 * 1024;
3410
+ var MAX_SAFE_WRITE_BYTES_YAML = 256 * 1024;
3411
+ var MAX_SAFE_WRITE_BYTES_ENV = 4 * 1024;
3412
+ var MAX_SAFE_WRITE_BYTES_DEFAULT = 256 * 1024;
3413
+ function getMaxBytesForPath(filePath) {
3414
+ if (filePath.endsWith(".json")) return { limit: MAX_SAFE_WRITE_BYTES_JSON, label: "JSON" };
3415
+ if (filePath.endsWith(".yml") || filePath.endsWith(".yaml"))
3416
+ return { limit: MAX_SAFE_WRITE_BYTES_YAML, label: "YAML" };
3417
+ if (filePath === ".env" || /^\.env\.[a-zA-Z0-9]+/.test(filePath))
3418
+ return { limit: MAX_SAFE_WRITE_BYTES_ENV, label: "env" };
3419
+ return { limit: MAX_SAFE_WRITE_BYTES_DEFAULT, label: "default" };
3420
+ }
2232
3421
  function checkPathAllowed(callerOtter, filePath) {
2233
- const normalized = (0, import_path5.normalize)(filePath);
3422
+ const normalized = (0, import_path6.normalize)(filePath);
2234
3423
  if (normalized.includes("..")) {
2235
3424
  return { allowed: false, error: 'Path traversal detected: ".." segments are not allowed' };
2236
3425
  }
2237
- if ((0, import_path5.isAbsolute)(normalized)) {
3426
+ if ((0, import_path6.isAbsolute)(normalized)) {
2238
3427
  return {
2239
3428
  allowed: false,
2240
3429
  error: "Absolute paths are not allowed \u2014 use paths relative to project root"
@@ -2354,11 +3543,23 @@ function handleSafeWrite(input) {
2354
3543
  };
2355
3544
  return { text: JSON.stringify(result), isError: true };
2356
3545
  }
2357
- const normalized = (0, import_path5.normalize)(filePath);
2358
- const fullPath = (0, import_path5.join)(cwd, normalized);
2359
- if ((0, import_fs5.existsSync)(fullPath)) {
3546
+ const contentBytes = Buffer.byteLength(content, "utf-8");
3547
+ const { limit: maxBytes, label: fileTypeLabel } = getMaxBytesForPath(filePath);
3548
+ if (contentBytes > maxBytes) {
3549
+ const result = {
3550
+ success: false,
3551
+ error: `Content size ${contentBytes} bytes exceeds ${fileTypeLabel} limit of ${maxBytes} bytes (${maxBytes / 1024} KB)`,
3552
+ callerOtter,
3553
+ attemptedPath: filePath,
3554
+ allowedPaths: []
3555
+ };
3556
+ return { text: JSON.stringify(result), isError: true };
3557
+ }
3558
+ const normalized = (0, import_path6.normalize)(filePath);
3559
+ const fullPath = (0, import_path6.join)(cwd, normalized);
3560
+ if ((0, import_fs6.existsSync)(fullPath)) {
2360
3561
  try {
2361
- const stat = (0, import_fs5.lstatSync)(fullPath);
3562
+ const stat = (0, import_fs6.lstatSync)(fullPath);
2362
3563
  if (stat.isSymbolicLink()) {
2363
3564
  const result = {
2364
3565
  success: false,
@@ -2385,9 +3586,9 @@ function handleSafeWrite(input) {
2385
3586
  }
2386
3587
  try {
2387
3588
  if (createDirectories) {
2388
- (0, import_fs5.mkdirSync)((0, import_path5.dirname)(fullPath), { recursive: true });
3589
+ (0, import_fs6.mkdirSync)((0, import_path6.dirname)(fullPath), { recursive: true });
2389
3590
  }
2390
- (0, import_fs5.writeFileSync)(fullPath, content, { encoding: "utf-8" });
3591
+ (0, import_fs6.writeFileSync)(fullPath, content, { encoding: "utf-8" });
2391
3592
  const result = {
2392
3593
  success: true,
2393
3594
  path: normalized,
@@ -2413,10 +3614,12 @@ function registerSafeWriteTools(server2) {
2413
3614
  "stackwright_pro_safe_write",
2414
3615
  DESC,
2415
3616
  {
2416
- callerOtter: import_zod10.z.string().describe('The otter agent name requesting the write, e.g. "stackwright-pro-page-otter"'),
2417
- filePath: import_zod10.z.string().describe('Relative path from project root, e.g. "pages/dashboard/content.yml"'),
2418
- content: import_zod10.z.string().describe("File content to write"),
2419
- createDirectories: import_zod10.z.boolean().optional().describe("Create parent directories if they don't exist. Default: true")
3617
+ callerOtter: import_zod12.z.string().describe('The otter agent name requesting the write, e.g. "stackwright-pro-page-otter"'),
3618
+ filePath: import_zod12.z.string().describe('Relative path from project root, e.g. "pages/dashboard/content.yml"'),
3619
+ content: import_zod12.z.string().describe("File content to write"),
3620
+ createDirectories: boolCoerce(import_zod12.z.boolean().optional().default(true)).describe(
3621
+ "Create parent directories if they don't exist. Default: true"
3622
+ )
2420
3623
  },
2421
3624
  async ({ callerOtter, filePath, content, createDirectories }) => {
2422
3625
  const result = handleSafeWrite({
@@ -2431,9 +3634,9 @@ function registerSafeWriteTools(server2) {
2431
3634
  }
2432
3635
 
2433
3636
  // src/tools/auth.ts
2434
- var import_zod11 = require("zod");
2435
- var import_fs6 = require("fs");
2436
- var import_path6 = require("path");
3637
+ var import_zod13 = require("zod");
3638
+ var import_fs7 = require("fs");
3639
+ var import_path7 = require("path");
2437
3640
  function buildHierarchy(roles) {
2438
3641
  const h = {};
2439
3642
  for (let i = 0; i < roles.length - 1; i++) {
@@ -2695,7 +3898,7 @@ async function configureAuthHandler(params, cwd) {
2695
3898
  auditRetentionDays,
2696
3899
  protectedRoutes
2697
3900
  );
2698
- (0, import_fs6.writeFileSync)((0, import_path6.join)(cwd, "middleware.ts"), middlewareContent, "utf8");
3901
+ (0, import_fs7.writeFileSync)((0, import_path7.join)(cwd, "middleware.ts"), middlewareContent, "utf8");
2699
3902
  filesWritten.push("middleware.ts");
2700
3903
  } catch (err) {
2701
3904
  const msg = err instanceof Error ? err.message : String(err);
@@ -2711,12 +3914,12 @@ async function configureAuthHandler(params, cwd) {
2711
3914
  }
2712
3915
  try {
2713
3916
  const envBlock = generateEnvBlock(method, params);
2714
- const envPath = (0, import_path6.join)(cwd, ".env.example");
2715
- if ((0, import_fs6.existsSync)(envPath)) {
2716
- const existing = (0, import_fs6.readFileSync)(envPath, "utf8");
2717
- (0, import_fs6.writeFileSync)(envPath, existing.trimEnd() + "\n\n" + envBlock, "utf8");
3917
+ const envPath = (0, import_path7.join)(cwd, ".env.example");
3918
+ if ((0, import_fs7.existsSync)(envPath)) {
3919
+ const existing = (0, import_fs7.readFileSync)(envPath, "utf8");
3920
+ (0, import_fs7.writeFileSync)(envPath, existing.trimEnd() + "\n\n" + envBlock, "utf8");
2718
3921
  } else {
2719
- (0, import_fs6.writeFileSync)(envPath, envBlock, "utf8");
3922
+ (0, import_fs7.writeFileSync)(envPath, envBlock, "utf8");
2720
3923
  }
2721
3924
  filesWritten.push(".env.example");
2722
3925
  } catch (err) {
@@ -2742,12 +3945,12 @@ async function configureAuthHandler(params, cwd) {
2742
3945
  auditRetentionDays,
2743
3946
  protectedRoutes
2744
3947
  );
2745
- const ymlPath = (0, import_path6.join)(cwd, "stackwright.yml");
2746
- if (!(0, import_fs6.existsSync)(ymlPath)) {
2747
- (0, import_fs6.writeFileSync)(ymlPath, authYaml, "utf8");
3948
+ const ymlPath = (0, import_path7.join)(cwd, "stackwright.yml");
3949
+ if (!(0, import_fs7.existsSync)(ymlPath)) {
3950
+ (0, import_fs7.writeFileSync)(ymlPath, authYaml, "utf8");
2748
3951
  } else {
2749
- const existing = (0, import_fs6.readFileSync)(ymlPath, "utf8");
2750
- (0, import_fs6.writeFileSync)(ymlPath, upsertAuthBlock(existing, authYaml), "utf8");
3952
+ const existing = (0, import_fs7.readFileSync)(ymlPath, "utf8");
3953
+ (0, import_fs7.writeFileSync)(ymlPath, upsertAuthBlock(existing, authYaml), "utf8");
2751
3954
  }
2752
3955
  filesWritten.push("stackwright.yml");
2753
3956
  } catch (err) {
@@ -2786,35 +3989,35 @@ function registerAuthTools(server2) {
2786
3989
  "stackwright_pro_configure_auth",
2787
3990
  "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.",
2788
3991
  {
2789
- method: import_zod11.z.enum(["cac", "oidc", "oauth2", "none"]),
2790
- provider: import_zod11.z.enum(["azure-ad", "okta", "ping", "cognito", "custom"]).optional(),
3992
+ method: import_zod13.z.enum(["cac", "oidc", "oauth2", "none"]),
3993
+ provider: import_zod13.z.enum(["azure-ad", "okta", "ping", "cognito", "custom"]).optional(),
2791
3994
  // CAC
2792
- cacCaBundle: import_zod11.z.string().optional(),
2793
- cacEdipiLookup: import_zod11.z.string().optional(),
2794
- cacOcspEndpoint: import_zod11.z.string().optional(),
2795
- cacCertHeader: import_zod11.z.string().optional(),
3995
+ cacCaBundle: import_zod13.z.string().optional(),
3996
+ cacEdipiLookup: import_zod13.z.string().optional(),
3997
+ cacOcspEndpoint: import_zod13.z.string().optional(),
3998
+ cacCertHeader: import_zod13.z.string().optional(),
2796
3999
  // OIDC
2797
- oidcDiscoveryUrl: import_zod11.z.string().optional(),
2798
- oidcClientId: import_zod11.z.string().optional(),
2799
- oidcClientSecret: import_zod11.z.string().optional(),
2800
- oidcScopes: import_zod11.z.string().optional(),
2801
- oidcRoleClaim: import_zod11.z.string().optional(),
4000
+ oidcDiscoveryUrl: import_zod13.z.string().optional(),
4001
+ oidcClientId: import_zod13.z.string().optional(),
4002
+ oidcClientSecret: import_zod13.z.string().optional(),
4003
+ oidcScopes: import_zod13.z.string().optional(),
4004
+ oidcRoleClaim: import_zod13.z.string().optional(),
2802
4005
  // OAuth2
2803
- oauth2AuthUrl: import_zod11.z.string().optional(),
2804
- oauth2TokenUrl: import_zod11.z.string().optional(),
2805
- oauth2ClientId: import_zod11.z.string().optional(),
2806
- oauth2ClientSecret: import_zod11.z.string().optional(),
2807
- oauth2Scopes: import_zod11.z.string().optional(),
4006
+ oauth2AuthUrl: import_zod13.z.string().optional(),
4007
+ oauth2TokenUrl: import_zod13.z.string().optional(),
4008
+ oauth2ClientId: import_zod13.z.string().optional(),
4009
+ oauth2ClientSecret: import_zod13.z.string().optional(),
4010
+ oauth2Scopes: import_zod13.z.string().optional(),
2808
4011
  // RBAC
2809
- rbacRoles: import_zod11.z.array(import_zod11.z.string()).optional(),
2810
- rbacDefaultRole: import_zod11.z.string().optional(),
4012
+ rbacRoles: jsonCoerce(import_zod13.z.array(import_zod13.z.string()).optional()),
4013
+ rbacDefaultRole: import_zod13.z.string().optional(),
2811
4014
  // Audit
2812
- auditEnabled: import_zod11.z.boolean().optional(),
2813
- auditRetentionDays: import_zod11.z.number().int().positive().optional(),
4015
+ auditEnabled: boolCoerce(import_zod13.z.boolean().optional()),
4016
+ auditRetentionDays: numCoerce(import_zod13.z.number().int().positive().optional()),
2814
4017
  // Routes
2815
- protectedRoutes: import_zod11.z.array(import_zod11.z.string()).optional(),
4018
+ protectedRoutes: jsonCoerce(import_zod13.z.array(import_zod13.z.string()).optional()),
2816
4019
  // Injection for tests
2817
- _cwd: import_zod11.z.string().optional()
4020
+ _cwd: import_zod13.z.string().optional()
2818
4021
  },
2819
4022
  async (params) => {
2820
4023
  const cwd = params._cwd ?? process.cwd();
@@ -2824,45 +4027,61 @@ function registerAuthTools(server2) {
2824
4027
  }
2825
4028
 
2826
4029
  // src/integrity.ts
2827
- var import_crypto2 = require("crypto");
2828
- var import_fs7 = require("fs");
2829
- var import_path7 = require("path");
4030
+ var import_crypto4 = require("crypto");
4031
+ var import_fs8 = require("fs");
4032
+ var import_path8 = require("path");
2830
4033
  var _checksums = /* @__PURE__ */ new Map([
2831
4034
  [
2832
4035
  "stackwright-pro-api-otter.json",
2833
- "f1cc9edf2dd1df3ebcea1d0ab33d17a358faaf8aa97ee232cd7994042f2eac0d"
4036
+ "9fbaed0ce6116b82d0289f24432037d04637c89b8e73062ed946e5d49b294734"
2834
4037
  ],
2835
4038
  [
2836
4039
  "stackwright-pro-auth-otter.json",
2837
- "a19e06c503209a8a35fe321d30448623545b36b48c47a6ec064d13406ad1f725"
4040
+ "8a6ee02cfe7fede3ca708d05b8b46824eb71f60c7f474b6edf9599da77f779b2"
2838
4041
  ],
2839
4042
  [
2840
4043
  "stackwright-pro-dashboard-otter.json",
2841
- "b3cb3d7554f2e9eed3b57d5e0e3bf85d6ba5b4db5d3af5514391cf0575fcc001"
4044
+ "f5a83b74ad7c44edc6f39b45a568fa122d82aa4788f741ce14614da56d4e29a4"
2842
4045
  ],
2843
4046
  [
2844
4047
  "stackwright-pro-data-otter.json",
2845
- "bfacb87ae82867472a75982215554336a105a658d6cd3dd2c8b819fa1e11d7ac"
4048
+ "c406e1c775bcb1f2b038b40a92d9bd23172b40d774fc0fa50bad4c9714f53445"
2846
4049
  ],
2847
4050
  [
2848
4051
  "stackwright-pro-designer-otter.json",
2849
- "c58fa7c7ead9e6398074e1c7ce3f31a8ef4eb3679f5fa18cc03cae3a87878c88"
4052
+ "af09ac8f06385bdbac63e2820daa2ff7d38b8ff1ff383c161f07e3fb9d9359c5"
4053
+ ],
4054
+ [
4055
+ "stackwright-pro-domain-expert-otter.json",
4056
+ "bfe5c167d73fef3f2ef280fff56dcb552073c218e1394a43ecf983a03169ed55"
2850
4057
  ],
2851
4058
  [
2852
4059
  "stackwright-pro-foreman-otter.json",
2853
- "84ba692e710ac3efab94d27332bcac19c6785b7f41d9076e8e7c860cdd6f8097"
4060
+ "ab38ef53b95ec610a38b2866d78a135cbec16d257a9b35d7e46e2fee2d4de235"
4061
+ ],
4062
+ [
4063
+ "stackwright-pro-geo-otter.json",
4064
+ "6eb7ecf97254dbd79c09ad24348bf16001423cce9585c14bef81afd67b7b901b"
2854
4065
  ],
2855
4066
  [
2856
4067
  "stackwright-pro-page-otter.json",
2857
- "65bec3a3a0dda6b7591bba2de9399f1e3a4fb99cfe1075342f4f4be98d917b67"
4068
+ "9a5672f0758c81539337d86955e2892cd412547b4f111c2aa098eed1e62d7626"
4069
+ ],
4070
+ [
4071
+ "stackwright-pro-polish-otter.json",
4072
+ "d31116995fdb417798af6056efd03bb1c71e0891371aba1774d283c03c9d77e8"
2858
4073
  ],
2859
4074
  [
2860
4075
  "stackwright-pro-theme-otter.json",
2861
- "64ffaeeceacd739922788a1d074f6feaffc3f91d09706c2c104f0c0281677732"
4076
+ "08bb04009fdfb8743b10ac4d503cbaddaf8d7c804ba9b606aaed9cc516fd8e93"
2862
4077
  ],
2863
4078
  [
2864
4079
  "stackwright-pro-workflow-otter.json",
2865
- "0eec9d6a731678cf547c2a7b0b6fc338ca143c35501365a1e4e5dd2779dd5510"
4080
+ "c90d6773b2287aa9a640c2715ca0e75f44c13e99fddcfb89ced36603f38930ce"
4081
+ ],
4082
+ [
4083
+ "stackwright-services-otter.json",
4084
+ "4893a596d187110124f78336ee91184a51b3c8d980c455382fe481adb9b487b5"
2866
4085
  ]
2867
4086
  ]);
2868
4087
  Object.freeze(_checksums);
@@ -2877,21 +4096,21 @@ for (const [name, digest] of CANONICAL_CHECKSUMS) {
2877
4096
  }
2878
4097
  var MAX_OTTER_BYTES = 1 * 1024 * 1024;
2879
4098
  function computeSha256(data) {
2880
- return (0, import_crypto2.createHash)("sha256").update(data).digest("hex");
4099
+ return (0, import_crypto4.createHash)("sha256").update(data).digest("hex");
2881
4100
  }
2882
4101
  function safeEqual(a, b) {
2883
4102
  if (a.length !== b.length) return false;
2884
- return (0, import_crypto2.timingSafeEqual)(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
4103
+ return (0, import_crypto4.timingSafeEqual)(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
2885
4104
  }
2886
4105
  function verifyOtterFile(filePath) {
2887
- const filename = (0, import_path7.basename)(filePath);
4106
+ const filename = (0, import_path8.basename)(filePath);
2888
4107
  const expected = CANONICAL_CHECKSUMS.get(filename);
2889
4108
  if (expected === void 0) {
2890
4109
  return { verified: false, filename, error: `Unknown otter file: not in canonical set` };
2891
4110
  }
2892
4111
  let stat;
2893
4112
  try {
2894
- stat = (0, import_fs7.lstatSync)(filePath);
4113
+ stat = (0, import_fs8.lstatSync)(filePath);
2895
4114
  } catch (err) {
2896
4115
  const msg = err instanceof Error ? err.message : String(err);
2897
4116
  return { verified: false, filename, error: `Cannot stat file: ${msg}` };
@@ -2909,7 +4128,7 @@ function verifyOtterFile(filePath) {
2909
4128
  }
2910
4129
  let raw;
2911
4130
  try {
2912
- raw = (0, import_fs7.readFileSync)(filePath);
4131
+ raw = (0, import_fs8.readFileSync)(filePath);
2913
4132
  } catch (err) {
2914
4133
  const msg = err instanceof Error ? err.message : String(err);
2915
4134
  return { verified: false, filename, error: `Cannot read file: ${msg}` };
@@ -2942,12 +4161,24 @@ function verifyOtterFile(filePath) {
2942
4161
  return { verified: true, filename };
2943
4162
  }
2944
4163
  function verifyAllOtters(otterDir) {
4164
+ if (/(?:^|[/\\])\.\.(?:[/\\]|$)/.test(otterDir) || otterDir.includes("..")) {
4165
+ return {
4166
+ verified: [],
4167
+ failed: [
4168
+ {
4169
+ filename: "<directory>",
4170
+ error: `Security: path traversal sequence detected in otter directory parameter`
4171
+ }
4172
+ ],
4173
+ unknown: []
4174
+ };
4175
+ }
2945
4176
  const verified = [];
2946
4177
  const failed = [];
2947
4178
  const unknown = [];
2948
4179
  let entries;
2949
4180
  try {
2950
- entries = (0, import_fs7.readdirSync)(otterDir);
4181
+ entries = (0, import_fs8.readdirSync)(otterDir);
2951
4182
  } catch (err) {
2952
4183
  const msg = err instanceof Error ? err.message : String(err);
2953
4184
  return {
@@ -2958,9 +4189,9 @@ function verifyAllOtters(otterDir) {
2958
4189
  }
2959
4190
  const otterFiles = entries.filter((f) => f.endsWith("-otter.json"));
2960
4191
  for (const filename of otterFiles) {
2961
- const filePath = (0, import_path7.join)(otterDir, filename);
4192
+ const filePath = (0, import_path8.join)(otterDir, filename);
2962
4193
  try {
2963
- if ((0, import_fs7.lstatSync)(filePath).isSymbolicLink()) {
4194
+ if ((0, import_fs8.lstatSync)(filePath).isSymbolicLink()) {
2964
4195
  failed.push({ filename, error: "Skipped: symlink" });
2965
4196
  continue;
2966
4197
  }
@@ -2986,15 +4217,30 @@ var DEFAULT_SEARCH_PATHS = ["node_modules/@stackwright-pro/otters/src/", "packag
2986
4217
  function resolveOtterDir() {
2987
4218
  const cwd = process.cwd();
2988
4219
  for (const relative of DEFAULT_SEARCH_PATHS) {
2989
- const candidate = (0, import_path7.join)(cwd, relative);
4220
+ const candidate = (0, import_path8.join)(cwd, relative);
2990
4221
  try {
2991
- (0, import_fs7.lstatSync)(candidate);
4222
+ (0, import_fs8.lstatSync)(candidate);
2992
4223
  return candidate;
2993
4224
  } catch {
2994
4225
  }
2995
4226
  }
2996
4227
  return null;
2997
4228
  }
4229
+ function emitIntegrityAuditEvent(params) {
4230
+ const record = JSON.stringify({
4231
+ level: "AUDIT",
4232
+ event: "INTEGRITY_FAIL",
4233
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
4234
+ source: "stackwright_pro_verify_otter_integrity",
4235
+ otterDir: params.otterDir,
4236
+ failedCount: params.failed.length,
4237
+ unknownCount: params.unknown.length,
4238
+ failures: params.failed,
4239
+ unknown: params.unknown
4240
+ });
4241
+ process.stderr.write(`INTEGRITY_FAIL ${record}
4242
+ `);
4243
+ }
2998
4244
  function registerIntegrityTools(server2) {
2999
4245
  server2.tool(
3000
4246
  "stackwright_pro_verify_otter_integrity",
@@ -3018,6 +4264,13 @@ function registerIntegrityTools(server2) {
3018
4264
  }
3019
4265
  const result = verifyAllOtters(resolved);
3020
4266
  const allGood = result.failed.length === 0 && result.unknown.length === 0;
4267
+ if (!allGood) {
4268
+ emitIntegrityAuditEvent({
4269
+ otterDir: resolved,
4270
+ failed: result.failed,
4271
+ unknown: result.unknown
4272
+ });
4273
+ }
3021
4274
  return {
3022
4275
  content: [
3023
4276
  {
@@ -3030,7 +4283,10 @@ function registerIntegrityTools(server2) {
3030
4283
  unknownCount: result.unknown.length,
3031
4284
  verified: result.verified,
3032
4285
  failed: result.failed,
3033
- unknown: result.unknown
4286
+ unknown: result.unknown,
4287
+ ...allGood ? {} : {
4288
+ error: "INTEGRITY CHECK FAILED: SHA-256 mismatch detected in otter agent definitions. Do not proceed \u2014 otter files may have been tampered with."
4289
+ }
3034
4290
  })
3035
4291
  }
3036
4292
  ],
@@ -3041,14 +4297,14 @@ function registerIntegrityTools(server2) {
3041
4297
  }
3042
4298
 
3043
4299
  // src/tools/domain.ts
3044
- var import_zod12 = require("zod");
3045
- var import_fs8 = require("fs");
3046
- var import_path8 = require("path");
4300
+ var import_zod14 = require("zod");
4301
+ var import_fs9 = require("fs");
4302
+ var import_path9 = require("path");
3047
4303
  function handleListCollections(input) {
3048
4304
  const cwd = input._cwd ?? process.cwd();
3049
4305
  const sources = [
3050
4306
  {
3051
- path: (0, import_path8.join)(cwd, ".stackwright", "artifacts", "data-config.json"),
4307
+ path: (0, import_path9.join)(cwd, ".stackwright", "artifacts", "data-config.json"),
3052
4308
  source: "data-config.json",
3053
4309
  parse: (raw) => {
3054
4310
  const parsed = JSON.parse(raw);
@@ -3059,15 +4315,15 @@ function handleListCollections(input) {
3059
4315
  }
3060
4316
  },
3061
4317
  {
3062
- path: (0, import_path8.join)(cwd, "stackwright.yml"),
4318
+ path: (0, import_path9.join)(cwd, "stackwright.yml"),
3063
4319
  source: "stackwright.yml",
3064
4320
  parse: extractCollectionsFromYaml
3065
4321
  }
3066
4322
  ];
3067
4323
  for (const { path: path3, source, parse } of sources) {
3068
- if (!(0, import_fs8.existsSync)(path3)) continue;
4324
+ if (!(0, import_fs9.existsSync)(path3)) continue;
3069
4325
  try {
3070
- const collections = parse((0, import_fs8.readFileSync)(path3, "utf8"));
4326
+ const collections = parse((0, import_fs9.readFileSync)(path3, "utf8"));
3071
4327
  return {
3072
4328
  text: JSON.stringify({ collections, source, collectionCount: collections.length }),
3073
4329
  isError: false
@@ -3218,8 +4474,8 @@ function handleValidateWorkflow(input) {
3218
4474
  if (input.workflow && Object.keys(input.workflow).length > 0) {
3219
4475
  raw = input.workflow;
3220
4476
  } else {
3221
- const artifactPath = (0, import_path8.join)(cwd, ".stackwright", "artifacts", "workflow-config.json");
3222
- if (!(0, import_fs8.existsSync)(artifactPath)) {
4477
+ const artifactPath = (0, import_path9.join)(cwd, ".stackwright", "artifacts", "workflow-config.json");
4478
+ if (!(0, import_fs9.existsSync)(artifactPath)) {
3223
4479
  return fail([
3224
4480
  {
3225
4481
  code: "NO_WORKFLOW",
@@ -3228,7 +4484,7 @@ function handleValidateWorkflow(input) {
3228
4484
  ]);
3229
4485
  }
3230
4486
  try {
3231
- raw = JSON.parse((0, import_fs8.readFileSync)(artifactPath, "utf8"));
4487
+ raw = JSON.parse((0, import_fs9.readFileSync)(artifactPath, "utf8"));
3232
4488
  } catch (err) {
3233
4489
  return fail([{ code: "INVALID_JSON", message: `Failed to parse workflow artifact: ${err}` }]);
3234
4490
  }
@@ -3427,7 +4683,7 @@ function registerDomainTools(server2) {
3427
4683
  "stackwright_pro_resolve_data_strategy",
3428
4684
  "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.",
3429
4685
  {
3430
- strategy: import_zod12.z.string().describe(
4686
+ strategy: import_zod14.z.string().describe(
3431
4687
  'The data-1 answer value: "pulse-fast", "isr-fast", "isr-standard", or "isr-slow"'
3432
4688
  )
3433
4689
  },
@@ -3437,7 +4693,7 @@ function registerDomainTools(server2) {
3437
4693
  "stackwright_pro_validate_workflow",
3438
4694
  "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.",
3439
4695
  {
3440
- workflow: import_zod12.z.record(import_zod12.z.string(), import_zod12.z.unknown()).optional().describe(
4696
+ workflow: jsonCoerce(import_zod14.z.record(import_zod14.z.string(), import_zod14.z.unknown()).optional()).describe(
3441
4697
  "Parsed workflow object. If omitted, reads from .stackwright/artifacts/workflow-config.json"
3442
4698
  )
3443
4699
  },
@@ -3445,18 +4701,109 @@ function registerDomainTools(server2) {
3445
4701
  );
3446
4702
  }
3447
4703
 
4704
+ // src/tools/type-schemas.ts
4705
+ var import_zod15 = require("zod");
4706
+ function buildTypeSchemaSummary() {
4707
+ return {
4708
+ version: "1.0",
4709
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
4710
+ domains: {
4711
+ workflow: {
4712
+ description: "Workflow DSL \u2014 step definitions, auth blocks, field types, conditions",
4713
+ schemas: [
4714
+ "WorkflowFileSchema",
4715
+ "WorkflowDefinitionSchema",
4716
+ "WorkflowStepSchema",
4717
+ "WorkflowStepTypeSchema",
4718
+ "WorkflowFieldSchema",
4719
+ "WorkflowActionSchema",
4720
+ "WorkflowAuthSchema",
4721
+ "WorkflowThemeSchema",
4722
+ "TransitionConditionSchema",
4723
+ "PersistenceSchema"
4724
+ ],
4725
+ otter: "stackwright-pro-workflow-otter",
4726
+ artifactKey: "workflowConfig"
4727
+ },
4728
+ auth: {
4729
+ description: "Authentication providers \u2014 PKI/CAC, OIDC, RBAC configuration",
4730
+ schemas: [
4731
+ "authConfigSchema",
4732
+ "pkiConfigSchema",
4733
+ "oidcConfigSchema",
4734
+ "rbacConfigSchema",
4735
+ "componentAuthSchema",
4736
+ "authUserSchema",
4737
+ "authSessionSchema"
4738
+ ],
4739
+ otter: "stackwright-pro-auth-otter",
4740
+ artifactKey: "authConfig"
4741
+ },
4742
+ openapi: {
4743
+ description: "OpenAPI spec integration \u2014 collection config, endpoint filters, actions",
4744
+ interfaces: [
4745
+ "OpenAPIConfig",
4746
+ "ActionConfig",
4747
+ "EndpointFilter",
4748
+ "ApprovedSpec",
4749
+ "PrebuildSecurityConfig",
4750
+ "SiteConfig",
4751
+ "ValidationResult"
4752
+ ],
4753
+ otter: "stackwright-pro-api-otter",
4754
+ artifactKey: "apiConfig"
4755
+ },
4756
+ pulse: {
4757
+ description: "Real-time data polling \u2014 source-agnostic polling options and states",
4758
+ interfaces: ["PulseOptions", "PulseMeta", "PulseState"],
4759
+ note: "React-bound types (PulseProps, PulseIndicatorProps) remain in @stackwright-pro/pulse"
4760
+ },
4761
+ enterprise: {
4762
+ description: "Enterprise collection access \u2014 multi-tenant provider extension",
4763
+ interfaces: [
4764
+ "EnterpriseCollectionProvider",
4765
+ "CollectionProvider",
4766
+ "CollectionEntry",
4767
+ "CollectionListOptions",
4768
+ "CollectionListResult",
4769
+ "TenantFilter",
4770
+ "Collection"
4771
+ ],
4772
+ note: "CollectionProvider, CollectionEntry, CollectionListOptions, and CollectionListResult are re-exported from @stackwright/types (^1.5.0). EnterpriseCollectionProvider, TenantFilter, and Collection are Pro-only extensions."
4773
+ }
4774
+ }
4775
+ };
4776
+ }
4777
+ function registerTypeSchemasTool(server2) {
4778
+ server2.tool(
4779
+ "stackwright_pro_get_type_schemas",
4780
+ "Returns a structured summary of all canonical @stackwright-pro/types schemas, organized by domain. Use this to determine which otter owns a given schema and what artifact key to expect.",
4781
+ {
4782
+ format: import_zod15.z.enum(["full", "domains-only"]).optional().default("full").describe("full = complete summary with all fields; domains-only = just domain names")
4783
+ },
4784
+ async ({ format }) => {
4785
+ const summary = buildTypeSchemaSummary();
4786
+ const output = format === "domains-only" ? Object.keys(summary.domains) : summary;
4787
+ return {
4788
+ content: [{ type: "text", text: JSON.stringify(output, null, 2) }]
4789
+ };
4790
+ }
4791
+ );
4792
+ }
4793
+
3448
4794
  // package.json
3449
4795
  var package_default = {
3450
4796
  dependencies: {
4797
+ "@stackwright-pro/types": "workspace:*",
3451
4798
  "@modelcontextprotocol/sdk": "^1.10.0",
3452
4799
  "@stackwright-pro/cli-data-explorer": "workspace:*",
3453
- zod: "^4.3.6"
4800
+ zod: "^4.4.3"
3454
4801
  },
3455
4802
  devDependencies: {
3456
- "@types/node": "^24.1.0",
3457
- tsup: "^8.5.0",
3458
- typescript: "^5.8.3",
3459
- vitest: "^4.0.18"
4803
+ "@types/node": "catalog:",
4804
+ tsup: "catalog:",
4805
+ typescript: "catalog:",
4806
+ vitest: "catalog:"
3460
4807
  },
3461
4808
  scripts: {
3462
4809
  prepublishOnly: "node scripts/verify-integrity-sync.js",
@@ -3467,10 +4814,13 @@ var package_default = {
3467
4814
  "test:coverage": "vitest run --coverage"
3468
4815
  },
3469
4816
  name: "@stackwright-pro/mcp",
3470
- version: "0.2.0-alpha.6",
4817
+ version: "0.2.0-alpha.61",
3471
4818
  description: "MCP tools for Stackwright Pro - Data Explorer, Security, ISR, and Dashboard generation",
3472
- license: "PROPRIETARY",
4819
+ license: "SEE LICENSE IN LICENSE",
3473
4820
  main: "./dist/server.js",
4821
+ bin: {
4822
+ "stackwright-pro-mcp": "./dist/server.js"
4823
+ },
3474
4824
  module: "./dist/server.mjs",
3475
4825
  types: "./dist/server.d.ts",
3476
4826
  exports: {
@@ -3483,6 +4833,11 @@ var package_default = {
3483
4833
  types: "./dist/integrity.d.ts",
3484
4834
  import: "./dist/integrity.mjs",
3485
4835
  require: "./dist/integrity.js"
4836
+ },
4837
+ "./type-schemas": {
4838
+ types: "./dist/tools/type-schemas.d.ts",
4839
+ import: "./dist/tools/type-schemas.mjs",
4840
+ require: "./dist/tools/type-schemas.js"
3486
4841
  }
3487
4842
  },
3488
4843
  files: [
@@ -3510,9 +4865,20 @@ registerPipelineTools(server);
3510
4865
  registerSafeWriteTools(server);
3511
4866
  registerAuthTools(server);
3512
4867
  registerIntegrityTools(server);
4868
+ registerArtifactSigningTools(server);
3513
4869
  registerDomainTools(server);
4870
+ registerTypeSchemasTool(server);
3514
4871
  async function main() {
3515
4872
  const transport = new import_stdio.StdioServerTransport();
4873
+ try {
4874
+ const servicesRegisterPkg = "@stackwright-services/mcp/register";
4875
+ const mod = await import(servicesRegisterPkg);
4876
+ if (typeof mod.registerServicesTools === "function") {
4877
+ mod.registerServicesTools(server);
4878
+ console.error("Stackwright Services tools registered on pro MCP");
4879
+ }
4880
+ } catch {
4881
+ }
3516
4882
  await server.connect(transport);
3517
4883
  console.error("Stackwright Pro MCP server running on stdio");
3518
4884
  }