@stackwright-pro/mcp 0.2.0-alpha.8 → 0.2.0-alpha.81

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.'
889
+ ),
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."
839
892
  ),
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(
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) {
@@ -1274,23 +1331,30 @@ function answersToManifestFormat(answers, questions) {
1274
1331
  return result;
1275
1332
  }
1276
1333
 
1334
+ // src/validation.ts
1335
+ var SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
1336
+ var SAFE_QUESTION_ID = /^[a-z0-9][a-z0-9-]{0,63}$/i;
1337
+ function isValidPhase(phase) {
1338
+ return SAFE_PHASE.test(phase);
1339
+ }
1340
+
1277
1341
  // 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()
1342
+ var ManifestQuestionSchema = import_zod8.z.object({
1343
+ id: import_zod8.z.string(),
1344
+ question: import_zod8.z.string(),
1345
+ type: import_zod8.z.enum(["text", "select", "multi-select", "confirm"]),
1346
+ required: import_zod8.z.boolean().optional(),
1347
+ options: import_zod8.z.array(
1348
+ import_zod8.z.object({
1349
+ label: import_zod8.z.string(),
1350
+ value: import_zod8.z.string()
1287
1351
  })
1288
1352
  ).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())])
1353
+ default: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.boolean(), import_zod8.z.array(import_zod8.z.string())]).optional(),
1354
+ help: import_zod8.z.string().optional(),
1355
+ dependsOn: import_zod8.z.object({
1356
+ questionId: import_zod8.z.string(),
1357
+ value: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.array(import_zod8.z.string())])
1294
1358
  }).optional()
1295
1359
  });
1296
1360
  function registerQuestionTools(server2) {
@@ -1298,15 +1362,16 @@ function registerQuestionTools(server2) {
1298
1362
  "stackwright_pro_present_phase_questions",
1299
1363
  "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
1364
  {
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(
1365
+ phase: import_zod8.z.string().describe('Phase name for display context, e.g. "designer", "api", "auth"'),
1366
+ questions: jsonCoerce(import_zod8.z.array(ManifestQuestionSchema).optional()).describe(
1303
1367
  "Questions in Question Manifest format. If omitted, questions are read from .stackwright/question-manifest.json using the phase name."
1304
1368
  ),
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")
1369
+ answers: jsonCoerce(
1370
+ 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()
1371
+ ).describe("Previously collected answers used to resolve dependsOn conditions")
1306
1372
  },
1307
1373
  async ({ phase, questions, answers }) => {
1308
1374
  let resolvedQuestions;
1309
- const SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
1310
1375
  if (!SAFE_PHASE.test(phase)) {
1311
1376
  return {
1312
1377
  content: [
@@ -1353,17 +1418,36 @@ function registerQuestionTools(server2) {
1353
1418
  }
1354
1419
  }
1355
1420
  const adapted = adaptQuestions(resolvedQuestions, answers ?? {});
1421
+ const labelSchema = import_zod8.z.string().max(50, "Value should have at most 50 characters");
1422
+ for (const q of adapted) {
1423
+ for (const opt of q.options) {
1424
+ const check = labelSchema.safeParse(opt.label);
1425
+ if (!check.success) {
1426
+ return {
1427
+ content: [
1428
+ {
1429
+ type: "text",
1430
+ text: JSON.stringify({
1431
+ 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.`
1432
+ })
1433
+ }
1434
+ ],
1435
+ isError: true
1436
+ };
1437
+ }
1438
+ }
1439
+ }
1356
1440
  if (adapted.length === 0) {
1357
1441
  return {
1358
1442
  content: [
1359
1443
  {
1360
1444
  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
- })
1445
+ 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.`
1446
+ },
1447
+ {
1448
+ type: "text",
1449
+ // Empty array — second block always present so the foreman's two-block contract holds
1450
+ text: JSON.stringify([])
1367
1451
  }
1368
1452
  ],
1369
1453
  isError: false
@@ -1384,31 +1468,175 @@ function registerQuestionTools(server2) {
1384
1468
  };
1385
1469
  }
1386
1470
  );
1471
+ server2.tool(
1472
+ "stackwright_pro_get_next_question",
1473
+ "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.",
1474
+ { phase: import_zod8.z.string().describe('Phase name e.g. "designer", "api", "auth"') },
1475
+ async ({ phase }) => {
1476
+ if (!SAFE_PHASE.test(phase)) {
1477
+ return {
1478
+ content: [
1479
+ {
1480
+ type: "text",
1481
+ text: JSON.stringify({ error: `Invalid phase name: "${phase.slice(0, 50)}"` })
1482
+ }
1483
+ ],
1484
+ isError: true
1485
+ };
1486
+ }
1487
+ const cwd = process.cwd();
1488
+ const questionsPath = (0, import_node_path.join)(cwd, ".stackwright", "questions", `${phase}.json`);
1489
+ let questions = [];
1490
+ try {
1491
+ const raw = await (0, import_promises.readFile)(questionsPath, "utf-8");
1492
+ const parsed = JSON.parse(raw);
1493
+ questions = parsed.questions ?? [];
1494
+ } catch {
1495
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1496
+ }
1497
+ if (questions.length === 0) {
1498
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1499
+ }
1500
+ const answersPath = (0, import_node_path.join)(cwd, ".stackwright", "answers", `${phase}.json`);
1501
+ let answeredIds = /* @__PURE__ */ new Set();
1502
+ try {
1503
+ const raw = await (0, import_promises.readFile)(answersPath, "utf-8");
1504
+ const parsed = JSON.parse(raw);
1505
+ answeredIds = new Set(Object.keys(parsed.answers ?? {}));
1506
+ } catch {
1507
+ }
1508
+ const next = questions.find((q) => !answeredIds.has(q.id));
1509
+ if (!next) {
1510
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1511
+ }
1512
+ return {
1513
+ content: [
1514
+ {
1515
+ type: "text",
1516
+ text: JSON.stringify({
1517
+ done: false,
1518
+ questionId: next.id,
1519
+ question: next.question,
1520
+ type: next.type,
1521
+ options: next.options ?? null,
1522
+ help: next.help ?? null,
1523
+ index: questions.indexOf(next) + 1,
1524
+ total: questions.length
1525
+ })
1526
+ }
1527
+ ]
1528
+ };
1529
+ }
1530
+ );
1531
+ server2.tool(
1532
+ "stackwright_pro_record_answer",
1533
+ "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.",
1534
+ {
1535
+ phase: import_zod8.z.string().describe('Phase name e.g. "designer"'),
1536
+ questionId: import_zod8.z.string().describe('The question ID from get_next_question, e.g. "designer-1"'),
1537
+ answer: import_zod8.z.string().describe("The user's free-text answer")
1538
+ },
1539
+ async ({ phase, questionId, answer }) => {
1540
+ if (!SAFE_PHASE.test(phase)) {
1541
+ return {
1542
+ content: [
1543
+ { type: "text", text: JSON.stringify({ error: "Invalid phase name" }) }
1544
+ ],
1545
+ isError: true
1546
+ };
1547
+ }
1548
+ if (!SAFE_QUESTION_ID.test(questionId)) {
1549
+ return {
1550
+ content: [
1551
+ { type: "text", text: JSON.stringify({ error: "Invalid questionId" }) }
1552
+ ],
1553
+ isError: true
1554
+ };
1555
+ }
1556
+ const safeAnswer = answer.slice(0, 2e3);
1557
+ const cwd = process.cwd();
1558
+ const answersDir = (0, import_node_path.join)(cwd, ".stackwright", "answers");
1559
+ const answersPath = (0, import_node_path.join)(answersDir, `${phase}.json`);
1560
+ if ((0, import_node_fs.existsSync)(answersDir) && (0, import_node_fs.lstatSync)(answersDir).isSymbolicLink()) {
1561
+ return {
1562
+ content: [
1563
+ {
1564
+ type: "text",
1565
+ text: JSON.stringify({ error: "answers dir is a symlink \u2014 refusing to write" })
1566
+ }
1567
+ ],
1568
+ isError: true
1569
+ };
1570
+ }
1571
+ (0, import_node_fs.mkdirSync)(answersDir, { recursive: true });
1572
+ let existing = {
1573
+ version: "1.0",
1574
+ phase,
1575
+ answers: {}
1576
+ };
1577
+ try {
1578
+ if ((0, import_node_fs.existsSync)(answersPath)) {
1579
+ if ((0, import_node_fs.lstatSync)(answersPath).isSymbolicLink()) {
1580
+ return {
1581
+ content: [
1582
+ {
1583
+ type: "text",
1584
+ text: JSON.stringify({ error: "answers file is a symlink \u2014 refusing to write" })
1585
+ }
1586
+ ],
1587
+ isError: true
1588
+ };
1589
+ }
1590
+ const raw = await (0, import_promises.readFile)(answersPath, "utf-8");
1591
+ existing = JSON.parse(raw);
1592
+ }
1593
+ } catch {
1594
+ }
1595
+ existing.answers[questionId] = safeAnswer;
1596
+ existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1597
+ const tmp = `${answersPath}.tmp`;
1598
+ await (0, import_promises.writeFile)(tmp, JSON.stringify(existing, null, 2), "utf-8");
1599
+ (0, import_node_fs.renameSync)(tmp, answersPath);
1600
+ return {
1601
+ content: [
1602
+ { type: "text", text: JSON.stringify({ recorded: true, phase, questionId }) }
1603
+ ]
1604
+ };
1605
+ }
1606
+ );
1387
1607
  }
1388
1608
 
1389
1609
  // src/tools/orchestration.ts
1390
- var import_zod8 = require("zod");
1610
+ var import_zod9 = require("zod");
1391
1611
  var import_fs3 = require("fs");
1392
1612
  var import_path3 = require("path");
1393
1613
  var OTTER_NAME_TO_PHASE = [
1394
1614
  ["designer", "designer"],
1395
1615
  ["theme", "theme"],
1616
+ ["scaffold", "scaffold"],
1396
1617
  ["api", "api"],
1397
1618
  ["auth", "auth"],
1398
1619
  ["dashboard", "dashboard"],
1399
1620
  ["data", "data"],
1400
1621
  ["page", "pages"],
1401
- ["workflow", "workflow"]
1622
+ ["workflow", "workflow"],
1623
+ ["services", "services"],
1624
+ ["polish", "polish"],
1625
+ ["geo", "geo"]
1402
1626
  ];
1403
1627
  var PHASE_TO_OTTER = {
1404
1628
  designer: "stackwright-pro-designer-otter",
1405
1629
  theme: "stackwright-pro-theme-otter",
1630
+ scaffold: "stackwright-pro-scaffold-otter",
1406
1631
  api: "stackwright-pro-api-otter",
1407
1632
  auth: "stackwright-pro-auth-otter",
1408
1633
  pages: "stackwright-pro-page-otter",
1409
1634
  dashboard: "stackwright-pro-dashboard-otter",
1410
1635
  data: "stackwright-pro-data-otter",
1411
- workflow: "stackwright-pro-workflow-otter"
1636
+ workflow: "stackwright-pro-workflow-otter",
1637
+ services: "stackwright-services-otter",
1638
+ polish: "stackwright-pro-polish-otter",
1639
+ geo: "stackwright-pro-geo-otter"
1412
1640
  };
1413
1641
  function detectPhase(otterName) {
1414
1642
  const lower = otterName.toLowerCase();
@@ -1474,14 +1702,78 @@ function handleSaveManifest(input) {
1474
1702
  }
1475
1703
  }
1476
1704
  function handleSavePhaseAnswers(input) {
1705
+ if (!isValidPhase(input.phase)) {
1706
+ return {
1707
+ text: JSON.stringify({
1708
+ success: false,
1709
+ error: `Invalid phase name: "${input.phase.slice(0, 50)}". Must be lowercase alphanumeric with hyphens, max 31 chars.`
1710
+ }),
1711
+ isError: true
1712
+ };
1713
+ }
1714
+ for (let i = 0; i < input.rawAnswers.length; i++) {
1715
+ const a = input.rawAnswers[i];
1716
+ if (!a.question_header || a.question_header.trim().length === 0) {
1717
+ return {
1718
+ text: JSON.stringify({
1719
+ success: false,
1720
+ error: `rawAnswers[${i}].question_header is empty \u2014 every answer must have a non-empty question_header.`
1721
+ }),
1722
+ isError: true
1723
+ };
1724
+ }
1725
+ if (!a.selected_options || a.selected_options.length === 0) {
1726
+ return {
1727
+ text: JSON.stringify({
1728
+ success: false,
1729
+ error: `rawAnswers[${i}].selected_options is empty for question_header "${a.question_header}" \u2014 every answer must have at least one selected option.`
1730
+ }),
1731
+ isError: true
1732
+ };
1733
+ }
1734
+ }
1735
+ if (input.questions && input.questions.length > 0 && input.rawAnswers.length === 0) {
1736
+ return {
1737
+ text: JSON.stringify({
1738
+ success: false,
1739
+ error: `${input.questions.length} questions provided but rawAnswers is empty \u2014 this is a malformed payload. If the phase truly has no questions, omit the questions parameter.`
1740
+ }),
1741
+ isError: true
1742
+ };
1743
+ }
1477
1744
  const cwd = input._cwd ?? process.cwd();
1478
1745
  const dir = (0, import_path3.join)(cwd, ".stackwright", "answers");
1479
1746
  const filePath = (0, import_path3.join)(dir, `${input.phase}.json`);
1480
1747
  try {
1481
1748
  (0, import_fs3.mkdirSync)(dir, { recursive: true });
1749
+ const warnings = [];
1482
1750
  let answers;
1483
1751
  if (input.questions && input.questions.length > 0) {
1484
- answers = answersToManifestFormat(input.rawAnswers, input.questions);
1752
+ try {
1753
+ answers = answersToManifestFormat(input.rawAnswers, input.questions);
1754
+ } catch (mapErr) {
1755
+ answers = {};
1756
+ warnings.push(
1757
+ `Reverse-mapping threw (${mapErr instanceof Error ? mapErr.message : String(mapErr)}) \u2014 falling back to direct key mapping.`
1758
+ );
1759
+ }
1760
+ if (Object.keys(answers).length === 0 && input.rawAnswers.length > 0) {
1761
+ answers = Object.fromEntries(
1762
+ input.rawAnswers.map((a) => [
1763
+ a.question_header,
1764
+ a.selected_options.length > 1 ? a.selected_options : a.selected_options[0] ?? ""
1765
+ ])
1766
+ );
1767
+ warnings.push(
1768
+ `Reverse-mapping produced empty answers despite ${input.rawAnswers.length} rawAnswers \u2014 used direct key mapping as fallback. Ensure question_header values match the manifest header format (e.g. "DESI-1", not descriptive keys).`
1769
+ );
1770
+ }
1771
+ const requiredCount = input.questions.filter((q) => q.required !== false).length;
1772
+ if (input.rawAnswers.length < requiredCount) {
1773
+ warnings.push(
1774
+ `Only ${input.rawAnswers.length} answers provided for ${requiredCount} required questions (${input.questions.length} total) \u2014 answers may be incomplete.`
1775
+ );
1776
+ }
1485
1777
  } else {
1486
1778
  answers = Object.fromEntries(
1487
1779
  input.rawAnswers.map((a) => [a.question_header, a.selected_options[0] ?? ""])
@@ -1508,7 +1800,8 @@ function handleSavePhaseAnswers(input) {
1508
1800
  text: JSON.stringify({
1509
1801
  success: true,
1510
1802
  path: filePath,
1511
- answersCount: Object.keys(answers).length
1803
+ answersCount: Object.keys(answers).length,
1804
+ ...warnings.length > 0 ? { warnings } : {}
1512
1805
  }),
1513
1806
  isError: false
1514
1807
  };
@@ -1555,13 +1848,63 @@ function handleGetOtterName(input) {
1555
1848
  isError: false
1556
1849
  };
1557
1850
  }
1851
+ function handleSaveBuildContext(input) {
1852
+ const cwd = input._cwd ?? process.cwd();
1853
+ const dir = (0, import_path3.join)(cwd, ".stackwright");
1854
+ const filePath = (0, import_path3.join)(dir, "build-context.json");
1855
+ try {
1856
+ (0, import_fs3.mkdirSync)(dir, { recursive: true });
1857
+ if ((0, import_fs3.existsSync)(filePath)) {
1858
+ const stat = (0, import_fs3.lstatSync)(filePath);
1859
+ if (stat.isSymbolicLink()) {
1860
+ return {
1861
+ text: JSON.stringify({
1862
+ success: false,
1863
+ error: `Refusing to write to symlink: ${filePath}`
1864
+ }),
1865
+ isError: true
1866
+ };
1867
+ }
1868
+ }
1869
+ const payload = {
1870
+ version: "1.0",
1871
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
1872
+ buildContext: input.buildContext
1873
+ };
1874
+ (0, import_fs3.writeFileSync)(filePath, JSON.stringify(payload, null, 2) + "\n");
1875
+ return {
1876
+ text: JSON.stringify({ success: true, path: filePath }),
1877
+ isError: false
1878
+ };
1879
+ } catch (err) {
1880
+ const message = err instanceof Error ? err.message : String(err);
1881
+ return {
1882
+ text: JSON.stringify({ success: false, error: message }),
1883
+ isError: true
1884
+ };
1885
+ }
1886
+ }
1558
1887
  function registerOrchestrationTools(server2) {
1888
+ server2.tool(
1889
+ "stackwright_pro_save_build_context",
1890
+ `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.`,
1891
+ {
1892
+ buildContext: import_zod9.z.string().describe("Free-text description of what the user wants to build")
1893
+ },
1894
+ async ({ buildContext }) => {
1895
+ const { text, isError } = handleSaveBuildContext({ buildContext });
1896
+ return {
1897
+ content: [{ type: "text", text }],
1898
+ isError
1899
+ };
1900
+ }
1901
+ );
1559
1902
  server2.tool(
1560
1903
  "stackwright_pro_parse_otter_response",
1561
1904
  "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
1905
  {
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")
1906
+ otterName: import_zod9.z.string().describe('The agent name, e.g. "stackwright-pro-api-otter"'),
1907
+ responseText: import_zod9.z.string().describe("Raw text response from the otter's QUESTION_COLLECTION_MODE invocation")
1565
1908
  },
1566
1909
  async ({ otterName, responseText }) => {
1567
1910
  const { result, isError } = handleParseOtterResponse({ otterName, responseText });
@@ -1575,16 +1918,18 @@ function registerOrchestrationTools(server2) {
1575
1918
  "stackwright_pro_save_manifest",
1576
1919
  "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
1920
  {
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
- })
1921
+ phases: jsonCoerce(
1922
+ import_zod9.z.array(
1923
+ import_zod9.z.object({
1924
+ phase: import_zod9.z.string(),
1925
+ otter: import_zod9.z.string(),
1926
+ questions: import_zod9.z.array(import_zod9.z.any()),
1927
+ requiredPackages: import_zod9.z.object({
1928
+ dependencies: import_zod9.z.record(import_zod9.z.string(), import_zod9.z.string()).optional(),
1929
+ devPackages: import_zod9.z.record(import_zod9.z.string(), import_zod9.z.string()).optional()
1930
+ }).optional()
1931
+ })
1932
+ )
1588
1933
  ).describe("Array of parsed phase objects from stackwright_pro_parse_otter_response")
1589
1934
  },
1590
1935
  async ({ phases }) => {
@@ -1599,15 +1944,37 @@ function registerOrchestrationTools(server2) {
1599
1944
  "stackwright_pro_save_phase_answers",
1600
1945
  "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
1946
  {
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")
1947
+ phase: import_zod9.z.string().describe('Phase name, e.g. "designer"'),
1948
+ rawAnswers: jsonCoerce(
1949
+ import_zod9.z.array(
1950
+ import_zod9.z.object({
1951
+ question_header: import_zod9.z.string().min(1, "question_header must not be empty"),
1952
+ selected_options: import_zod9.z.array(import_zod9.z.string()).min(1, "selected_options must have at least one entry"),
1953
+ other_text: import_zod9.z.string().nullable().optional()
1954
+ })
1955
+ )
1956
+ ).describe(
1957
+ "Answers as returned by ask_user_question \u2014 pass the native array, not a JSON string"
1958
+ ),
1959
+ questions: jsonCoerce(
1960
+ import_zod9.z.array(
1961
+ import_zod9.z.object({
1962
+ id: import_zod9.z.string(),
1963
+ question: import_zod9.z.string(),
1964
+ type: import_zod9.z.string(),
1965
+ options: import_zod9.z.array(import_zod9.z.object({ label: import_zod9.z.string(), value: import_zod9.z.string() })).optional(),
1966
+ required: import_zod9.z.boolean().optional(),
1967
+ default: import_zod9.z.union([import_zod9.z.string(), import_zod9.z.boolean(), import_zod9.z.array(import_zod9.z.string())]).optional(),
1968
+ help: import_zod9.z.string().optional(),
1969
+ dependsOn: import_zod9.z.object({
1970
+ questionId: import_zod9.z.string(),
1971
+ value: import_zod9.z.union([import_zod9.z.string(), import_zod9.z.array(import_zod9.z.string())])
1972
+ }).optional()
1973
+ }).passthrough()
1974
+ ).optional()
1975
+ ).describe(
1976
+ "Original manifest questions for label\u2192value reverse-mapping \u2014 pass the native array, not a JSON string"
1977
+ )
1611
1978
  },
1612
1979
  async ({ phase, rawAnswers, questions }) => {
1613
1980
  const { text, isError } = handleSavePhaseAnswers({
@@ -1625,7 +1992,7 @@ function registerOrchestrationTools(server2) {
1625
1992
  "stackwright_pro_read_phase_answers",
1626
1993
  "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
1994
  {
1628
- phase: import_zod8.z.string().describe('Phase name, e.g. "designer"')
1995
+ phase: import_zod9.z.string().describe('Phase name, e.g. "designer"')
1629
1996
  },
1630
1997
  async ({ phase }) => {
1631
1998
  const { text, isError } = handleReadPhaseAnswers({ phase });
@@ -1639,7 +2006,7 @@ function registerOrchestrationTools(server2) {
1639
2006
  "stackwright_pro_get_otter_name",
1640
2007
  "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
2008
  {
1642
- phase: import_zod8.z.string().describe('Phase name, e.g. "designer", "api", "pages"')
2009
+ phase: import_zod9.z.string().describe('Phase name, e.g. "designer", "api", "pages"')
1643
2010
  },
1644
2011
  async ({ phase }) => {
1645
2012
  const { text, isError } = handleGetOtterName({ phase });
@@ -1652,50 +2019,746 @@ function registerOrchestrationTools(server2) {
1652
2019
  }
1653
2020
 
1654
2021
  // src/tools/pipeline.ts
1655
- var import_zod9 = require("zod");
2022
+ var import_zod13 = require("zod");
2023
+ var import_fs5 = require("fs");
2024
+ var import_path5 = require("path");
2025
+ var import_crypto3 = require("crypto");
2026
+
2027
+ // src/artifact-signing.ts
2028
+ var import_crypto2 = require("crypto");
1656
2029
  var import_fs4 = require("fs");
1657
2030
  var import_path4 = require("path");
1658
- var PHASE_ORDER = [
1659
- "designer",
1660
- "theme",
1661
- "api",
1662
- "auth",
1663
- "data",
1664
- "pages",
1665
- "dashboard",
1666
- "workflow"
1667
- ];
1668
- var PHASE_DEPENDENCIES = {
1669
- designer: [],
1670
- theme: ["designer"],
1671
- api: [],
1672
- auth: [],
1673
- data: ["api"],
1674
- pages: ["designer", "theme", "api", "data", "auth"],
1675
- dashboard: ["designer", "theme", "api", "data"],
1676
- workflow: ["auth"]
1677
- };
1678
- var PHASE_ARTIFACT = {
1679
- designer: "design-language.json",
1680
- theme: "theme-tokens.json",
1681
- api: "api-config.json",
1682
- auth: "auth-config.json",
1683
- data: "data-config.json",
1684
- pages: "pages-manifest.json",
1685
- dashboard: "dashboard-manifest.json",
1686
- workflow: "workflow-config.json"
1687
- };
1688
- var PHASE_TO_OTTER2 = {
1689
- designer: "stackwright-pro-designer-otter",
1690
- theme: "stackwright-pro-theme-otter",
1691
- api: "stackwright-pro-api-otter",
1692
- auth: "stackwright-pro-auth-otter",
1693
- data: "stackwright-pro-data-otter",
1694
- pages: "stackwright-pro-page-otter",
2031
+ var import_zod10 = require("zod");
2032
+ var ALGORITHM = "ECDSA-P384-SHA384";
2033
+ var KEY_FILE = "pipeline-keys.json";
2034
+ var KEY_DIR = ".stackwright";
2035
+ var SIGNATURE_MANIFEST = "signatures.json";
2036
+ var ARTIFACTS_DIR = ".stackwright/artifacts";
2037
+ function rejectSymlink(filePath, context) {
2038
+ if (!(0, import_fs4.existsSync)(filePath)) return;
2039
+ const stat = (0, import_fs4.lstatSync)(filePath);
2040
+ if (stat.isSymbolicLink()) {
2041
+ throw new Error(`Security: refusing to follow symlink at ${context}: ${filePath}`);
2042
+ }
2043
+ }
2044
+ function computeSha384(data) {
2045
+ return (0, import_crypto2.createHash)("sha384").update(data).digest("hex");
2046
+ }
2047
+ function safeDigestEqual(a, b) {
2048
+ if (a.length !== b.length) return false;
2049
+ return (0, import_crypto2.timingSafeEqual)(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
2050
+ }
2051
+ function emptyManifest() {
2052
+ return {
2053
+ version: "1.0",
2054
+ algorithm: ALGORITHM,
2055
+ signatures: {}
2056
+ };
2057
+ }
2058
+ function initPipelineKeys(cwd) {
2059
+ const keyDir = (0, import_path4.join)(cwd, KEY_DIR);
2060
+ const keyPath = (0, import_path4.join)(keyDir, KEY_FILE);
2061
+ rejectSymlink(keyPath, "pipeline-keys.json");
2062
+ (0, import_fs4.mkdirSync)(keyDir, { recursive: true });
2063
+ const { publicKey, privateKey } = (0, import_crypto2.generateKeyPairSync)("ec", {
2064
+ namedCurve: "P-384"
2065
+ });
2066
+ const publicKeyPem = publicKey.export({ type: "spki", format: "pem" });
2067
+ const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" });
2068
+ const fingerprint = (0, import_crypto2.createHash)("sha256").update(publicKeyPem).digest("hex");
2069
+ const keyFile = {
2070
+ version: "1.0",
2071
+ algorithm: ALGORITHM,
2072
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2073
+ publicKeyPem,
2074
+ privateKeyPem
2075
+ };
2076
+ (0, import_fs4.writeFileSync)(keyPath, JSON.stringify(keyFile, null, 2), { encoding: "utf-8" });
2077
+ return { publicKeyPem, fingerprint };
2078
+ }
2079
+ function loadPipelineKeys(cwd) {
2080
+ const keyPath = (0, import_path4.join)(cwd, KEY_DIR, KEY_FILE);
2081
+ rejectSymlink(keyPath, "pipeline-keys.json");
2082
+ if (!(0, import_fs4.existsSync)(keyPath)) {
2083
+ throw new Error("Pipeline keys not found \u2014 call initPipelineKeys() first");
2084
+ }
2085
+ let raw;
2086
+ try {
2087
+ raw = (0, import_fs4.readFileSync)(keyPath, "utf-8");
2088
+ } catch (err) {
2089
+ const msg = err instanceof Error ? err.message : String(err);
2090
+ throw new Error(`Cannot read pipeline keys: ${msg}`, { cause: err });
2091
+ }
2092
+ let parsed;
2093
+ try {
2094
+ parsed = JSON.parse(raw);
2095
+ } catch {
2096
+ throw new Error("Pipeline keys file is not valid JSON");
2097
+ }
2098
+ if (typeof parsed.publicKeyPem !== "string" || !parsed.publicKeyPem.includes("-----BEGIN PUBLIC KEY-----")) {
2099
+ throw new Error("Invalid public key PEM in pipeline keys file");
2100
+ }
2101
+ if (typeof parsed.privateKeyPem !== "string" || !parsed.privateKeyPem.includes("-----BEGIN")) {
2102
+ throw new Error("Invalid private key PEM in pipeline keys file");
2103
+ }
2104
+ const publicKey = (0, import_crypto2.createPublicKey)(parsed.publicKeyPem);
2105
+ const privateKey = (0, import_crypto2.createPrivateKey)(parsed.privateKeyPem);
2106
+ return { privateKey, publicKey };
2107
+ }
2108
+ function signArtifact(artifactBytes, privateKey) {
2109
+ const digest = computeSha384(artifactBytes);
2110
+ const sig = (0, import_crypto2.sign)("SHA384", artifactBytes, privateKey);
2111
+ return {
2112
+ digest,
2113
+ signature: sig.toString("base64"),
2114
+ algorithm: ALGORITHM,
2115
+ signedAt: (/* @__PURE__ */ new Date()).toISOString()
2116
+ };
2117
+ }
2118
+ function verifyArtifact(artifactBytes, signature, publicKey) {
2119
+ const sigValid = (0, import_crypto2.verify)(
2120
+ "SHA384",
2121
+ artifactBytes,
2122
+ publicKey,
2123
+ Buffer.from(signature.signature, "base64")
2124
+ );
2125
+ if (!sigValid) return false;
2126
+ const actualDigest = computeSha384(artifactBytes);
2127
+ return safeDigestEqual(actualDigest, signature.digest);
2128
+ }
2129
+ function loadSignatureManifest(cwd) {
2130
+ const manifestPath = (0, import_path4.join)(cwd, ARTIFACTS_DIR, SIGNATURE_MANIFEST);
2131
+ rejectSymlink(manifestPath, "signatures.json");
2132
+ if (!(0, import_fs4.existsSync)(manifestPath)) return emptyManifest();
2133
+ let raw;
2134
+ try {
2135
+ raw = (0, import_fs4.readFileSync)(manifestPath, "utf-8");
2136
+ } catch (err) {
2137
+ const msg = err instanceof Error ? err.message : String(err);
2138
+ throw new Error(`Cannot read signature manifest: ${msg}`, { cause: err });
2139
+ }
2140
+ try {
2141
+ const parsed = JSON.parse(raw);
2142
+ if (parsed.version !== "1.0" || typeof parsed.signatures !== "object") {
2143
+ throw new Error("Malformed signature manifest: invalid version or missing signatures object");
2144
+ }
2145
+ return parsed;
2146
+ } catch (err) {
2147
+ if (err instanceof Error && err.message.startsWith("Malformed")) throw err;
2148
+ throw new Error("Signature manifest is not valid JSON", { cause: err });
2149
+ }
2150
+ }
2151
+ function saveArtifactSignature(cwd, artifactFilename, sig, signerOtter) {
2152
+ const artifactsDir = (0, import_path4.join)(cwd, ARTIFACTS_DIR);
2153
+ const manifestPath = (0, import_path4.join)(artifactsDir, SIGNATURE_MANIFEST);
2154
+ rejectSymlink(manifestPath, "signatures.json (save)");
2155
+ (0, import_fs4.mkdirSync)(artifactsDir, { recursive: true });
2156
+ const manifest = loadSignatureManifest(cwd);
2157
+ manifest.signatures[artifactFilename] = {
2158
+ ...sig,
2159
+ signedBy: signerOtter
2160
+ };
2161
+ (0, import_fs4.writeFileSync)(manifestPath, JSON.stringify(manifest, null, 2), { encoding: "utf-8" });
2162
+ }
2163
+ function getArtifactSignature(cwd, artifactFilename) {
2164
+ const manifest = loadSignatureManifest(cwd);
2165
+ const entry = manifest.signatures[artifactFilename];
2166
+ if (!entry) return null;
2167
+ return {
2168
+ digest: entry.digest,
2169
+ signature: entry.signature,
2170
+ algorithm: entry.algorithm,
2171
+ signedAt: entry.signedAt
2172
+ };
2173
+ }
2174
+ function emitSignatureAuditEvent(params) {
2175
+ const record = JSON.stringify({
2176
+ level: "AUDIT",
2177
+ event: "ARTIFACT_SIGNATURE_FAIL",
2178
+ timestamp: params.timestamp,
2179
+ source: params.source,
2180
+ artifactFilename: params.artifactFilename,
2181
+ expectedDigest: params.expectedDigest,
2182
+ actualDigest: params.actualDigest,
2183
+ phase: params.phase
2184
+ });
2185
+ process.stderr.write(`ARTIFACT_SIGNATURE_FAIL ${record}
2186
+ `);
2187
+ }
2188
+ function registerArtifactSigningTools(server2) {
2189
+ server2.tool(
2190
+ "stackwright_pro_verify_artifact_signatures",
2191
+ "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.",
2192
+ {
2193
+ cwd: import_zod10.z.string().optional().describe("Project root directory. Defaults to process.cwd().")
2194
+ },
2195
+ async ({ cwd: cwdParam }) => {
2196
+ const cwd = cwdParam ?? process.cwd();
2197
+ let publicKey;
2198
+ try {
2199
+ const keys = loadPipelineKeys(cwd);
2200
+ publicKey = keys.publicKey;
2201
+ } catch (err) {
2202
+ const msg = err instanceof Error ? err.message : String(err);
2203
+ return {
2204
+ content: [
2205
+ {
2206
+ type: "text",
2207
+ text: JSON.stringify({
2208
+ error: true,
2209
+ message: `Cannot load pipeline keys: ${msg}`
2210
+ })
2211
+ }
2212
+ ],
2213
+ isError: true
2214
+ };
2215
+ }
2216
+ let manifest;
2217
+ try {
2218
+ manifest = loadSignatureManifest(cwd);
2219
+ } catch (err) {
2220
+ const msg = err instanceof Error ? err.message : String(err);
2221
+ return {
2222
+ content: [
2223
+ {
2224
+ type: "text",
2225
+ text: JSON.stringify({
2226
+ error: true,
2227
+ message: `Cannot load signature manifest: ${msg}`
2228
+ })
2229
+ }
2230
+ ],
2231
+ isError: true
2232
+ };
2233
+ }
2234
+ const artifactsPath = (0, import_path4.join)(cwd, ARTIFACTS_DIR);
2235
+ let artifactFiles = [];
2236
+ try {
2237
+ if ((0, import_fs4.existsSync)(artifactsPath)) {
2238
+ artifactFiles = (0, import_fs4.readdirSync)(artifactsPath).filter(
2239
+ (f) => f.endsWith(".json") && f !== SIGNATURE_MANIFEST
2240
+ );
2241
+ }
2242
+ } catch {
2243
+ }
2244
+ const results = [];
2245
+ let hasFailure = false;
2246
+ for (const filename of artifactFiles) {
2247
+ const filePath = (0, import_path4.join)(artifactsPath, filename);
2248
+ try {
2249
+ rejectSymlink(filePath, `artifact ${filename}`);
2250
+ } catch {
2251
+ results.push({
2252
+ filename,
2253
+ verified: false,
2254
+ error: "Refusing to verify symlink"
2255
+ });
2256
+ hasFailure = true;
2257
+ continue;
2258
+ }
2259
+ let artifactBytes;
2260
+ try {
2261
+ artifactBytes = (0, import_fs4.readFileSync)(filePath);
2262
+ } catch (err) {
2263
+ const msg = err instanceof Error ? err.message : String(err);
2264
+ results.push({
2265
+ filename,
2266
+ verified: false,
2267
+ error: `Cannot read artifact: ${msg}`
2268
+ });
2269
+ hasFailure = true;
2270
+ continue;
2271
+ }
2272
+ const entry = manifest.signatures[filename];
2273
+ if (!entry) {
2274
+ results.push({
2275
+ filename,
2276
+ verified: false,
2277
+ error: "No signature found in manifest"
2278
+ });
2279
+ hasFailure = true;
2280
+ continue;
2281
+ }
2282
+ const sig = {
2283
+ digest: entry.digest,
2284
+ signature: entry.signature,
2285
+ algorithm: entry.algorithm,
2286
+ signedAt: entry.signedAt
2287
+ };
2288
+ const verified = verifyArtifact(artifactBytes, sig, publicKey);
2289
+ if (!verified) {
2290
+ const actualDigest = computeSha384(artifactBytes);
2291
+ emitSignatureAuditEvent({
2292
+ artifactFilename: filename,
2293
+ expectedDigest: sig.digest,
2294
+ actualDigest,
2295
+ phase: entry.signedBy ?? "unknown",
2296
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2297
+ source: "stackwright_pro_verify_artifact_signatures"
2298
+ });
2299
+ results.push({
2300
+ filename,
2301
+ verified: false,
2302
+ error: `Signature verification failed \u2014 artifact may have been tampered with`,
2303
+ signedBy: entry.signedBy,
2304
+ signedAt: entry.signedAt
2305
+ });
2306
+ hasFailure = true;
2307
+ } else {
2308
+ results.push({
2309
+ filename,
2310
+ verified: true,
2311
+ signedBy: entry.signedBy,
2312
+ signedAt: entry.signedAt
2313
+ });
2314
+ }
2315
+ }
2316
+ for (const manifestFilename of Object.keys(manifest.signatures)) {
2317
+ if (!artifactFiles.includes(manifestFilename)) {
2318
+ results.push({
2319
+ filename: manifestFilename,
2320
+ verified: false,
2321
+ error: "Artifact referenced in manifest but missing from disk"
2322
+ });
2323
+ hasFailure = true;
2324
+ }
2325
+ }
2326
+ const verifiedCount = results.filter((r) => r.verified).length;
2327
+ const failedCount = results.filter((r) => !r.verified).length;
2328
+ return {
2329
+ content: [
2330
+ {
2331
+ type: "text",
2332
+ text: JSON.stringify({
2333
+ totalArtifacts: artifactFiles.length,
2334
+ verifiedCount,
2335
+ failedCount,
2336
+ results,
2337
+ ...hasFailure ? {
2338
+ error: "SIGNATURE VERIFICATION FAILED: One or more artifact signatures are invalid. Do not proceed \u2014 artifacts may have been tampered with."
2339
+ } : {}
2340
+ })
2341
+ }
2342
+ ],
2343
+ isError: hasFailure
2344
+ };
2345
+ }
2346
+ );
2347
+ }
2348
+
2349
+ // src/tools/pipeline.ts
2350
+ var import_types3 = require("@stackwright-pro/types");
2351
+
2352
+ // src/tools/get-schema.ts
2353
+ var import_zod12 = require("zod");
2354
+ var import_types2 = require("@stackwright-pro/types");
2355
+
2356
+ // src/tools/validate-yaml-fragment.ts
2357
+ var import_zod11 = require("zod");
2358
+ var import_js_yaml = require("js-yaml");
2359
+ var import_types = require("@stackwright-pro/types");
2360
+ var SUPPORTED_SCHEMA_NAMES = [
2361
+ "workflow_step",
2362
+ "workflow_definition",
2363
+ "workflow_field",
2364
+ "workflow_action",
2365
+ "navigation_item",
2366
+ "auth_config"
2367
+ ];
2368
+ var NavigationLinkSchema = import_zod11.z.lazy(
2369
+ () => import_zod11.z.object({
2370
+ label: import_zod11.z.string().min(1),
2371
+ href: import_zod11.z.string().min(1),
2372
+ children: import_zod11.z.array(NavigationLinkSchema).optional()
2373
+ })
2374
+ );
2375
+ var NavigationSectionSchema = import_zod11.z.object({
2376
+ section: import_zod11.z.string().min(1),
2377
+ items: import_zod11.z.array(NavigationLinkSchema)
2378
+ });
2379
+ var NavigationItemSchema = import_zod11.z.union([
2380
+ NavigationLinkSchema,
2381
+ NavigationSectionSchema
2382
+ ]);
2383
+ var FIELD_SYNONYMS = {
2384
+ workflow_step: {
2385
+ title: "label",
2386
+ name: "label (at step level, use label: not name:)",
2387
+ description: "message (use message: for step-level descriptive text)",
2388
+ style: 'theme.variant \u2014 use theme: { variant: "primary" } not style: "primary"',
2389
+ transitions: 'on_submit.transition \u2014 use on_submit: { transition: "next_step" } not transitions: [{then:...}]'
2390
+ },
2391
+ workflow_definition: {
2392
+ title: "label",
2393
+ name: "label (workflow-level label, not name:)",
2394
+ description: "description is valid here \u2014 but message: is not (that is a step field)",
2395
+ type: "id (workflows are identified by id:, not type:)"
2396
+ },
2397
+ workflow_field: {
2398
+ id: "name (field-level identifier is name:, NOT id:)",
2399
+ title: "label (field display text is label:, NOT title:)",
2400
+ description: "placeholder or label (no description field on WorkflowField)"
2401
+ },
2402
+ workflow_action: {
2403
+ style: 'theme.variant \u2014 use theme: { variant: "primary" } not style: "primary"',
2404
+ then: "transition (action-level next-step is transition:, NOT then:)",
2405
+ on_click: 'action: "service:..." (extract the service reference from on_click.action)',
2406
+ title: "label (action display text is label:, NOT title:)",
2407
+ name: "label (action display text is label:, NOT name:)"
2408
+ },
2409
+ navigation_item: {
2410
+ children: "items (NavigationSection uses items: not children: \u2014 also use section: instead of label: for section headers)",
2411
+ label: 'section (if this is a nav group/section, use section: "Title" and items: [...], not label:)',
2412
+ title: "section (NavigationSection header field is section:, NOT title:)"
2413
+ },
2414
+ auth_config: {
2415
+ method: 'type \u2014 auth config discriminates on type: "oidc" | "pki", NOT method:',
2416
+ provider_type: 'type \u2014 use type: "oidc" or type: "pki"',
2417
+ strategy: "type \u2014 top-level discriminator is type:, not strategy:"
2418
+ }
2419
+ };
2420
+ function getSchema(name) {
2421
+ switch (name) {
2422
+ case "workflow_step":
2423
+ return import_types.WorkflowStepSchema;
2424
+ case "workflow_definition":
2425
+ return import_types.WorkflowDefinitionSchema;
2426
+ case "workflow_field":
2427
+ return import_types.WorkflowFieldSchema;
2428
+ case "workflow_action":
2429
+ return import_types.WorkflowActionSchema;
2430
+ case "navigation_item":
2431
+ return NavigationItemSchema;
2432
+ case "auth_config":
2433
+ return import_types.authConfigSchema;
2434
+ }
2435
+ }
2436
+ function enrichErrors(issues, synonyms) {
2437
+ return issues.map((issue) => {
2438
+ const pathStr = issue.path.join(".");
2439
+ const lastSegment = issue.path[issue.path.length - 1];
2440
+ const fieldName = typeof lastSegment === "string" ? lastSegment : void 0;
2441
+ const didYouMean = fieldName ? synonyms[fieldName] : void 0;
2442
+ return {
2443
+ path: pathStr || "(root)",
2444
+ message: issue.message,
2445
+ ...didYouMean ? { didYouMean } : {}
2446
+ };
2447
+ });
2448
+ }
2449
+ function handleValidateYamlFragment(input) {
2450
+ const { schemaName, yaml } = input;
2451
+ if (!SUPPORTED_SCHEMA_NAMES.includes(schemaName)) {
2452
+ return {
2453
+ valid: false,
2454
+ parseError: `Unknown schemaName: "${schemaName}". Supported: ${SUPPORTED_SCHEMA_NAMES.join(", ")}`
2455
+ };
2456
+ }
2457
+ const name = schemaName;
2458
+ let parsed;
2459
+ try {
2460
+ parsed = (0, import_js_yaml.load)(yaml);
2461
+ } catch (err) {
2462
+ return {
2463
+ valid: false,
2464
+ parseError: `YAML parse error: ${err instanceof Error ? err.message : String(err)}`
2465
+ };
2466
+ }
2467
+ const schema = getSchema(name);
2468
+ const result = schema.safeParse(parsed);
2469
+ if (result.success) {
2470
+ return { valid: true };
2471
+ }
2472
+ const synonyms = FIELD_SYNONYMS[name];
2473
+ const errors = enrichErrors(result.error.issues, synonyms);
2474
+ return { valid: false, errors };
2475
+ }
2476
+ function registerValidateYamlFragmentTool(server2) {
2477
+ server2.tool(
2478
+ "stackwright_pro_validate_yaml_fragment",
2479
+ 'Validates a YAML snippet against a canonical Zod schema before writing to disk. Returns actionable errors with "did you mean?" suggestions for common field-name drift (title vs label, id vs name, style vs theme.variant, etc.). Call this before stackwright_pro_safe_write to catch schema violations in-session.',
2480
+ {
2481
+ schemaName: import_zod11.z.enum(SUPPORTED_SCHEMA_NAMES).describe(
2482
+ "Schema to validate against. One of: workflow_step, workflow_definition, workflow_field, workflow_action, navigation_item, auth_config"
2483
+ ),
2484
+ yaml: import_zod11.z.string().describe("YAML string to validate (can also be JSON \u2014 js-yaml parses both)")
2485
+ },
2486
+ async ({ schemaName, yaml }) => {
2487
+ const result = handleValidateYamlFragment({ schemaName, yaml });
2488
+ return {
2489
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2490
+ };
2491
+ }
2492
+ );
2493
+ }
2494
+
2495
+ // src/tools/get-schema.ts
2496
+ var NavigationLinkSchema2 = import_zod12.z.lazy(
2497
+ () => import_zod12.z.object({
2498
+ label: import_zod12.z.string().min(1),
2499
+ href: import_zod12.z.string().min(1),
2500
+ children: import_zod12.z.array(NavigationLinkSchema2).optional()
2501
+ })
2502
+ );
2503
+ var NavigationSectionSchema2 = import_zod12.z.object({
2504
+ section: import_zod12.z.string().min(1),
2505
+ items: import_zod12.z.array(NavigationLinkSchema2)
2506
+ });
2507
+ var NavigationItemSchema2 = import_zod12.z.union([
2508
+ NavigationLinkSchema2,
2509
+ NavigationSectionSchema2
2510
+ ]);
2511
+ function getZodSchema(name) {
2512
+ switch (name) {
2513
+ case "workflow_step":
2514
+ return import_types2.WorkflowStepSchema;
2515
+ case "workflow_definition":
2516
+ return import_types2.WorkflowDefinitionSchema;
2517
+ case "workflow_field":
2518
+ return import_types2.WorkflowFieldSchema;
2519
+ case "workflow_action":
2520
+ return import_types2.WorkflowActionSchema;
2521
+ case "navigation_item":
2522
+ return NavigationItemSchema2;
2523
+ case "auth_config":
2524
+ return import_types2.authConfigSchema;
2525
+ }
2526
+ }
2527
+ function formatType(node, depth = 0) {
2528
+ if (node.const !== void 0) return JSON.stringify(node.const);
2529
+ if (node.enum) return node.enum.map((v) => JSON.stringify(v)).join(" | ");
2530
+ if (node.oneOf || node.anyOf) {
2531
+ const branches = node.oneOf ?? node.anyOf ?? [];
2532
+ return branches.map((b) => {
2533
+ const disc = b.properties ? Object.entries(b.properties).filter(([, v]) => v.const !== void 0).map(([k, v]) => `${k}: ${JSON.stringify(v.const)}`).join(", ") : "";
2534
+ return disc ? `{ ${disc}, ... }` : "{ ... }";
2535
+ }).join(" | ");
2536
+ }
2537
+ if (node.type === "array" && node.items) {
2538
+ return `${formatType(node.items, depth)}[]`;
2539
+ }
2540
+ if (node.type === "object" && node.properties && depth < 2) {
2541
+ const inner = Object.entries(node.properties).map(([k, v]) => `${k}: ${formatType(v, depth + 1)}`).join(", ");
2542
+ return `{ ${inner} }`;
2543
+ }
2544
+ const base = Array.isArray(node.type) ? node.type.join(" | ") : node.type ?? "unknown";
2545
+ const constraints = [];
2546
+ if (node.maxLength !== void 0) constraints.push(`max ${node.maxLength} chars`);
2547
+ if (node.minLength !== void 0) constraints.push(`min ${node.minLength} chars`);
2548
+ if (node.pattern) constraints.push(`pattern: ${node.pattern}`);
2549
+ if (node.minimum !== void 0) constraints.push(`min ${node.minimum}`);
2550
+ if (node.maximum !== void 0) constraints.push(`max ${node.maximum}`);
2551
+ return constraints.length > 0 ? `${base} (${constraints.join(", ")})` : base;
2552
+ }
2553
+ function formatObjectSchema(node, schemaName, synonyms) {
2554
+ const lines = [];
2555
+ const displayName = schemaName.split("_").map((w) => w[0].toUpperCase() + w.slice(1)).join("");
2556
+ lines.push(`${displayName}:`);
2557
+ if (node.oneOf || node.anyOf) {
2558
+ const branches = node.oneOf ?? node.anyOf ?? [];
2559
+ lines.push(" Discriminated union \u2014 choose one variant:");
2560
+ for (const branch of branches) {
2561
+ const req = new Set(branch.required ?? []);
2562
+ const disc = Object.entries(branch.properties ?? {}).filter(([, v]) => v.const !== void 0).map(([k, v]) => `${k}: ${JSON.stringify(v.const)}`).join(", ");
2563
+ lines.push(` VARIANT (${disc}):`);
2564
+ for (const [field, fieldNode] of Object.entries(branch.properties ?? {})) {
2565
+ if (fieldNode.const !== void 0) continue;
2566
+ const isRequired = req.has(field);
2567
+ const hint = synonyms[field] ? ` -- WARNING: use ${field}: not ${synonyms[field]}` : "";
2568
+ lines.push(
2569
+ ` ${isRequired ? "REQUIRED" : "optional"}: ${field}: ${formatType(fieldNode)}${hint}`
2570
+ );
2571
+ }
2572
+ }
2573
+ return lines.join("\n");
2574
+ }
2575
+ const required = new Set(node.required ?? []);
2576
+ const properties = node.properties ?? {};
2577
+ const requiredFields = Object.entries(properties).filter(([k]) => required.has(k));
2578
+ const optionalFields = Object.entries(properties).filter(([k]) => !required.has(k));
2579
+ if (requiredFields.length > 0) {
2580
+ lines.push(" REQUIRED:");
2581
+ for (const [field, fieldNode] of requiredFields) {
2582
+ const typeStr = formatType(fieldNode);
2583
+ const warn = synonyms[field] ? ` -- CAUTION: this schema uses ${field}` : "";
2584
+ lines.push(` ${field}: ${typeStr}${warn}`);
2585
+ }
2586
+ }
2587
+ if (optionalFields.length > 0) {
2588
+ lines.push(" OPTIONAL:");
2589
+ for (const [field, fieldNode] of optionalFields) {
2590
+ const typeStr = formatType(fieldNode);
2591
+ lines.push(` ${field}: ${typeStr}`);
2592
+ }
2593
+ }
2594
+ return lines.join("\n");
2595
+ }
2596
+ function handleGetSchema(input) {
2597
+ const { schemaName } = input;
2598
+ if (!SUPPORTED_SCHEMA_NAMES.includes(schemaName)) {
2599
+ return {
2600
+ error: `Unknown schemaName: "${schemaName}". Supported: ${SUPPORTED_SCHEMA_NAMES.join(", ")}`
2601
+ };
2602
+ }
2603
+ const name = schemaName;
2604
+ const schema = getZodSchema(name);
2605
+ const synonyms = FIELD_SYNONYMS[name];
2606
+ let jsonSchema;
2607
+ try {
2608
+ const raw = import_zod12.z.toJSONSchema(schema, { unrepresentable: "any" });
2609
+ jsonSchema = raw;
2610
+ } catch {
2611
+ jsonSchema = { type: "object", description: "Schema introspection unavailable for this type" };
2612
+ }
2613
+ const summary = formatObjectSchema(jsonSchema, name, synonyms);
2614
+ const synonymWarnings = Object.entries(synonyms).map(
2615
+ ([wrong, correct]) => ` WARNING: use "${correct}" \u2014 NOT "${wrong}"`
2616
+ );
2617
+ const fullText = [
2618
+ summary,
2619
+ "",
2620
+ "FIELD NAME WARNINGS (common drift patterns):",
2621
+ ...synonymWarnings
2622
+ ].join("\n");
2623
+ const tokenEstimate = Math.ceil(fullText.length / 4);
2624
+ return {
2625
+ schemaName: name,
2626
+ summary,
2627
+ synonymWarnings,
2628
+ tokenEstimate
2629
+ };
2630
+ }
2631
+ var PHASE_SCHEMA_NAMES = {
2632
+ workflow: ["workflow_step", "workflow_definition", "workflow_field", "workflow_action"],
2633
+ pages: ["navigation_item"],
2634
+ dashboard: ["navigation_item"],
2635
+ polish: ["navigation_item"],
2636
+ auth: ["auth_config"]
2637
+ };
2638
+ function buildSchemaReferenceBlock(phase) {
2639
+ const schemaNames = PHASE_SCHEMA_NAMES[phase];
2640
+ if (!schemaNames || schemaNames.length === 0) return null;
2641
+ const sections = [
2642
+ "CANONICAL_SCHEMA_REFERENCE (authoritative \u2014 use exact field names below):",
2643
+ ""
2644
+ ];
2645
+ for (const name of schemaNames) {
2646
+ const result = handleGetSchema({ schemaName: name });
2647
+ if ("error" in result) continue;
2648
+ sections.push(result.summary);
2649
+ if (result.synonymWarnings.length > 0) {
2650
+ sections.push(" Common mistakes to avoid:");
2651
+ sections.push(...result.synonymWarnings);
2652
+ }
2653
+ sections.push("");
2654
+ }
2655
+ return sections.join("\n");
2656
+ }
2657
+ function registerGetSchemaTool(server2) {
2658
+ server2.tool(
2659
+ "stackwright_pro_get_schema",
2660
+ 'Returns a compact, LLM-friendly summary of a canonical schema derived programmatically from Zod. Includes required/optional fields, types, constraints, and "did you mean?" warnings for common field-name drift. Use before authoring YAML to confirm exact field names.',
2661
+ {
2662
+ schemaName: import_zod12.z.enum(SUPPORTED_SCHEMA_NAMES).describe(
2663
+ "Schema to summarize. One of: workflow_step, workflow_definition, workflow_field, workflow_action, navigation_item, auth_config"
2664
+ )
2665
+ },
2666
+ async ({ schemaName }) => {
2667
+ const result = handleGetSchema({ schemaName });
2668
+ if ("error" in result) {
2669
+ return {
2670
+ content: [{ type: "text", text: JSON.stringify({ error: result.error }) }],
2671
+ isError: true
2672
+ };
2673
+ }
2674
+ return {
2675
+ content: [
2676
+ {
2677
+ type: "text",
2678
+ text: JSON.stringify(result, null, 2)
2679
+ }
2680
+ ]
2681
+ };
2682
+ }
2683
+ );
2684
+ }
2685
+
2686
+ // src/tools/pipeline.ts
2687
+ var PHASE_ORDER = [
2688
+ "designer",
2689
+ "theme",
2690
+ "scaffold",
2691
+ // generates app/ directory from config
2692
+ "api",
2693
+ "data",
2694
+ "geo",
2695
+ "workflow",
2696
+ "services",
2697
+ "pages",
2698
+ "dashboard",
2699
+ "auth",
2700
+ "polish"
2701
+ ];
2702
+ var PHASE_DEPENDENCIES = {
2703
+ designer: [],
2704
+ theme: ["designer"],
2705
+ scaffold: ["designer", "theme"],
2706
+ // needs stackwright.yml + theme-tokens
2707
+ api: [],
2708
+ data: ["api"],
2709
+ geo: ["data"],
2710
+ // workflow: no hard deps — uses service: references with Prism mock fallback
2711
+ // when API artifacts aren't available; roles come from user answers
2712
+ workflow: [],
2713
+ // services: needs API endpoints to know what to wire, and optionally
2714
+ // workflow states as trigger sources. Produces OpenAPI specs consumed
2715
+ // by pages and dashboard for typed data wiring.
2716
+ services: ["api", "workflow"],
2717
+ // pages/dashboard: depend on services for typed endpoint wiring (OpenAPI
2718
+ // specs) and on geo so the specialist prompt includes geo-manifest.json
2719
+ // — page/dashboard otters see which page slugs are already claimed and
2720
+ // won't attempt to overwrite them (swp-73c). 'api' is still transitive
2721
+ // through 'data'; auth removed — page-otter has graceful fallback.
2722
+ pages: ["designer", "theme", "data", "services", "geo", "scaffold"],
2723
+ dashboard: ["designer", "theme", "data", "services", "geo", "scaffold"],
2724
+ // auth is the penultimate phase — runs after all content-producing phases
2725
+ // so it can read pages, dashboard, workflow, and geo artifacts for route
2726
+ // protection and RBAC wiring. Skipped upstream phases still satisfy deps
2727
+ // (the foreman marks them executed=true), so auth always runs.
2728
+ auth: ["pages", "dashboard", "workflow", "geo"],
2729
+ // polish is the terminal phase — runs after auth so the landing page and
2730
+ // nav reflect the final set of protected routes and all generated pages.
2731
+ polish: ["auth"]
2732
+ };
2733
+ var PHASE_ARTIFACT = {
2734
+ designer: "design-language.json",
2735
+ theme: "theme-tokens.json",
2736
+ scaffold: "scaffold-manifest.json",
2737
+ api: "api-config.json",
2738
+ auth: "auth-config.json",
2739
+ data: "data-config.json",
2740
+ pages: "pages-manifest.json",
2741
+ dashboard: "dashboard-manifest.json",
2742
+ workflow: "workflow-config.json",
2743
+ services: "services-config.json",
2744
+ polish: "polish-manifest.json",
2745
+ geo: "geo-manifest.json"
2746
+ };
2747
+ var PHASE_TO_OTTER2 = {
2748
+ designer: "stackwright-pro-designer-otter",
2749
+ theme: "stackwright-pro-theme-otter",
2750
+ scaffold: "stackwright-pro-scaffold-otter",
2751
+ api: "stackwright-pro-api-otter",
2752
+ auth: "stackwright-pro-auth-otter",
2753
+ data: "stackwright-pro-data-otter",
2754
+ pages: "stackwright-pro-page-otter",
1695
2755
  dashboard: "stackwright-pro-dashboard-otter",
1696
- workflow: "stackwright-pro-workflow-otter"
2756
+ workflow: "stackwright-pro-workflow-otter",
2757
+ services: "stackwright-services-otter",
2758
+ polish: "stackwright-pro-polish-otter",
2759
+ geo: "stackwright-pro-geo-otter"
1697
2760
  };
1698
- function isValidPhase(phase) {
2761
+ function isValidPhase2(phase) {
1699
2762
  return PHASE_ORDER.includes(phase);
1700
2763
  }
1701
2764
  function defaultPhaseStatus() {
@@ -1723,11 +2786,11 @@ function createDefaultState() {
1723
2786
  };
1724
2787
  }
1725
2788
  function statePath(cwd) {
1726
- return (0, import_path4.join)(cwd, ".stackwright", "pipeline-state.json");
2789
+ return (0, import_path5.join)(cwd, ".stackwright", "pipeline-state.json");
1727
2790
  }
1728
2791
  function readState(cwd) {
1729
2792
  const p = statePath(cwd);
1730
- if (!(0, import_fs4.existsSync)(p)) return createDefaultState();
2793
+ if (!(0, import_fs5.existsSync)(p)) return createDefaultState();
1731
2794
  const raw = JSON.parse(safeReadSync(p));
1732
2795
  if (typeof raw !== "object" || raw === null || raw.version !== "1.0") {
1733
2796
  return createDefaultState();
@@ -1735,26 +2798,26 @@ function readState(cwd) {
1735
2798
  return raw;
1736
2799
  }
1737
2800
  function safeWriteSync(filePath, content) {
1738
- if ((0, import_fs4.existsSync)(filePath)) {
1739
- const stat = (0, import_fs4.lstatSync)(filePath);
2801
+ if ((0, import_fs5.existsSync)(filePath)) {
2802
+ const stat = (0, import_fs5.lstatSync)(filePath);
1740
2803
  if (stat.isSymbolicLink()) {
1741
2804
  throw new Error(`Refusing to write to symlink: ${filePath}`);
1742
2805
  }
1743
2806
  }
1744
- (0, import_fs4.writeFileSync)(filePath, content);
2807
+ (0, import_fs5.writeFileSync)(filePath, content);
1745
2808
  }
1746
2809
  function safeReadSync(filePath) {
1747
- if ((0, import_fs4.existsSync)(filePath)) {
1748
- const stat = (0, import_fs4.lstatSync)(filePath);
2810
+ if ((0, import_fs5.existsSync)(filePath)) {
2811
+ const stat = (0, import_fs5.lstatSync)(filePath);
1749
2812
  if (stat.isSymbolicLink()) {
1750
2813
  throw new Error(`Refusing to read symlink: ${filePath}`);
1751
2814
  }
1752
2815
  }
1753
- return (0, import_fs4.readFileSync)(filePath, "utf-8");
2816
+ return (0, import_fs5.readFileSync)(filePath, "utf-8");
1754
2817
  }
1755
2818
  function writeState(cwd, state) {
1756
- const dir = (0, import_path4.join)(cwd, ".stackwright");
1757
- (0, import_fs4.mkdirSync)(dir, { recursive: true });
2819
+ const dir = (0, import_path5.join)(cwd, ".stackwright");
2820
+ (0, import_fs5.mkdirSync)(dir, { recursive: true });
1758
2821
  state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1759
2822
  safeWriteSync(statePath(cwd), JSON.stringify(state, null, 2) + "\n");
1760
2823
  }
@@ -1775,6 +2838,15 @@ function handleGetPipelineState(_cwd) {
1775
2838
  const cwd = _cwd ?? process.cwd();
1776
2839
  try {
1777
2840
  const state = readState(cwd);
2841
+ const keyPath = (0, import_path5.join)(cwd, ".stackwright", "pipeline-keys.json");
2842
+ if (!(0, import_fs5.existsSync)(keyPath)) {
2843
+ try {
2844
+ const { fingerprint } = initPipelineKeys(cwd);
2845
+ state["signingKeyFingerprint"] = fingerprint;
2846
+ writeState(cwd, state);
2847
+ } catch {
2848
+ }
2849
+ }
1778
2850
  return { text: JSON.stringify(state), isError: false };
1779
2851
  } catch (err) {
1780
2852
  return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
@@ -1782,7 +2854,7 @@ function handleGetPipelineState(_cwd) {
1782
2854
  }
1783
2855
  function handleSetPipelineState(input) {
1784
2856
  const cwd = input._cwd ?? process.cwd();
1785
- if (input.phase && !isValidPhase(input.phase)) {
2857
+ if (input.phase && !isValidPhase2(input.phase)) {
1786
2858
  return {
1787
2859
  text: JSON.stringify({
1788
2860
  error: true,
@@ -1801,6 +2873,28 @@ function handleSetPipelineState(input) {
1801
2873
  isError: true
1802
2874
  };
1803
2875
  }
2876
+ if (input.updates && input.updates.length > 0) {
2877
+ for (const update of input.updates) {
2878
+ if (!isValidPhase2(update.phase)) {
2879
+ return {
2880
+ text: JSON.stringify({
2881
+ error: true,
2882
+ message: `Invalid phase in batch update: ${update.phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
2883
+ }),
2884
+ isError: true
2885
+ };
2886
+ }
2887
+ if (!VALID_FIELDS.includes(update.field)) {
2888
+ return {
2889
+ text: JSON.stringify({
2890
+ error: true,
2891
+ message: `Invalid field in batch update: ${update.field}. Valid fields are: ${VALID_FIELDS.join(", ")}`
2892
+ }),
2893
+ isError: true
2894
+ };
2895
+ }
2896
+ }
2897
+ }
1804
2898
  try {
1805
2899
  const state = readState(cwd);
1806
2900
  if (input.status) {
@@ -1820,34 +2914,78 @@ function handleSetPipelineState(input) {
1820
2914
  }
1821
2915
  state.currentPhase = phase;
1822
2916
  }
2917
+ if (input.updates && input.updates.length > 0) {
2918
+ for (const update of input.updates) {
2919
+ if (!state.phases[update.phase]) {
2920
+ state.phases[update.phase] = defaultPhaseStatus();
2921
+ }
2922
+ const batchPhaseState = state.phases[update.phase];
2923
+ batchPhaseState[update.field] = update.value;
2924
+ state.currentPhase = update.phase;
2925
+ }
2926
+ }
1823
2927
  writeState(cwd, state);
1824
2928
  return { text: JSON.stringify(state), isError: false };
1825
2929
  } catch (err) {
1826
2930
  return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
1827
2931
  }
1828
2932
  }
1829
- function handleCheckExecutionReady(_cwd) {
2933
+ function handleCheckExecutionReady(_cwd, phase) {
1830
2934
  const cwd = _cwd ?? process.cwd();
2935
+ if (phase) {
2936
+ if (!isValidPhase2(phase)) {
2937
+ return {
2938
+ text: JSON.stringify({
2939
+ error: true,
2940
+ message: `Invalid phase: ${phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
2941
+ }),
2942
+ isError: true
2943
+ };
2944
+ }
2945
+ const answerFile = (0, import_path5.join)(cwd, ".stackwright", "answers", `${phase}.json`);
2946
+ if (!(0, import_fs5.existsSync)(answerFile)) {
2947
+ return {
2948
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file not found" }),
2949
+ isError: false
2950
+ };
2951
+ }
2952
+ try {
2953
+ const raw = safeReadSync(answerFile);
2954
+ const parsed = JSON.parse(raw);
2955
+ if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
2956
+ return {
2957
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file is malformed" }),
2958
+ isError: false
2959
+ };
2960
+ }
2961
+ return { text: JSON.stringify({ ready: true, phase }), isError: false };
2962
+ } catch {
2963
+ return {
2964
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file could not be parsed" }),
2965
+ isError: false
2966
+ };
2967
+ }
2968
+ }
1831
2969
  try {
1832
- const answersDir = (0, import_path4.join)(cwd, ".stackwright", "answers");
2970
+ const answersDir = (0, import_path5.join)(cwd, ".stackwright", "answers");
1833
2971
  const answeredPhases = [];
1834
2972
  const missingPhases = [];
1835
- for (const phase of PHASE_ORDER) {
1836
- const answerFile = (0, import_path4.join)(answersDir, `${phase}.json`);
1837
- if ((0, import_fs4.existsSync)(answerFile)) {
2973
+ for (const phase2 of PHASE_ORDER) {
2974
+ const answerFile = (0, import_path5.join)(answersDir, `${phase2}.json`);
2975
+ if ((0, import_fs5.existsSync)(answerFile)) {
1838
2976
  try {
1839
2977
  const raw = safeReadSync(answerFile);
1840
2978
  const parsed = JSON.parse(raw);
1841
2979
  if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
1842
- missingPhases.push(phase);
2980
+ missingPhases.push(phase2);
1843
2981
  continue;
1844
2982
  }
1845
- answeredPhases.push(phase);
2983
+ answeredPhases.push(phase2);
1846
2984
  } catch {
1847
- missingPhases.push(phase);
2985
+ missingPhases.push(phase2);
1848
2986
  }
1849
2987
  } else {
1850
- missingPhases.push(phase);
2988
+ missingPhases.push(phase2);
1851
2989
  }
1852
2990
  }
1853
2991
  return {
@@ -1863,18 +3001,74 @@ function handleCheckExecutionReady(_cwd) {
1863
3001
  return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
1864
3002
  }
1865
3003
  }
3004
+ function handleGetReadyPhases(_cwd) {
3005
+ const cwd = _cwd ?? process.cwd();
3006
+ try {
3007
+ const state = readState(cwd);
3008
+ const completed = [];
3009
+ const ready = [];
3010
+ const blocked = [];
3011
+ for (const phase of PHASE_ORDER) {
3012
+ const ps = state.phases[phase];
3013
+ if (ps?.executed) {
3014
+ completed.push(phase);
3015
+ continue;
3016
+ }
3017
+ const deps = PHASE_DEPENDENCIES[phase];
3018
+ const unmetDeps = deps.filter((dep) => !state.phases[dep]?.executed);
3019
+ if (unmetDeps.length === 0) {
3020
+ ready.push(phase);
3021
+ } else {
3022
+ blocked.push(phase);
3023
+ }
3024
+ }
3025
+ return {
3026
+ text: JSON.stringify({
3027
+ readyPhases: ready,
3028
+ completedPhases: completed,
3029
+ blockedPhases: blocked,
3030
+ waveSize: ready.length,
3031
+ allComplete: ready.length === 0 && blocked.length === 0
3032
+ }),
3033
+ isError: false
3034
+ };
3035
+ } catch (err) {
3036
+ const message = err instanceof Error ? err.message : String(err);
3037
+ return { text: JSON.stringify({ error: true, message }), isError: true };
3038
+ }
3039
+ }
1866
3040
  function handleListArtifacts(_cwd) {
1867
3041
  const cwd = _cwd ?? process.cwd();
1868
3042
  try {
1869
- const artifactsDir = (0, import_path4.join)(cwd, ".stackwright", "artifacts");
3043
+ const artifactsDir = (0, import_path5.join)(cwd, ".stackwright", "artifacts");
3044
+ let manifest = null;
3045
+ try {
3046
+ manifest = loadSignatureManifest(cwd);
3047
+ } catch {
3048
+ }
1870
3049
  const artifacts = [];
1871
3050
  let completedCount = 0;
1872
3051
  for (const phase of PHASE_ORDER) {
1873
3052
  const expectedFile = PHASE_ARTIFACT[phase];
1874
- const fullPath = (0, import_path4.join)(artifactsDir, expectedFile);
1875
- const exists = (0, import_fs4.existsSync)(fullPath);
3053
+ const fullPath = (0, import_path5.join)(artifactsDir, expectedFile);
3054
+ const exists = (0, import_fs5.existsSync)(fullPath);
1876
3055
  if (exists) completedCount++;
1877
- artifacts.push({ phase, expectedFile, exists, path: fullPath });
3056
+ let signed = false;
3057
+ let signatureValid = null;
3058
+ if (exists && manifest) {
3059
+ const entry = manifest.signatures[expectedFile];
3060
+ if (entry) {
3061
+ signed = true;
3062
+ try {
3063
+ const rawBytes = Buffer.from(safeReadSync(fullPath), "utf-8");
3064
+ const { publicKey } = loadPipelineKeys(cwd);
3065
+ signatureValid = verifyArtifact(rawBytes, entry, publicKey);
3066
+ } catch {
3067
+ signatureValid = null;
3068
+ }
3069
+ }
3070
+ }
3071
+ artifacts.push({ phase, expectedFile, exists, path: fullPath, signed, signatureValid });
1878
3072
  }
1879
3073
  return {
1880
3074
  text: JSON.stringify({ artifacts, completedCount, totalCount: PHASE_ORDER.length }),
@@ -1887,7 +3081,7 @@ function handleListArtifacts(_cwd) {
1887
3081
  function handleWritePhaseQuestions(input) {
1888
3082
  const cwd = input._cwd ?? process.cwd();
1889
3083
  const { phase, responseText } = input;
1890
- if (!isValidPhase(phase)) {
3084
+ if (!isValidPhase2(phase)) {
1891
3085
  return {
1892
3086
  text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
1893
3087
  isError: true
@@ -1910,9 +3104,9 @@ function handleWritePhaseQuestions(input) {
1910
3104
  }
1911
3105
  } catch {
1912
3106
  }
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`);
3107
+ const questionsDir = (0, import_path5.join)(cwd, ".stackwright", "questions");
3108
+ (0, import_fs5.mkdirSync)(questionsDir, { recursive: true });
3109
+ const filePath = (0, import_path5.join)(questionsDir, `${phase}.json`);
1916
3110
  const payload = {
1917
3111
  version: "1.0",
1918
3112
  phase,
@@ -1945,43 +3139,88 @@ function handleWritePhaseQuestions(input) {
1945
3139
  function handleBuildSpecialistPrompt(input) {
1946
3140
  const cwd = input._cwd ?? process.cwd();
1947
3141
  const { phase } = input;
1948
- if (!isValidPhase(phase)) {
3142
+ if (!isValidPhase2(phase)) {
1949
3143
  return {
1950
3144
  text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
1951
3145
  isError: true
1952
3146
  };
1953
3147
  }
1954
3148
  try {
1955
- const answersPath = (0, import_path4.join)(cwd, ".stackwright", "answers", `${phase}.json`);
3149
+ const answersPath = (0, import_path5.join)(cwd, ".stackwright", "answers", `${phase}.json`);
1956
3150
  let answers = {};
1957
- if ((0, import_fs4.existsSync)(answersPath)) {
3151
+ if ((0, import_fs5.existsSync)(answersPath)) {
1958
3152
  answers = JSON.parse(safeReadSync(answersPath));
1959
3153
  }
3154
+ let buildContextText = "";
3155
+ const buildContextPath = (0, import_path5.join)(cwd, ".stackwright", "build-context.json");
3156
+ if ((0, import_fs5.existsSync)(buildContextPath)) {
3157
+ try {
3158
+ const bcRaw = JSON.parse(safeReadSync(buildContextPath));
3159
+ if (typeof bcRaw.buildContext === "string" && bcRaw.buildContext.trim().length > 0) {
3160
+ buildContextText = bcRaw.buildContext.trim();
3161
+ }
3162
+ } catch {
3163
+ }
3164
+ }
1960
3165
  const deps = PHASE_DEPENDENCIES[phase];
1961
3166
  const artifactSections = [];
1962
3167
  const missingDependencies = [];
1963
3168
  for (const dep of deps) {
1964
3169
  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));
3170
+ const artifactPath = (0, import_path5.join)(cwd, ".stackwright", "artifacts", artifactFile);
3171
+ if ((0, import_fs5.existsSync)(artifactPath)) {
3172
+ const rawContent = safeReadSync(artifactPath);
3173
+ const rawBytes = Buffer.from(rawContent, "utf-8");
3174
+ const content = JSON.parse(rawContent);
3175
+ let signatureVerified = false;
3176
+ let signatureAvailable = false;
3177
+ try {
3178
+ const sig = getArtifactSignature(cwd, artifactFile);
3179
+ if (sig) {
3180
+ signatureAvailable = true;
3181
+ const { publicKey } = loadPipelineKeys(cwd);
3182
+ signatureVerified = verifyArtifact(rawBytes, sig, publicKey);
3183
+ if (!signatureVerified) {
3184
+ const actualDigest = (0, import_crypto3.createHash)("sha384").update(rawBytes).digest("hex");
3185
+ emitSignatureAuditEvent({
3186
+ artifactFilename: artifactFile,
3187
+ expectedDigest: sig.digest,
3188
+ actualDigest,
3189
+ phase: dep,
3190
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3191
+ source: "stackwright_pro_build_specialist_prompt"
3192
+ });
3193
+ missingDependencies.push(dep);
3194
+ artifactSections.push(
3195
+ `[${artifactFile}]:
3196
+ (integrity check failed: ECDSA-P384 signature verification failed \u2014 artifact may have been tampered with)`
3197
+ );
3198
+ continue;
3199
+ }
3200
+ }
3201
+ } catch {
3202
+ }
1968
3203
  const expectedOtter = PHASE_TO_OTTER2[dep];
1969
3204
  const artifactOtter = content["generatedBy"];
3205
+ const normalizedOtter = artifactOtter?.replace(/-[a-f0-9]{6}$/, "");
1970
3206
  if (!artifactOtter) {
1971
3207
  missingDependencies.push(dep);
1972
3208
  artifactSections.push(
1973
3209
  `[${artifactFile}]:
1974
3210
  (integrity check failed: missing generatedBy field)`
1975
3211
  );
1976
- } else if (artifactOtter !== expectedOtter) {
3212
+ } else if (normalizedOtter !== expectedOtter) {
1977
3213
  missingDependencies.push(dep);
1978
3214
  artifactSections.push(
1979
3215
  `[${artifactFile}]:
1980
3216
  (integrity check failed: artifact claims generatedBy="${artifactOtter}" but expected="${expectedOtter}")`
1981
3217
  );
1982
3218
  } else {
1983
- artifactSections.push(`[${artifactFile}]:
1984
- ${JSON.stringify(content, null, 2)}`);
3219
+ const sigStatus = signatureAvailable ? signatureVerified ? " [signature verified]" : " [signature check skipped]" : " [unsigned]";
3220
+ artifactSections.push(
3221
+ `[${artifactFile}]${sigStatus}:
3222
+ ${JSON.stringify(content, null, 2)}`
3223
+ );
1985
3224
  }
1986
3225
  } else {
1987
3226
  missingDependencies.push(dep);
@@ -1989,10 +3228,33 @@ ${JSON.stringify(content, null, 2)}`);
1989
3228
  (not yet available)`);
1990
3229
  }
1991
3230
  }
1992
- const parts = ["ANSWERS:", JSON.stringify(answers, null, 2)];
3231
+ const parts = [];
3232
+ if (buildContextText) {
3233
+ parts.push("BUILD_CONTEXT:", buildContextText, "");
3234
+ }
3235
+ if (phase === "auth") {
3236
+ const initContextPath = (0, import_path5.join)(cwd, ".stackwright", "init-context.json");
3237
+ if ((0, import_fs5.existsSync)(initContextPath)) {
3238
+ try {
3239
+ const initContext = JSON.parse(safeReadSync(initContextPath));
3240
+ if (initContext.devOnly === true || initContext.nonInteractive === true) {
3241
+ answers["devOnly"] = true;
3242
+ }
3243
+ } catch {
3244
+ }
3245
+ }
3246
+ }
3247
+ parts.push("ANSWERS:", JSON.stringify(answers, null, 2));
1993
3248
  if (artifactSections.length > 0) {
1994
3249
  parts.push("", "UPSTREAM ARTIFACTS:", "", ...artifactSections);
1995
3250
  }
3251
+ const artifactSchema = PHASE_ARTIFACT_SCHEMA[phase];
3252
+ parts.push("", "REQUIRED_ARTIFACT_SCHEMA:");
3253
+ parts.push(artifactSchema);
3254
+ const schemaRef = buildSchemaReferenceBlock(phase);
3255
+ if (schemaRef) {
3256
+ parts.push("", schemaRef);
3257
+ }
1996
3258
  parts.push("", "Execute using these answers and the upstream artifacts provided.");
1997
3259
  const prompt = parts.join("\n");
1998
3260
  const dependenciesSatisfied = missingDependencies.length === 0;
@@ -2027,45 +3289,322 @@ var OFF_SCRIPT_PATTERNS = [
2027
3289
  var PHASE_REQUIRED_KEYS = {
2028
3290
  designer: ["designLanguage", "themeTokenSeeds"],
2029
3291
  theme: ["tokens"],
2030
- api: ["entities"],
3292
+ api: ["entities", "version", "generatedBy"],
2031
3293
  auth: ["version", "generatedBy"],
2032
- data: ["version", "generatedBy"],
3294
+ data: ["version", "generatedBy", "strategy", "collections"],
2033
3295
  pages: ["version", "generatedBy"],
2034
3296
  dashboard: ["version", "generatedBy"],
2035
- workflow: ["version", "generatedBy"]
3297
+ workflow: ["version", "generatedBy"],
3298
+ services: ["version", "generatedBy", "flows"],
3299
+ polish: ["version", "generatedBy"],
3300
+ geo: ["version", "generatedBy", "geoCollections"]
3301
+ };
3302
+ var PHASE_ARTIFACT_SCHEMA = {
3303
+ designer: JSON.stringify(
3304
+ {
3305
+ version: "1.0",
3306
+ generatedBy: "stackwright-pro-designer-otter",
3307
+ application: {
3308
+ type: "<operational|data-explorer|admin|logistics|general>",
3309
+ environment: "<workstation|field|control-room|mixed>",
3310
+ density: "<compact|balanced|spacious>",
3311
+ accessibility: "<wcag-aa|section-508|none>",
3312
+ colorScheme: "<light|dark|both>"
3313
+ },
3314
+ designLanguage: {
3315
+ rationale: "<design rationale>",
3316
+ spacingScale: { base: 8, scale: [0, 4, 8, 16, 24, 32, 48, 64] },
3317
+ colorSemantics: { primary: "#1a365d", accent: "#e53e3e" },
3318
+ typography: {
3319
+ dataFont: "Inter",
3320
+ headingFont: "Inter",
3321
+ monoFont: "monospace",
3322
+ dataSizePx: 12,
3323
+ bodySizePx: 14
3324
+ },
3325
+ contrastRatio: "4.5",
3326
+ borderRadius: "4",
3327
+ shadowElevation: "standard"
3328
+ },
3329
+ themeTokenSeeds: {
3330
+ light: {
3331
+ background: "#ffffff",
3332
+ foreground: "#1a1a1a",
3333
+ primary: "#1a365d",
3334
+ surface: "#f7f7f7",
3335
+ border: "#e2e8f0"
3336
+ },
3337
+ dark: {
3338
+ background: "#1a1a1a",
3339
+ foreground: "#ffffff",
3340
+ primary: "#90cdf4",
3341
+ surface: "#2d2d2d",
3342
+ border: "#4a5568"
3343
+ }
3344
+ },
3345
+ conformsTo: null,
3346
+ operationalNotes: []
3347
+ },
3348
+ null,
3349
+ 2
3350
+ ),
3351
+ theme: JSON.stringify(
3352
+ {
3353
+ version: "1.0",
3354
+ generatedBy: "stackwright-pro-theme-otter",
3355
+ componentLibrary: "shadcn",
3356
+ colorScheme: "<light|dark|both>",
3357
+ tokens: {
3358
+ colors: { "primary-500": "#1a365d", background: "#ffffff" },
3359
+ spacing: { "spacing-1": "8px", "spacing-2": "16px" },
3360
+ typography: { "font-data": "Inter", "text-sm": "12px" },
3361
+ shape: { "radius-sm": "4px", "radius-md": "8px" },
3362
+ shadows: { "shadow-sm": "0 1px 2px rgba(0,0,0,0.08)" }
3363
+ },
3364
+ cssVariables: {
3365
+ "--background": "0 0% 100%",
3366
+ "--foreground": "222.2 84% 4.9%",
3367
+ "--primary": "222.2 47.4% 11.2%",
3368
+ "--primary-foreground": "210 40% 98%",
3369
+ "--surface": "210 40% 98%",
3370
+ "--border": "214.3 31.8% 91.4%"
3371
+ },
3372
+ dark: { "--background": "222.2 84% 4.9%", "--foreground": "210 40% 98%" }
3373
+ },
3374
+ null,
3375
+ 2
3376
+ ),
3377
+ api: JSON.stringify(
3378
+ {
3379
+ version: "1.0",
3380
+ generatedBy: "stackwright-pro-api-otter",
3381
+ entities: [
3382
+ {
3383
+ name: "Shipment",
3384
+ endpoint: "/shipments",
3385
+ method: "GET",
3386
+ revalidate: 60,
3387
+ mutationType: null
3388
+ }
3389
+ ],
3390
+ skipped: [
3391
+ {
3392
+ spec: "ais-message-models.yaml",
3393
+ format: "asyncapi",
3394
+ reason: "AsyncAPI spec \u2014 WebSocket/event integration required (no REST endpoints)"
3395
+ }
3396
+ ],
3397
+ warnings: [
3398
+ "Spec contains external $ref URLs \u2014 recommend bundle: true in stackwright.yml integration config"
3399
+ ],
3400
+ auth: { type: "bearer", header: "Authorization", envVar: "API_TOKEN" },
3401
+ baseUrl: "https://api.example.mil/v2",
3402
+ specPath: "./specs/api.yaml"
3403
+ },
3404
+ null,
3405
+ 2
3406
+ ),
3407
+ data: JSON.stringify(
3408
+ {
3409
+ version: "1.0",
3410
+ generatedBy: "stackwright-pro-data-otter",
3411
+ strategy: "<pulse-fast|isr-fast|isr-standard|isr-slow>",
3412
+ pulseMode: false,
3413
+ collections: [{ name: "equipment", revalidate: 60, pulse: false }],
3414
+ endpoints: { included: ["/equipment/**"], excluded: ["/admin/**"] },
3415
+ requiredPackages: { dependencies: {}, devPackages: {} }
3416
+ },
3417
+ null,
3418
+ 2
3419
+ ),
3420
+ geo: JSON.stringify(
3421
+ {
3422
+ version: "1.0",
3423
+ generatedBy: "stackwright-pro-geo-otter",
3424
+ geoCollections: [
3425
+ {
3426
+ collection: "vessels",
3427
+ latField: "latitude",
3428
+ lngField: "longitude",
3429
+ labelField: "vesselName",
3430
+ colorField: "navigationStatus"
3431
+ }
3432
+ ],
3433
+ pages: [
3434
+ {
3435
+ slug: "fleet-tracker",
3436
+ type: "<tracker|zone|route|combined>",
3437
+ collections: ["vessels"],
3438
+ hasLayers: false
3439
+ }
3440
+ ]
3441
+ },
3442
+ null,
3443
+ 2
3444
+ ),
3445
+ workflow: JSON.stringify(
3446
+ {
3447
+ version: "1.0",
3448
+ generatedBy: "stackwright-pro-workflow-otter",
3449
+ workflowConfig: {
3450
+ id: "procurement-approval",
3451
+ route: "/procurement",
3452
+ files: ["workflows/procurement-approval.yml"],
3453
+ serviceDependencies: ["service:workflow-state"],
3454
+ warnings: []
3455
+ }
3456
+ },
3457
+ null,
3458
+ 2
3459
+ ),
3460
+ services: JSON.stringify(
3461
+ {
3462
+ version: "1.0",
3463
+ generatedBy: "stackwright-services-otter",
3464
+ flows: [
3465
+ {
3466
+ name: "at-risk-patients",
3467
+ trigger: "<http|event|schedule|queue>",
3468
+ steps: 3,
3469
+ outputSpec: "at-risk-patients.openapi.json"
3470
+ }
3471
+ ],
3472
+ workflows: [
3473
+ {
3474
+ name: "evacuation-coordination",
3475
+ states: 4,
3476
+ transitions: 5
3477
+ }
3478
+ ],
3479
+ openApiSpecs: ["at-risk-patients.openapi.json"],
3480
+ capabilitiesUsed: ["service.call", "collection.join", "collection.filter"]
3481
+ },
3482
+ null,
3483
+ 2
3484
+ ),
3485
+ pages: JSON.stringify(
3486
+ {
3487
+ version: "1.0",
3488
+ generatedBy: "stackwright-pro-page-otter",
3489
+ pages: [
3490
+ {
3491
+ slug: "catalog",
3492
+ type: "collection_listing",
3493
+ collection: "products",
3494
+ themeApplied: true,
3495
+ authRequired: false
3496
+ },
3497
+ {
3498
+ slug: "admin",
3499
+ type: "protected",
3500
+ collection: null,
3501
+ themeApplied: true,
3502
+ authRequired: true
3503
+ }
3504
+ ]
3505
+ },
3506
+ null,
3507
+ 2
3508
+ ),
3509
+ dashboard: JSON.stringify(
3510
+ {
3511
+ version: "1.0",
3512
+ generatedBy: "stackwright-pro-dashboard-otter",
3513
+ pages: [
3514
+ {
3515
+ slug: "dashboard",
3516
+ layout: "<grid|table|mixed>",
3517
+ collections: ["equipment", "supplies"],
3518
+ mode: "<ISR|Pulse>"
3519
+ }
3520
+ ]
3521
+ },
3522
+ null,
3523
+ 2
3524
+ ),
3525
+ // type: 'pki' = CAC/DoD certificate auth | 'oidc' = enterprise SSO
3526
+ // For dev-only mock auth: use type: 'oidc' with devOnly: true (Zod strips devOnly — it's a convention only)
3527
+ auth: JSON.stringify(
3528
+ {
3529
+ version: "1.0",
3530
+ generatedBy: "stackwright-pro-auth-otter",
3531
+ authConfig: {
3532
+ type: "<pki|oidc>",
3533
+ // OIDC-only fields (omit for pki):
3534
+ provider: "<azure_ad|okta|cognito|auth0|authentik|keycloak|custom>",
3535
+ discoveryUrl: "<IdP OIDC discovery URL>",
3536
+ clientId: "<OIDC client ID>",
3537
+ clientSecret: "<OIDC client secret>",
3538
+ rbacRoles: ["ADMIN", "ANALYST"],
3539
+ rbacDefaultRole: "ANALYST",
3540
+ protectedRoutes: ["/dashboard/:path*", "/procurement/:path*"],
3541
+ auditEnabled: true,
3542
+ auditRetentionDays: 90
3543
+ },
3544
+ // devScripts is OPTIONAL — only present when devOnly: true was used
3545
+ // Polish otter and foreman MUST check devScripts.written before referencing scripts
3546
+ devScripts: {
3547
+ written: true,
3548
+ scripts: { "dev:admin": "MOCK_USER=admin next dev" }
3549
+ }
3550
+ },
3551
+ null,
3552
+ 2
3553
+ ),
3554
+ polish: JSON.stringify(
3555
+ {
3556
+ version: "1.0",
3557
+ generatedBy: "stackwright-pro-polish-otter",
3558
+ landingPage: { slug: "", rewritten: true },
3559
+ navigation: { itemCount: 5, items: ["/dashboard", "/equipment", "/workflows"] },
3560
+ gettingStarted: "<rewritten|redirected|not-found>",
3561
+ scaffoldCleanup: {
3562
+ deleted: ["content/posts/getting-started.yaml"],
3563
+ rewritten: ["app/not-found.tsx"],
3564
+ skipped: []
3565
+ }
3566
+ },
3567
+ null,
3568
+ 2
3569
+ )
2036
3570
  };
2037
3571
  function handleValidateArtifact(input) {
2038
3572
  const cwd = input._cwd ?? process.cwd();
2039
- const { phase, responseText } = input;
2040
- if (!isValidPhase(phase)) {
3573
+ const { phase, responseText, artifact: directArtifact } = input;
3574
+ if (!isValidPhase2(phase)) {
2041
3575
  return {
2042
3576
  text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
2043
3577
  isError: true
2044
3578
  };
2045
3579
  }
2046
- for (const { pattern, label } of OFF_SCRIPT_PATTERNS) {
2047
- if (pattern.test(responseText)) {
3580
+ let artifact;
3581
+ if (directArtifact) {
3582
+ artifact = directArtifact;
3583
+ } else {
3584
+ const text = responseText ?? "";
3585
+ for (const { pattern, label } of OFF_SCRIPT_PATTERNS) {
3586
+ if (pattern.test(text)) {
3587
+ const result = {
3588
+ valid: false,
3589
+ phase,
3590
+ violation: "off-script",
3591
+ retryPrompt: `You returned code output (detected: ${label}). Return ONLY a JSON artifact \u2014 no code, no files.`
3592
+ };
3593
+ return { text: JSON.stringify(result), isError: false };
3594
+ }
3595
+ }
3596
+ try {
3597
+ artifact = extractJsonFromResponse(text);
3598
+ } catch {
2048
3599
  const result = {
2049
3600
  valid: false,
2050
3601
  phase,
2051
- violation: "off-script",
2052
- retryPrompt: `You returned code output (detected: ${label}). Return ONLY a JSON artifact \u2014 no code, no files.`
3602
+ violation: "invalid-json",
3603
+ retryPrompt: "Your response did not contain valid JSON. Return a single JSON object with no surrounding text."
2053
3604
  };
2054
3605
  return { text: JSON.stringify(result), isError: false };
2055
3606
  }
2056
3607
  }
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
3608
  if (!artifact.version || !artifact.generatedBy) {
2070
3609
  const result = {
2071
3610
  valid: false,
@@ -2086,12 +3625,58 @@ function handleValidateArtifact(input) {
2086
3625
  };
2087
3626
  return { text: JSON.stringify(result), isError: false };
2088
3627
  }
3628
+ const PHASE_ZOD_VALIDATORS = {
3629
+ workflow: (artifact2) => {
3630
+ const workflowConfig = artifact2["workflowConfig"];
3631
+ if (!workflowConfig) return { success: true };
3632
+ const result = import_types3.WorkflowFileSchema.safeParse(workflowConfig);
3633
+ if (!result.success) {
3634
+ const issues = result.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
3635
+ return { success: false, error: { message: issues } };
3636
+ }
3637
+ return { success: true };
3638
+ },
3639
+ auth: (artifact2) => {
3640
+ const authConfig = artifact2["authConfig"];
3641
+ if (!authConfig) return { success: true };
3642
+ const result = import_types3.authConfigSchema.safeParse(authConfig);
3643
+ if (!result.success) {
3644
+ const issues = result.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
3645
+ return { success: false, error: { message: issues } };
3646
+ }
3647
+ return { success: true };
3648
+ }
3649
+ };
3650
+ const zodValidator = PHASE_ZOD_VALIDATORS[phase];
3651
+ if (zodValidator) {
3652
+ const zodResult = zodValidator(artifact);
3653
+ if (!zodResult.success) {
3654
+ const result = {
3655
+ valid: false,
3656
+ phase,
3657
+ violation: "schema-mismatch",
3658
+ retryPrompt: `Your artifact failed schema validation: ${zodResult.error?.message}. Fix these fields and return the corrected JSON artifact.`
3659
+ };
3660
+ return { text: JSON.stringify(result), isError: false };
3661
+ }
3662
+ }
2089
3663
  try {
2090
- const artifactsDir = (0, import_path4.join)(cwd, ".stackwright", "artifacts");
2091
- (0, import_fs4.mkdirSync)(artifactsDir, { recursive: true });
3664
+ const artifactsDir = (0, import_path5.join)(cwd, ".stackwright", "artifacts");
3665
+ (0, import_fs5.mkdirSync)(artifactsDir, { recursive: true });
2092
3666
  const artifactFile = PHASE_ARTIFACT[phase];
2093
- const artifactPath = (0, import_path4.join)(artifactsDir, artifactFile);
2094
- safeWriteSync(artifactPath, JSON.stringify(artifact, null, 2) + "\n");
3667
+ const artifactPath = (0, import_path5.join)(artifactsDir, artifactFile);
3668
+ const serialized = JSON.stringify(artifact, null, 2) + "\n";
3669
+ const artifactBytes = Buffer.from(serialized, "utf-8");
3670
+ safeWriteSync(artifactPath, serialized);
3671
+ let signed = false;
3672
+ try {
3673
+ const { privateKey } = loadPipelineKeys(cwd);
3674
+ const sig = signArtifact(artifactBytes, privateKey);
3675
+ const signerOtter = PHASE_TO_OTTER2[phase];
3676
+ saveArtifactSignature(cwd, artifactFile, sig, signerOtter);
3677
+ signed = true;
3678
+ } catch {
3679
+ }
2095
3680
  const state = readState(cwd);
2096
3681
  if (!state.phases[phase]) state.phases[phase] = defaultPhaseStatus();
2097
3682
  const ps = state.phases[phase];
@@ -2102,7 +3687,7 @@ function handleValidateArtifact(input) {
2102
3687
  valid: true,
2103
3688
  phase,
2104
3689
  artifactPath,
2105
- summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})`
3690
+ summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})${signed ? " [signed]" : ""}`
2106
3691
  };
2107
3692
  return { text: JSON.stringify(result), isError: false };
2108
3693
  } catch (err) {
@@ -2126,11 +3711,24 @@ function registerPipelineTools(server2) {
2126
3711
  "stackwright_pro_set_pipeline_state",
2127
3712
  `Atomic read\u2192modify\u2192write pipeline state. ${DESC}`,
2128
3713
  {
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")
3714
+ phase: import_zod13.z.string().optional().describe('Phase to update, e.g. "designer"'),
3715
+ field: import_zod13.z.enum(["questionsCollected", "answered", "executed", "artifactWritten"]).optional().describe("Boolean field to set"),
3716
+ value: boolCoerce(import_zod13.z.boolean().optional()).describe(
3717
+ 'Value for the field \u2014 must be a JSON boolean (true/false), NOT the string "true"/"false"'
3718
+ ),
3719
+ status: import_zod13.z.enum(["setup", "questions", "execution", "done"]).optional().describe("Top-level status override"),
3720
+ incrementRetry: boolCoerce(import_zod13.z.boolean().optional()).describe(
3721
+ "Bump retryCount by 1 \u2014 must be a JSON boolean"
3722
+ ),
3723
+ updates: jsonCoerce(
3724
+ import_zod13.z.array(
3725
+ import_zod13.z.object({
3726
+ phase: import_zod13.z.string(),
3727
+ field: import_zod13.z.enum(["questionsCollected", "answered", "executed", "artifactWritten"]),
3728
+ value: import_zod13.z.boolean()
3729
+ })
3730
+ ).optional()
3731
+ ).describe("Batch updates \u2014 apply multiple field changes in one atomic read\u2192modify\u2192write")
2134
3732
  },
2135
3733
  async (args) => res(
2136
3734
  handleSetPipelineState({
@@ -2138,15 +3736,24 @@ function registerPipelineTools(server2) {
2138
3736
  ...args.field != null ? { field: args.field } : {},
2139
3737
  ...args.value != null ? { value: args.value } : {},
2140
3738
  ...args.status != null ? { status: args.status } : {},
2141
- ...args.incrementRetry != null ? { incrementRetry: args.incrementRetry } : {}
3739
+ ...args.incrementRetry != null ? { incrementRetry: args.incrementRetry } : {},
3740
+ ...args.updates != null ? { updates: args.updates } : {}
2142
3741
  })
2143
3742
  )
2144
3743
  );
2145
3744
  server2.tool(
2146
3745
  "stackwright_pro_check_execution_ready",
2147
- `Check all phases have answer files in .stackwright/answers/. ${DESC}`,
3746
+ `Check all phases have answer files in .stackwright/answers/. If phase is provided, check only that phase. ${DESC}`,
3747
+ {
3748
+ phase: import_zod13.z.string().optional().describe("If provided, check only this phase's readiness. Omit to check all phases.")
3749
+ },
3750
+ async ({ phase }) => res(handleCheckExecutionReady(void 0, phase))
3751
+ );
3752
+ server2.tool(
3753
+ "stackwright_pro_get_ready_phases",
3754
+ `Return phases whose dependencies are all satisfied (executed=true). Use to determine which phases can run next \u2014 enables wave-based execution. ${DESC}`,
2148
3755
  {},
2149
- async () => res(handleCheckExecutionReady())
3756
+ async () => res(handleGetReadyPhases())
2150
3757
  );
2151
3758
  server2.tool(
2152
3759
  "stackwright_pro_list_artifacts",
@@ -2156,40 +3763,91 @@ function registerPipelineTools(server2) {
2156
3763
  );
2157
3764
  server2.tool(
2158
3765
  "stackwright_pro_write_phase_questions",
2159
- `Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. ${DESC}`,
3766
+ `Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. Specialists may also call this directly with a parsed questions array. ${DESC}`,
2160
3767
  {
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")
3768
+ phase: import_zod13.z.string().optional().describe('Phase name, e.g. "designer" (required for direct write)'),
3769
+ responseText: import_zod13.z.string().optional().describe("Raw LLM response from QUESTION_COLLECTION_MODE"),
3770
+ questions: jsonCoerce(import_zod13.z.array(import_zod13.z.any()).optional()).describe(
3771
+ "Questions array for direct specialist write"
3772
+ )
2163
3773
  },
2164
- async ({ phase, responseText }) => res(handleWritePhaseQuestions({ phase, responseText }))
3774
+ async ({ phase, responseText, questions }) => {
3775
+ if (phase && questions && Array.isArray(questions)) {
3776
+ if (!SAFE_PHASE.test(phase)) {
3777
+ return {
3778
+ content: [
3779
+ { type: "text", text: JSON.stringify({ error: `Invalid phase name` }) }
3780
+ ],
3781
+ isError: true
3782
+ };
3783
+ }
3784
+ const questionsDir = (0, import_path5.join)(process.cwd(), ".stackwright", "questions");
3785
+ (0, import_fs5.mkdirSync)(questionsDir, { recursive: true });
3786
+ const outPath = (0, import_path5.join)(questionsDir, `${phase}.json`);
3787
+ (0, import_fs5.writeFileSync)(
3788
+ outPath,
3789
+ JSON.stringify({ phase, questions, writtenAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2)
3790
+ );
3791
+ return {
3792
+ content: [
3793
+ {
3794
+ type: "text",
3795
+ text: JSON.stringify({
3796
+ written: true,
3797
+ phase,
3798
+ count: questions.length
3799
+ })
3800
+ }
3801
+ ]
3802
+ };
3803
+ }
3804
+ return res(
3805
+ handleWritePhaseQuestions({ phase: phase ?? "", responseText: responseText ?? "" })
3806
+ );
3807
+ }
2165
3808
  );
2166
3809
  server2.tool(
2167
3810
  "stackwright_pro_build_specialist_prompt",
2168
3811
  `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"') },
3812
+ { phase: import_zod13.z.string().describe('Phase to build prompt for, e.g. "pages"') },
2170
3813
  async ({ phase }) => res(handleBuildSpecialistPrompt({ phase }))
2171
3814
  );
2172
3815
  server2.tool(
2173
3816
  "stackwright_pro_validate_artifact",
2174
- `Validate specialist response + write artifact to .stackwright/artifacts/. Returns retryPrompt on failure. ${DESC}`,
3817
+ `Validate and write artifact to .stackwright/artifacts/. Returns retryPrompt on failure. ${DESC}`,
2175
3818
  {
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")
3819
+ phase: import_zod13.z.string().describe('Phase that produced this artifact, e.g. "designer"'),
3820
+ responseText: import_zod13.z.string().optional().describe("Raw response text from the specialist otter (Foreman-mediated path, legacy)"),
3821
+ artifact: jsonCoerce(import_zod13.z.record(import_zod13.z.string(), import_zod13.z.unknown()).optional()).describe(
3822
+ "Artifact object to validate and write directly (specialist direct path \u2014 skips off-script detection and JSON parsing)"
3823
+ )
2178
3824
  },
2179
- async ({ phase, responseText }) => res(handleValidateArtifact({ phase, responseText }))
3825
+ async ({ phase, responseText, artifact }) => {
3826
+ if (artifact) {
3827
+ return res(
3828
+ handleValidateArtifact({ phase, artifact })
3829
+ );
3830
+ }
3831
+ return res(handleValidateArtifact({ phase, responseText: responseText ?? "" }));
3832
+ }
2180
3833
  );
2181
3834
  }
2182
3835
 
2183
3836
  // src/tools/safe-write.ts
2184
- var import_zod10 = require("zod");
2185
- var import_fs5 = require("fs");
2186
- var import_path5 = require("path");
3837
+ var import_zod14 = require("zod");
3838
+ var import_fs6 = require("fs");
3839
+ var import_path6 = require("path");
2187
3840
  var OTTER_WRITE_ALLOWLISTS = {
2188
3841
  "stackwright-pro-designer-otter": [
2189
3842
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Design language artifact" }
2190
3843
  ],
2191
3844
  "stackwright-pro-theme-otter": [
2192
- { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" }
3845
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" },
3846
+ {
3847
+ prefix: "stackwright.theme.",
3848
+ suffix: ".yml",
3849
+ description: "Theme config YAML (merged at build time)"
3850
+ }
2193
3851
  ],
2194
3852
  "stackwright-pro-auth-otter": [
2195
3853
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Auth config artifact" },
@@ -2199,6 +3857,16 @@ var OTTER_WRITE_ALLOWLISTS = {
2199
3857
  prefix: ".env",
2200
3858
  suffix: "",
2201
3859
  description: "Dotenv files (.env, .env.local, .env.production, etc.)"
3860
+ },
3861
+ {
3862
+ prefix: "lib/mock-auth",
3863
+ suffix: ".ts",
3864
+ description: "Mock auth module (DEV_ONLY_MODE role updates)"
3865
+ },
3866
+ {
3867
+ prefix: "package.json",
3868
+ suffix: ".json",
3869
+ description: "Project package.json (DEV_ONLY_MODE script cleanup)"
2202
3870
  }
2203
3871
  ],
2204
3872
  "stackwright-pro-data-otter": [
@@ -2220,21 +3888,125 @@ var OTTER_WRITE_ALLOWLISTS = {
2220
3888
  { prefix: "workflows/", suffix: ".yaml", description: "Workflow definition" },
2221
3889
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Workflow config" }
2222
3890
  ],
3891
+ "stackwright-pro-scaffold-otter": [
3892
+ { prefix: "app/", suffix: ".tsx", description: "Next.js App Router shell files" },
3893
+ {
3894
+ prefix: ".stackwright/artifacts/",
3895
+ suffix: ".json",
3896
+ description: "Scaffold manifest artifact"
3897
+ }
3898
+ ],
2223
3899
  "stackwright-pro-api-otter": [
2224
3900
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "API config artifact" }
3901
+ ],
3902
+ "stackwright-pro-geo-otter": [
3903
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Geo manifest artifact" },
3904
+ { prefix: "pages/", suffix: "/content.yml", description: "Map page content" },
3905
+ { prefix: "pages/", suffix: "/content.yaml", description: "Map page content" }
3906
+ ],
3907
+ "stackwright-pro-polish-otter": [
3908
+ {
3909
+ prefix: "stackwright.yml",
3910
+ suffix: "",
3911
+ description: "Stackwright config (navigation updates)"
3912
+ },
3913
+ { prefix: "pages/", suffix: "/content.yml", description: "Landing page content" },
3914
+ { prefix: "pages/", suffix: "/content.yaml", description: "Landing page content" },
3915
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Polish artifact" },
3916
+ { prefix: "README.md", suffix: "", description: "Project README rewrite" }
3917
+ ],
3918
+ "stackwright-services-otter": [
3919
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Services config artifact" },
3920
+ { prefix: "services/", suffix: ".ts", description: "Service implementation files" },
3921
+ { prefix: "services/", suffix: ".yaml", description: "Service flow definitions" },
3922
+ { prefix: "services/", suffix: ".yml", description: "Service flow definitions" },
3923
+ { prefix: "lib/seeds/", suffix: ".ts", description: "Seed data files" },
3924
+ { prefix: "specs/", suffix: ".json", description: "Generated OpenAPI specs" },
3925
+ { prefix: "specs/", suffix: ".yaml", description: "Generated OpenAPI specs" },
3926
+ { prefix: "stackwright-generated/", suffix: ".json", description: "Services manifest" }
2225
3927
  ]
2226
3928
  };
2227
3929
  var PROTECTED_PATH_PREFIXES = [
2228
3930
  ".stackwright/pipeline-state.json",
3931
+ ".stackwright/pipeline-keys.json",
3932
+ // ephemeral signing keys
3933
+ ".stackwright/artifacts/signatures.json",
3934
+ // artifact signature manifest
2229
3935
  ".stackwright/questions/",
2230
- ".stackwright/answers/"
3936
+ ".stackwright/answers/",
3937
+ ".stackwright/page-registry.json"
3938
+ // page ownership — managed by safe_write internally
2231
3939
  ];
3940
+ var MAX_SAFE_WRITE_BYTES_JSON = 512 * 1024;
3941
+ var MAX_SAFE_WRITE_BYTES_YAML = 256 * 1024;
3942
+ var MAX_SAFE_WRITE_BYTES_ENV = 4 * 1024;
3943
+ var MAX_SAFE_WRITE_BYTES_DEFAULT = 256 * 1024;
3944
+ function getMaxBytesForPath(filePath) {
3945
+ if (filePath.endsWith(".json")) return { limit: MAX_SAFE_WRITE_BYTES_JSON, label: "JSON" };
3946
+ if (filePath.endsWith(".yml") || filePath.endsWith(".yaml"))
3947
+ return { limit: MAX_SAFE_WRITE_BYTES_YAML, label: "YAML" };
3948
+ if (filePath === ".env" || /^\.env\.[a-zA-Z0-9]+/.test(filePath))
3949
+ return { limit: MAX_SAFE_WRITE_BYTES_ENV, label: "env" };
3950
+ return { limit: MAX_SAFE_WRITE_BYTES_DEFAULT, label: "default" };
3951
+ }
3952
+ var PAGE_REGISTRY_FILE = ".stackwright/page-registry.json";
3953
+ function extractPageSlug(filePath) {
3954
+ const match = (0, import_path6.normalize)(filePath).match(/^pages\/(.+?)\/content\.ya?ml$/);
3955
+ return match?.[1] ?? null;
3956
+ }
3957
+ function extractContentTypes(yamlContent) {
3958
+ const typePattern = /^\s*-?\s*type:\s*(\S+)/gm;
3959
+ const types = [];
3960
+ let m;
3961
+ while ((m = typePattern.exec(yamlContent)) !== null) {
3962
+ const typeName = m[1];
3963
+ if (typeName && !types.includes(typeName)) {
3964
+ types.push(typeName);
3965
+ }
3966
+ }
3967
+ return types.length > 0 ? types : ["unknown"];
3968
+ }
3969
+ function readPageRegistry(cwd) {
3970
+ const regPath = (0, import_path6.join)(cwd, PAGE_REGISTRY_FILE);
3971
+ if (!(0, import_fs6.existsSync)(regPath)) return {};
3972
+ try {
3973
+ const stat = (0, import_fs6.lstatSync)(regPath);
3974
+ if (stat.isSymbolicLink()) return {};
3975
+ return JSON.parse((0, import_fs6.readFileSync)(regPath, "utf-8"));
3976
+ } catch {
3977
+ return {};
3978
+ }
3979
+ }
3980
+ function writePageRegistry(cwd, registry) {
3981
+ const dir = (0, import_path6.join)(cwd, ".stackwright");
3982
+ (0, import_fs6.mkdirSync)(dir, { recursive: true });
3983
+ const regPath = (0, import_path6.join)(cwd, PAGE_REGISTRY_FILE);
3984
+ if ((0, import_fs6.existsSync)(regPath)) {
3985
+ const stat = (0, import_fs6.lstatSync)(regPath);
3986
+ if (stat.isSymbolicLink()) {
3987
+ throw new Error("Refusing to write page registry through symlink");
3988
+ }
3989
+ }
3990
+ (0, import_fs6.writeFileSync)(regPath, JSON.stringify(registry, null, 2) + "\n", { encoding: "utf-8" });
3991
+ }
3992
+ function checkPageOwnership(cwd, slug, callerOtter) {
3993
+ const registry = readPageRegistry(cwd);
3994
+ const existing = registry[slug];
3995
+ if (!existing || existing.claimedBy === callerOtter) {
3996
+ return { allowed: true };
3997
+ }
3998
+ return {
3999
+ allowed: false,
4000
+ owner: existing.claimedBy,
4001
+ contentTypes: existing.contentTypes
4002
+ };
4003
+ }
2232
4004
  function checkPathAllowed(callerOtter, filePath) {
2233
- const normalized = (0, import_path5.normalize)(filePath);
4005
+ const normalized = (0, import_path6.normalize)(filePath);
2234
4006
  if (normalized.includes("..")) {
2235
4007
  return { allowed: false, error: 'Path traversal detected: ".." segments are not allowed' };
2236
4008
  }
2237
- if ((0, import_path5.isAbsolute)(normalized)) {
4009
+ if ((0, import_path6.isAbsolute)(normalized)) {
2238
4010
  return {
2239
4011
  allowed: false,
2240
4012
  error: "Absolute paths are not allowed \u2014 use paths relative to project root"
@@ -2270,6 +4042,16 @@ function checkPathAllowed(callerOtter, filePath) {
2270
4042
  continue;
2271
4043
  }
2272
4044
  }
4045
+ if (rule.prefix === "lib/mock-auth" && rule.suffix === ".ts") {
4046
+ if (normalized !== "lib/mock-auth.ts") {
4047
+ continue;
4048
+ }
4049
+ }
4050
+ if (rule.prefix === "package.json" && rule.suffix === ".json") {
4051
+ if (normalized !== "package.json") {
4052
+ continue;
4053
+ }
4054
+ }
2273
4055
  return { allowed: true, rule: rule.description };
2274
4056
  }
2275
4057
  }
@@ -2354,11 +4136,23 @@ function handleSafeWrite(input) {
2354
4136
  };
2355
4137
  return { text: JSON.stringify(result), isError: true };
2356
4138
  }
2357
- const normalized = (0, import_path5.normalize)(filePath);
2358
- const fullPath = (0, import_path5.join)(cwd, normalized);
2359
- if ((0, import_fs5.existsSync)(fullPath)) {
4139
+ const contentBytes = Buffer.byteLength(content, "utf-8");
4140
+ const { limit: maxBytes, label: fileTypeLabel } = getMaxBytesForPath(filePath);
4141
+ if (contentBytes > maxBytes) {
4142
+ const result = {
4143
+ success: false,
4144
+ error: `Content size ${contentBytes} bytes exceeds ${fileTypeLabel} limit of ${maxBytes} bytes (${maxBytes / 1024} KB)`,
4145
+ callerOtter,
4146
+ attemptedPath: filePath,
4147
+ allowedPaths: []
4148
+ };
4149
+ return { text: JSON.stringify(result), isError: true };
4150
+ }
4151
+ const normalized = (0, import_path6.normalize)(filePath);
4152
+ const fullPath = (0, import_path6.join)(cwd, normalized);
4153
+ if ((0, import_fs6.existsSync)(fullPath)) {
2360
4154
  try {
2361
- const stat = (0, import_fs5.lstatSync)(fullPath);
4155
+ const stat = (0, import_fs6.lstatSync)(fullPath);
2362
4156
  if (stat.isSymbolicLink()) {
2363
4157
  const result = {
2364
4158
  success: false,
@@ -2383,11 +4177,38 @@ function handleSafeWrite(input) {
2383
4177
  };
2384
4178
  return { text: JSON.stringify(result), isError: true };
2385
4179
  }
4180
+ const pageSlug = extractPageSlug(normalized);
4181
+ if (pageSlug) {
4182
+ const ownership = checkPageOwnership(cwd, pageSlug, callerOtter);
4183
+ if (!ownership.allowed) {
4184
+ const result = {
4185
+ success: false,
4186
+ error: `Page slug "${pageSlug}" is already claimed by ${ownership.owner} (content types: ${ownership.contentTypes.join(", ")}). Use a different slug or coordinate with the owning otter.`,
4187
+ callerOtter,
4188
+ attemptedPath: filePath,
4189
+ allowedPaths: []
4190
+ };
4191
+ return { text: JSON.stringify(result), isError: true };
4192
+ }
4193
+ }
2386
4194
  try {
2387
4195
  if (createDirectories) {
2388
- (0, import_fs5.mkdirSync)((0, import_path5.dirname)(fullPath), { recursive: true });
4196
+ (0, import_fs6.mkdirSync)((0, import_path6.dirname)(fullPath), { recursive: true });
4197
+ }
4198
+ (0, import_fs6.writeFileSync)(fullPath, content, { encoding: "utf-8" });
4199
+ if (pageSlug) {
4200
+ try {
4201
+ const registry = readPageRegistry(cwd);
4202
+ registry[pageSlug] = {
4203
+ slug: pageSlug,
4204
+ claimedBy: callerOtter,
4205
+ contentTypes: extractContentTypes(content),
4206
+ writtenAt: (/* @__PURE__ */ new Date()).toISOString()
4207
+ };
4208
+ writePageRegistry(cwd, registry);
4209
+ } catch {
4210
+ }
2389
4211
  }
2390
- (0, import_fs5.writeFileSync)(fullPath, content, { encoding: "utf-8" });
2391
4212
  const result = {
2392
4213
  success: true,
2393
4214
  path: normalized,
@@ -2413,10 +4234,12 @@ function registerSafeWriteTools(server2) {
2413
4234
  "stackwright_pro_safe_write",
2414
4235
  DESC,
2415
4236
  {
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")
4237
+ callerOtter: import_zod14.z.string().describe('The otter agent name requesting the write, e.g. "stackwright-pro-page-otter"'),
4238
+ filePath: import_zod14.z.string().describe('Relative path from project root, e.g. "pages/dashboard/content.yml"'),
4239
+ content: import_zod14.z.string().describe("File content to write"),
4240
+ createDirectories: boolCoerce(import_zod14.z.boolean().optional().default(true)).describe(
4241
+ "Create parent directories if they don't exist. Default: true"
4242
+ )
2420
4243
  },
2421
4244
  async ({ callerOtter, filePath, content, createDirectories }) => {
2422
4245
  const result = handleSafeWrite({
@@ -2431,9 +4254,9 @@ function registerSafeWriteTools(server2) {
2431
4254
  }
2432
4255
 
2433
4256
  // src/tools/auth.ts
2434
- var import_zod11 = require("zod");
2435
- var import_fs6 = require("fs");
2436
- var import_path6 = require("path");
4257
+ var import_zod15 = require("zod");
4258
+ var import_fs7 = require("fs");
4259
+ var import_path7 = require("path");
2437
4260
  function buildHierarchy(roles) {
2438
4261
  const h = {};
2439
4262
  for (let i = 0; i < roles.length - 1; i++) {
@@ -2453,6 +4276,19 @@ function routesToYaml(routes, defaultRole, indent) {
2453
4276
  return routes.map((r) => `${indent}- pattern: ${r}
2454
4277
  ${indent} requiredRole: ${defaultRole}`).join("\n");
2455
4278
  }
4279
+ function detectNextMajorVersion(cwd) {
4280
+ try {
4281
+ const pkgPath = (0, import_path7.join)(cwd, "package.json");
4282
+ if (!(0, import_fs7.existsSync)(pkgPath)) return null;
4283
+ const pkg = JSON.parse((0, import_fs7.readFileSync)(pkgPath, "utf8"));
4284
+ const nextVersion = pkg.dependencies?.next ?? pkg.devDependencies?.next;
4285
+ if (!nextVersion) return null;
4286
+ const match = nextVersion.match(/(\d+)/);
4287
+ return match ? parseInt(match[1], 10) : null;
4288
+ } catch {
4289
+ return null;
4290
+ }
4291
+ }
2456
4292
  function upsertAuthBlock(existing, authYaml) {
2457
4293
  const lines = existing.split("\n");
2458
4294
  let authStart = -1;
@@ -2465,14 +4301,99 @@ function upsertAuthBlock(existing, authYaml) {
2465
4301
  break;
2466
4302
  }
2467
4303
  }
2468
- if (authStart < 0) {
2469
- return existing.trimEnd() + "\n" + authYaml + "\n";
4304
+ if (authStart < 0) {
4305
+ return existing.trimEnd() + "\n" + authYaml + "\n";
4306
+ }
4307
+ const before = lines.slice(0, authStart);
4308
+ const after = lines.slice(authEnd);
4309
+ return [...before, ...authYaml.trimEnd().split("\n"), ...after.length ? after : []].join("\n");
4310
+ }
4311
+ function generateMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4312
+ const rbacBlock = ` rbac: {
4313
+ roles: ${JSON.stringify(roles)},
4314
+ defaultRole: '${defaultRole}',
4315
+ hierarchy: ${JSON.stringify(hierarchy, null, 4)},
4316
+ },`;
4317
+ const auditBlock = ` audit: {
4318
+ enabled: ${auditEnabled},
4319
+ retentionDays: ${auditRetentionDays},
4320
+ },`;
4321
+ const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
4322
+ const configBlock = `export const config = {
4323
+ matcher: ${JSON.stringify(protectedRoutes)},
4324
+ };`;
4325
+ if (method === "cac") {
4326
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
4327
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
4328
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
4329
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
4330
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth
4331
+ // \u26A0\uFE0F SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
4332
+ // DoD security officer review required before production deployment.
4333
+ // Verify: CA bundle completeness, EDIPI lookup endpoint, OCSP accessibility.
4334
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs/edge';
4335
+
4336
+ export const middleware = createProMiddleware({
4337
+ method: 'cac',
4338
+ cac: {
4339
+ caBundle: process.env.CAC_CA_BUNDLE ?? '${caBundle}',
4340
+ edipiLookup: '${edipiLookup}',
4341
+ ocspEndpoint: process.env.CAC_OCSP_ENDPOINT ?? '${ocspEndpoint}',
4342
+ certHeader: '${certHeader}',
4343
+ },
4344
+ ${rbacBlock}
4345
+ ${auditBlock}
4346
+ ${routesBlock}
4347
+ });
4348
+
4349
+ ${configBlock}
4350
+ `;
4351
+ }
4352
+ if (method === "oidc") {
4353
+ const scopes2 = params.oidcScopes ?? "openid profile email";
4354
+ const roleClaim = params.oidcRoleClaim ?? "roles";
4355
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
4356
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs/edge';
4357
+
4358
+ export const middleware = createProMiddleware({
4359
+ method: 'oidc',
4360
+ oidc: {
4361
+ discoveryUrl: process.env.OIDC_DISCOVERY_URL!,
4362
+ clientId: process.env.OIDC_CLIENT_ID!,
4363
+ clientSecret: process.env.OIDC_CLIENT_SECRET!,
4364
+ scopes: '${scopes2}',
4365
+ roleClaim: '${roleClaim}',
4366
+ },
4367
+ ${rbacBlock}
4368
+ ${auditBlock}
4369
+ ${routesBlock}
4370
+ });
4371
+
4372
+ ${configBlock}
4373
+ `;
2470
4374
  }
2471
- const before = lines.slice(0, authStart);
2472
- const after = lines.slice(authEnd);
2473
- return [...before, ...authYaml.trimEnd().split("\n"), ...after.length ? after : []].join("\n");
4375
+ const scopes = params.oauth2Scopes ?? "read write";
4376
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
4377
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs/edge';
4378
+
4379
+ export const middleware = createProMiddleware({
4380
+ method: 'oauth2',
4381
+ oauth2: {
4382
+ authorizationUrl: process.env.OAUTH2_AUTH_URL!,
4383
+ tokenUrl: process.env.OAUTH2_TOKEN_URL!,
4384
+ clientId: process.env.OAUTH2_CLIENT_ID!,
4385
+ clientSecret: process.env.OAUTH2_CLIENT_SECRET!,
4386
+ scopes: '${scopes}',
4387
+ },
4388
+ ${rbacBlock}
4389
+ ${auditBlock}
4390
+ ${routesBlock}
4391
+ });
4392
+
4393
+ ${configBlock}
4394
+ `;
2474
4395
  }
2475
- function generateMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4396
+ function generateProxyContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
2476
4397
  const rbacBlock = ` rbac: {
2477
4398
  roles: ${JSON.stringify(roles)},
2478
4399
  defaultRole: '${defaultRole}',
@@ -2491,13 +4412,13 @@ function generateMiddlewareContent(method, params, roles, defaultRole, hierarchy
2491
4412
  const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
2492
4413
  const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
2493
4414
  const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
2494
- return `// middleware.ts \u2014 generated by @stackwright-pro/auth
2495
- // \u26A0\uFE0F SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
4415
+ return `// proxy.ts \u2014 generated by @stackwright-pro/auth (Next.js >=16)
4416
+ // SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
2496
4417
  // DoD security officer review required before production deployment.
2497
4418
  // Verify: CA bundle completeness, EDIPI lookup endpoint, OCSP accessibility.
2498
- import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
4419
+ import { createProProxy } from '@stackwright-pro/auth-nextjs/edge';
2499
4420
 
2500
- export const middleware = createProMiddleware({
4421
+ export const proxy = createProProxy({
2501
4422
  method: 'cac',
2502
4423
  cac: {
2503
4424
  caBundle: process.env.CAC_CA_BUNDLE ?? '${caBundle}',
@@ -2516,10 +4437,10 @@ ${configBlock}
2516
4437
  if (method === "oidc") {
2517
4438
  const scopes2 = params.oidcScopes ?? "openid profile email";
2518
4439
  const roleClaim = params.oidcRoleClaim ?? "roles";
2519
- return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
2520
- import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
4440
+ return `// proxy.ts \u2014 generated by @stackwright-pro/auth (Next.js >=16)
4441
+ import { createProProxy } from '@stackwright-pro/auth-nextjs/edge';
2521
4442
 
2522
- export const middleware = createProMiddleware({
4443
+ export const proxy = createProProxy({
2523
4444
  method: 'oidc',
2524
4445
  oidc: {
2525
4446
  discoveryUrl: process.env.OIDC_DISCOVERY_URL!,
@@ -2537,10 +4458,10 @@ ${configBlock}
2537
4458
  `;
2538
4459
  }
2539
4460
  const scopes = params.oauth2Scopes ?? "read write";
2540
- return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
2541
- import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
4461
+ return `// proxy.ts \u2014 generated by @stackwright-pro/auth (Next.js >=16)
4462
+ import { createProProxy } from '@stackwright-pro/auth-nextjs/edge';
2542
4463
 
2543
- export const middleware = createProMiddleware({
4464
+ export const proxy = createProProxy({
2544
4465
  method: 'oauth2',
2545
4466
  oauth2: {
2546
4467
  authorizationUrl: process.env.OAUTH2_AUTH_URL!,
@@ -2583,7 +4504,7 @@ OAUTH2_CLIENT_ID=your-client-id
2583
4504
  OAUTH2_CLIENT_SECRET=your-client-secret
2584
4505
  `;
2585
4506
  }
2586
- function generateYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4507
+ function generateYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes, useProxy) {
2587
4508
  const rbacSection = ` rbac:
2588
4509
  roles:
2589
4510
  ${rolesToYaml(roles, " ")}
@@ -2606,7 +4527,7 @@ ${routesToYaml(protectedRoutes, " ", defaultRole)}`.replace(/\n\s+,/g, "");
2606
4527
  const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
2607
4528
  return `auth:
2608
4529
  method: cac
2609
- ${providerLine} middleware: ./middleware.ts
4530
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
2610
4531
  cac:
2611
4532
  caBundle: \${CAC_CA_BUNDLE}
2612
4533
  edipiLookup: ${edipiLookup}
@@ -2623,7 +4544,7 @@ ${auditSection}
2623
4544
  const roleClaim = params.oidcRoleClaim ?? "roles";
2624
4545
  return `auth:
2625
4546
  method: oidc
2626
- ${providerLine} middleware: ./middleware.ts
4547
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
2627
4548
  oidc:
2628
4549
  discoveryUrl: \${OIDC_DISCOVERY_URL}
2629
4550
  clientId: \${OIDC_CLIENT_ID}
@@ -2639,7 +4560,7 @@ ${auditSection}
2639
4560
  const scopes = params.oauth2Scopes ?? "read write";
2640
4561
  return `auth:
2641
4562
  method: oauth2
2642
- ${providerLine} middleware: ./middleware.ts
4563
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
2643
4564
  oauth2:
2644
4565
  authorizationUrl: \${OAUTH2_AUTH_URL}
2645
4566
  tokenUrl: \${OAUTH2_TOKEN_URL}
@@ -2652,10 +4573,321 @@ ${routeLines}
2652
4573
  ${auditSection}
2653
4574
  `;
2654
4575
  }
4576
+ function generateDevOnlyMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4577
+ const rbacBlock = ` rbac: {
4578
+ roles: ${JSON.stringify(roles)},
4579
+ defaultRole: '${defaultRole}',
4580
+ hierarchy: ${JSON.stringify(hierarchy, null, 4)},
4581
+ },`;
4582
+ const auditBlock = ` audit: {
4583
+ enabled: ${auditEnabled},
4584
+ retentionDays: ${auditRetentionDays},
4585
+ },`;
4586
+ const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
4587
+ const configBlock = `export const config = {
4588
+ matcher: ${JSON.stringify(protectedRoutes)},
4589
+ };`;
4590
+ const devHeader = [
4591
+ "// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs (dev-only mock)",
4592
+ "// DEV ONLY \u2014 uses mock authentication from lib/mock-auth.ts",
4593
+ "// Do NOT deploy to production.",
4594
+ "import { createProMiddleware } from '@stackwright-pro/auth-nextjs/edge';",
4595
+ "import { mockAuthProvider } from './lib/mock-auth';"
4596
+ ].join("\n");
4597
+ if (method === "cac") {
4598
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
4599
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
4600
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
4601
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
4602
+ return `${devHeader}
4603
+
4604
+ export const middleware = createProMiddleware({
4605
+ method: 'cac',
4606
+ cac: {
4607
+ caBundle: '${caBundle}',
4608
+ edipiLookup: '${edipiLookup}',
4609
+ ocspEndpoint: '${ocspEndpoint}',
4610
+ certHeader: '${certHeader}',
4611
+ provider: mockAuthProvider,
4612
+ },
4613
+ ${rbacBlock}
4614
+ ${auditBlock}
4615
+ ${routesBlock}
4616
+ });
4617
+
4618
+ ${configBlock}
4619
+ `;
4620
+ }
4621
+ if (method === "oidc") {
4622
+ const scopes2 = params.oidcScopes ?? "openid profile email";
4623
+ const roleClaim = params.oidcRoleClaim ?? "roles";
4624
+ return `${devHeader}
4625
+
4626
+ export const middleware = createProMiddleware({
4627
+ method: 'oidc',
4628
+ oidc: {
4629
+ discoveryUrl: 'https://dev-mock-oidc/.well-known/openid-configuration',
4630
+ clientId: 'dev-mock-client',
4631
+ clientSecret: 'dev-mock-secret',
4632
+ scopes: '${scopes2}',
4633
+ roleClaim: '${roleClaim}',
4634
+ provider: mockAuthProvider,
4635
+ },
4636
+ ${rbacBlock}
4637
+ ${auditBlock}
4638
+ ${routesBlock}
4639
+ });
4640
+
4641
+ ${configBlock}
4642
+ `;
4643
+ }
4644
+ const scopes = params.oauth2Scopes ?? "read write";
4645
+ return `${devHeader}
4646
+
4647
+ export const middleware = createProMiddleware({
4648
+ method: 'oauth2',
4649
+ oauth2: {
4650
+ authorizationUrl: 'https://dev-mock-oauth2/authorize',
4651
+ tokenUrl: 'https://dev-mock-oauth2/token',
4652
+ clientId: 'dev-mock-client',
4653
+ clientSecret: 'dev-mock-secret',
4654
+ scopes: '${scopes}',
4655
+ provider: mockAuthProvider,
4656
+ },
4657
+ ${rbacBlock}
4658
+ ${auditBlock}
4659
+ ${routesBlock}
4660
+ });
4661
+
4662
+ ${configBlock}
4663
+ `;
4664
+ }
4665
+ function generateDevOnlyProxyContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4666
+ const rbacBlock = ` rbac: {
4667
+ roles: ${JSON.stringify(roles)},
4668
+ defaultRole: '${defaultRole}',
4669
+ hierarchy: ${JSON.stringify(hierarchy, null, 4)},
4670
+ },`;
4671
+ const auditBlock = ` audit: {
4672
+ enabled: ${auditEnabled},
4673
+ retentionDays: ${auditRetentionDays},
4674
+ },`;
4675
+ const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
4676
+ const configBlock = `export const config = {
4677
+ matcher: ${JSON.stringify(protectedRoutes)},
4678
+ };`;
4679
+ const devHeader = [
4680
+ "// proxy.ts -- generated by @stackwright-pro/auth (Next.js >=16, dev-only mock)",
4681
+ "// DEV ONLY -- uses mock authentication from lib/mock-auth.ts",
4682
+ "// Do NOT deploy to production.",
4683
+ "import { createProProxy } from '@stackwright-pro/auth-nextjs/edge';",
4684
+ "import { mockAuthProvider } from './lib/mock-auth';"
4685
+ ].join("\n");
4686
+ if (method === "cac") {
4687
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
4688
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
4689
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
4690
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
4691
+ return `${devHeader}
4692
+
4693
+ export const proxy = createProProxy({
4694
+ method: 'cac',
4695
+ cac: {
4696
+ caBundle: '${caBundle}',
4697
+ edipiLookup: '${edipiLookup}',
4698
+ ocspEndpoint: '${ocspEndpoint}',
4699
+ certHeader: '${certHeader}',
4700
+ provider: mockAuthProvider,
4701
+ },
4702
+ ${rbacBlock}
4703
+ ${auditBlock}
4704
+ ${routesBlock}
4705
+ });
4706
+
4707
+ ${configBlock}
4708
+ `;
4709
+ }
4710
+ if (method === "oidc") {
4711
+ const scopes2 = params.oidcScopes ?? "openid profile email";
4712
+ const roleClaim = params.oidcRoleClaim ?? "roles";
4713
+ return `${devHeader}
4714
+
4715
+ export const proxy = createProProxy({
4716
+ method: 'oidc',
4717
+ oidc: {
4718
+ discoveryUrl: 'https://dev-mock-oidc/.well-known/openid-configuration',
4719
+ clientId: 'dev-mock-client',
4720
+ clientSecret: 'dev-mock-secret',
4721
+ scopes: '${scopes2}',
4722
+ roleClaim: '${roleClaim}',
4723
+ provider: mockAuthProvider,
4724
+ },
4725
+ ${rbacBlock}
4726
+ ${auditBlock}
4727
+ ${routesBlock}
4728
+ });
4729
+
4730
+ ${configBlock}
4731
+ `;
4732
+ }
4733
+ const scopes = params.oauth2Scopes ?? "read write";
4734
+ return `${devHeader}
4735
+
4736
+ export const proxy = createProProxy({
4737
+ method: 'oauth2',
4738
+ oauth2: {
4739
+ authorizationUrl: 'https://dev-mock-oauth2/authorize',
4740
+ tokenUrl: 'https://dev-mock-oauth2/token',
4741
+ clientId: 'dev-mock-client',
4742
+ clientSecret: 'dev-mock-secret',
4743
+ scopes: '${scopes}',
4744
+ provider: mockAuthProvider,
4745
+ },
4746
+ ${rbacBlock}
4747
+ ${auditBlock}
4748
+ ${routesBlock}
4749
+ });
4750
+
4751
+ ${configBlock}
4752
+ `;
4753
+ }
4754
+ function generateDevOnlyYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes, useProxy) {
4755
+ const rbacSection = ` rbac:
4756
+ roles:
4757
+ ${rolesToYaml(roles, " ")}
4758
+ defaultRole: ${defaultRole}
4759
+ hierarchy:
4760
+ ${hierarchyToYaml(hierarchy, " ")}`;
4761
+ const auditSection = ` audit:
4762
+ enabled: ${auditEnabled}
4763
+ retentionDays: ${auditRetentionDays}`;
4764
+ const routeLines = protectedRoutes.map((r) => ` - pattern: ${r}
4765
+ requiredRole: ${defaultRole}`).join("\n");
4766
+ const providerLine = params.provider ? ` provider: ${params.provider}
4767
+ ` : "";
4768
+ if (method === "cac") {
4769
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
4770
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
4771
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
4772
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
4773
+ return `auth:
4774
+ method: cac
4775
+ devOnly: true
4776
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
4777
+ cac:
4778
+ caBundle: ${caBundle}
4779
+ edipiLookup: ${edipiLookup}
4780
+ ocspEndpoint: ${ocspEndpoint}
4781
+ certHeader: ${certHeader}
4782
+ ${rbacSection}
4783
+ protectedRoutes:
4784
+ ${routeLines}
4785
+ ${auditSection}
4786
+ `;
4787
+ }
4788
+ if (method === "oidc") {
4789
+ const scopes2 = params.oidcScopes ?? "openid profile email";
4790
+ const roleClaim = params.oidcRoleClaim ?? "roles";
4791
+ return `auth:
4792
+ method: oidc
4793
+ devOnly: true
4794
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
4795
+ oidc:
4796
+ discoveryUrl: https://dev-mock-oidc/.well-known/openid-configuration
4797
+ clientId: dev-mock-client
4798
+ clientSecret: dev-mock-secret
4799
+ scopes: ${scopes2}
4800
+ roleClaim: ${roleClaim}
4801
+ ${rbacSection}
4802
+ protectedRoutes:
4803
+ ${routeLines}
4804
+ ${auditSection}
4805
+ `;
4806
+ }
4807
+ const scopes = params.oauth2Scopes ?? "read write";
4808
+ return `auth:
4809
+ method: oauth2
4810
+ devOnly: true
4811
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
4812
+ oauth2:
4813
+ authorizationUrl: https://dev-mock-oauth2/authorize
4814
+ tokenUrl: https://dev-mock-oauth2/token
4815
+ clientId: dev-mock-client
4816
+ clientSecret: dev-mock-secret
4817
+ scopes: ${scopes}
4818
+ ${rbacSection}
4819
+ protectedRoutes:
4820
+ ${routeLines}
4821
+ ${auditSection}
4822
+ `;
4823
+ }
4824
+ function deriveDevKey(roleName) {
4825
+ const segment = roleName.split("_")[0];
4826
+ return (segment ?? roleName).toLowerCase();
4827
+ }
4828
+ function generateMockAuthContent(roles, mockUsers) {
4829
+ const entries = [];
4830
+ const scriptLines = [];
4831
+ for (let i = 0; i < roles.length; i++) {
4832
+ const role = roles[i];
4833
+ const devKey = deriveDevKey(role);
4834
+ const persona = mockUsers?.[i];
4835
+ const name = persona?.name ?? `Dev ${role}`;
4836
+ const email = persona?.email ?? `dev-${devKey}@example.mil`;
4837
+ const edipi = String(i + 1).padStart(10, "0");
4838
+ entries.push(` ${devKey}: {
4839
+ id: 'mock-${devKey}-${String(i + 1).padStart(3, "0")}',
4840
+ name: '${name}',
4841
+ email: '${email}',
4842
+ roles: ['${role}'],
4843
+ edipi: '${edipi}',
4844
+ }`);
4845
+ scriptLines.push(` * pnpm dev:${devKey} \u2014 ${name}`);
4846
+ }
4847
+ return `/**
4848
+ * Mock authentication for development mode.
4849
+ *
4850
+ * DEV_ONLY_MODE \u2014 no real auth provider. Select a persona via MOCK_USER env var
4851
+ * or use the convenience scripts in package.json:
4852
+ ${scriptLines.join("\n")}
4853
+ */
4854
+
4855
+ export const MOCK_USERS = {
4856
+ ${entries.join(",\n")}
4857
+ } as const;
4858
+
4859
+ export type MockRole = keyof typeof MOCK_USERS;
4860
+
4861
+ export function getMockUser(role?: string) {
4862
+ const key = (role ?? process.env.MOCK_USER) as MockRole | undefined;
4863
+ if (!key) return null;
4864
+ return MOCK_USERS[key] ?? null;
4865
+ }
4866
+
4867
+ export function mockAuthProvider() {
4868
+ return getMockUser();
4869
+ }
4870
+ `;
4871
+ }
4872
+ function updatePackageJsonScripts(existingJson, roles, mockUsers) {
4873
+ const pkg = JSON.parse(existingJson);
4874
+ const scripts = pkg.scripts ?? {};
4875
+ delete scripts["dev:admin"];
4876
+ delete scripts["dev:analyst"];
4877
+ delete scripts["dev:viewer"];
4878
+ for (let i = 0; i < roles.length; i++) {
4879
+ const devKey = deriveDevKey(roles[i]);
4880
+ scripts[`dev:${devKey}`] = `MOCK_USER=${devKey} next dev`;
4881
+ }
4882
+ pkg.scripts = scripts;
4883
+ return JSON.stringify(pkg, null, 2) + "\n";
4884
+ }
2655
4885
  async function configureAuthHandler(params, cwd) {
2656
4886
  const {
2657
4887
  method,
2658
4888
  provider,
4889
+ devOnly = false,
4890
+ mockUsers,
2659
4891
  rbacRoles = ["SUPER_ADMIN", "ADMIN", "ANALYST"],
2660
4892
  auditEnabled = true,
2661
4893
  auditRetentionDays = 90,
@@ -2664,6 +4896,9 @@ async function configureAuthHandler(params, cwd) {
2664
4896
  const roles = rbacRoles;
2665
4897
  const defaultRole = params.rbacDefaultRole ?? roles[roles.length - 1];
2666
4898
  const hierarchy = buildHierarchy(roles);
4899
+ const detectedVersion = params.nextMajorVersion ?? detectNextMajorVersion(cwd);
4900
+ const useProxy = (detectedVersion ?? 0) >= 16;
4901
+ const conventionFile = useProxy ? "proxy.ts" : "middleware.ts";
2667
4902
  if (method === "none") {
2668
4903
  return {
2669
4904
  content: [
@@ -2685,7 +4920,34 @@ async function configureAuthHandler(params, cwd) {
2685
4920
  }
2686
4921
  const filesWritten = [];
2687
4922
  try {
2688
- const middlewareContent = generateMiddlewareContent(
4923
+ const authFileContent = devOnly ? useProxy ? generateDevOnlyProxyContent(
4924
+ method,
4925
+ params,
4926
+ roles,
4927
+ defaultRole,
4928
+ hierarchy,
4929
+ auditEnabled,
4930
+ auditRetentionDays,
4931
+ protectedRoutes
4932
+ ) : generateDevOnlyMiddlewareContent(
4933
+ method,
4934
+ params,
4935
+ roles,
4936
+ defaultRole,
4937
+ hierarchy,
4938
+ auditEnabled,
4939
+ auditRetentionDays,
4940
+ protectedRoutes
4941
+ ) : useProxy ? generateProxyContent(
4942
+ method,
4943
+ params,
4944
+ roles,
4945
+ defaultRole,
4946
+ hierarchy,
4947
+ auditEnabled,
4948
+ auditRetentionDays,
4949
+ protectedRoutes
4950
+ ) : generateMiddlewareContent(
2689
4951
  method,
2690
4952
  params,
2691
4953
  roles,
@@ -2695,44 +4957,95 @@ async function configureAuthHandler(params, cwd) {
2695
4957
  auditRetentionDays,
2696
4958
  protectedRoutes
2697
4959
  );
2698
- (0, import_fs6.writeFileSync)((0, import_path6.join)(cwd, "middleware.ts"), middlewareContent, "utf8");
2699
- filesWritten.push("middleware.ts");
4960
+ (0, import_fs7.writeFileSync)((0, import_path7.join)(cwd, conventionFile), authFileContent, "utf8");
4961
+ filesWritten.push(conventionFile);
2700
4962
  } catch (err) {
2701
4963
  const msg = err instanceof Error ? err.message : String(err);
2702
4964
  return {
2703
4965
  content: [
2704
4966
  {
2705
4967
  type: "text",
2706
- text: JSON.stringify({ success: false, error: `Failed writing middleware.ts: ${msg}` })
4968
+ text: JSON.stringify({
4969
+ success: false,
4970
+ error: `Failed writing ${conventionFile}: ${msg}`
4971
+ })
2707
4972
  }
2708
4973
  ],
2709
4974
  isError: true
2710
4975
  };
2711
4976
  }
2712
- try {
2713
- 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");
2718
- } else {
2719
- (0, import_fs6.writeFileSync)(envPath, envBlock, "utf8");
4977
+ if (!devOnly) {
4978
+ try {
4979
+ const envBlock = generateEnvBlock(method, params);
4980
+ const envPath = (0, import_path7.join)(cwd, ".env.example");
4981
+ if ((0, import_fs7.existsSync)(envPath)) {
4982
+ const existing = (0, import_fs7.readFileSync)(envPath, "utf8");
4983
+ (0, import_fs7.writeFileSync)(envPath, existing.trimEnd() + "\n\n" + envBlock, "utf8");
4984
+ } else {
4985
+ (0, import_fs7.writeFileSync)(envPath, envBlock, "utf8");
4986
+ }
4987
+ filesWritten.push(".env.example");
4988
+ } catch (err) {
4989
+ const msg = err instanceof Error ? err.message : String(err);
4990
+ return {
4991
+ content: [
4992
+ {
4993
+ type: "text",
4994
+ text: JSON.stringify({ success: false, error: `Failed writing .env.example: ${msg}` })
4995
+ }
4996
+ ],
4997
+ isError: true
4998
+ };
4999
+ }
5000
+ }
5001
+ if (devOnly) {
5002
+ try {
5003
+ const mockAuthDir = (0, import_path7.join)(cwd, "lib");
5004
+ (0, import_fs7.mkdirSync)(mockAuthDir, { recursive: true });
5005
+ const mockAuthContent = generateMockAuthContent(roles, mockUsers);
5006
+ (0, import_fs7.writeFileSync)((0, import_path7.join)(mockAuthDir, "mock-auth.ts"), mockAuthContent, "utf8");
5007
+ filesWritten.push("lib/mock-auth.ts");
5008
+ } catch (err) {
5009
+ const msg = err instanceof Error ? err.message : String(err);
5010
+ return {
5011
+ content: [
5012
+ {
5013
+ type: "text",
5014
+ text: JSON.stringify({
5015
+ success: false,
5016
+ error: `Failed writing lib/mock-auth.ts: ${msg}`
5017
+ })
5018
+ }
5019
+ ],
5020
+ isError: true
5021
+ };
5022
+ }
5023
+ try {
5024
+ const pkgPath = (0, import_path7.join)(cwd, "package.json");
5025
+ if ((0, import_fs7.existsSync)(pkgPath)) {
5026
+ const existingPkg = (0, import_fs7.readFileSync)(pkgPath, "utf8");
5027
+ const updatedPkg = updatePackageJsonScripts(existingPkg, roles, mockUsers);
5028
+ (0, import_fs7.writeFileSync)(pkgPath, updatedPkg, "utf8");
5029
+ filesWritten.push("package.json");
5030
+ }
5031
+ } catch (err) {
5032
+ const msg = err instanceof Error ? err.message : String(err);
5033
+ return {
5034
+ content: [
5035
+ {
5036
+ type: "text",
5037
+ text: JSON.stringify({
5038
+ success: false,
5039
+ error: `Failed updating package.json: ${msg}`
5040
+ })
5041
+ }
5042
+ ],
5043
+ isError: true
5044
+ };
2720
5045
  }
2721
- filesWritten.push(".env.example");
2722
- } catch (err) {
2723
- const msg = err instanceof Error ? err.message : String(err);
2724
- return {
2725
- content: [
2726
- {
2727
- type: "text",
2728
- text: JSON.stringify({ success: false, error: `Failed writing .env.example: ${msg}` })
2729
- }
2730
- ],
2731
- isError: true
2732
- };
2733
5046
  }
2734
5047
  try {
2735
- const authYaml = generateYamlBlock(
5048
+ const authYaml = devOnly ? generateDevOnlyYamlBlock(
2736
5049
  method,
2737
5050
  params,
2738
5051
  roles,
@@ -2740,14 +5053,25 @@ async function configureAuthHandler(params, cwd) {
2740
5053
  hierarchy,
2741
5054
  auditEnabled,
2742
5055
  auditRetentionDays,
2743
- protectedRoutes
5056
+ protectedRoutes,
5057
+ useProxy
5058
+ ) : generateYamlBlock(
5059
+ method,
5060
+ params,
5061
+ roles,
5062
+ defaultRole,
5063
+ hierarchy,
5064
+ auditEnabled,
5065
+ auditRetentionDays,
5066
+ protectedRoutes,
5067
+ useProxy
2744
5068
  );
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");
5069
+ const ymlPath = (0, import_path7.join)(cwd, "stackwright.yml");
5070
+ if (!(0, import_fs7.existsSync)(ymlPath)) {
5071
+ (0, import_fs7.writeFileSync)(ymlPath, authYaml, "utf8");
2748
5072
  } else {
2749
- const existing = (0, import_fs6.readFileSync)(ymlPath, "utf8");
2750
- (0, import_fs6.writeFileSync)(ymlPath, upsertAuthBlock(existing, authYaml), "utf8");
5073
+ const existing = (0, import_fs7.readFileSync)(ymlPath, "utf8");
5074
+ (0, import_fs7.writeFileSync)(ymlPath, upsertAuthBlock(existing, authYaml), "utf8");
2751
5075
  }
2752
5076
  filesWritten.push("stackwright.yml");
2753
5077
  } catch (err) {
@@ -2775,7 +5099,23 @@ async function configureAuthHandler(params, cwd) {
2775
5099
  rbacDefaultRole: defaultRole,
2776
5100
  protectedRoutesCount: protectedRoutes.length,
2777
5101
  filesWritten,
2778
- securityWarning
5102
+ convention: useProxy ? "proxy" : "middleware",
5103
+ nextMajorVersion: params.nextMajorVersion ?? null,
5104
+ securityWarning,
5105
+ ...devOnly ? {
5106
+ devScripts: {
5107
+ written: filesWritten.includes("package.json"),
5108
+ scripts: filesWritten.includes("package.json") ? Object.fromEntries(
5109
+ roles.map((r) => {
5110
+ const k = deriveDevKey(r);
5111
+ return [`dev:${k}`, `MOCK_USER=${k} next dev`];
5112
+ })
5113
+ ) : {},
5114
+ ...filesWritten.includes("package.json") ? {} : {
5115
+ warning: "package.json not found \u2014 dev scripts were not written. Run the auth phase again after scaffolding creates package.json."
5116
+ }
5117
+ }
5118
+ } : {}
2779
5119
  })
2780
5120
  }
2781
5121
  ]
@@ -2786,35 +5126,38 @@ function registerAuthTools(server2) {
2786
5126
  "stackwright_pro_configure_auth",
2787
5127
  "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
5128
  {
2789
- method: import_zod11.z.enum(["cac", "oidc", "oauth2", "none"]),
2790
- provider: import_zod11.z.enum(["azure-ad", "okta", "ping", "cognito", "custom"]).optional(),
5129
+ method: import_zod15.z.enum(["cac", "oidc", "oauth2", "none"]),
5130
+ provider: import_zod15.z.enum(["azure-ad", "okta", "ping", "cognito", "custom"]).optional(),
2791
5131
  // 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(),
5132
+ cacCaBundle: import_zod15.z.string().optional(),
5133
+ cacEdipiLookup: import_zod15.z.string().optional(),
5134
+ cacOcspEndpoint: import_zod15.z.string().optional(),
5135
+ cacCertHeader: import_zod15.z.string().optional(),
2796
5136
  // 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(),
5137
+ oidcDiscoveryUrl: import_zod15.z.string().optional(),
5138
+ oidcClientId: import_zod15.z.string().optional(),
5139
+ oidcClientSecret: import_zod15.z.string().optional(),
5140
+ oidcScopes: import_zod15.z.string().optional(),
5141
+ oidcRoleClaim: import_zod15.z.string().optional(),
2802
5142
  // 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(),
5143
+ oauth2AuthUrl: import_zod15.z.string().optional(),
5144
+ oauth2TokenUrl: import_zod15.z.string().optional(),
5145
+ oauth2ClientId: import_zod15.z.string().optional(),
5146
+ oauth2ClientSecret: import_zod15.z.string().optional(),
5147
+ oauth2Scopes: import_zod15.z.string().optional(),
2808
5148
  // RBAC
2809
- rbacRoles: import_zod11.z.array(import_zod11.z.string()).optional(),
2810
- rbacDefaultRole: import_zod11.z.string().optional(),
5149
+ rbacRoles: jsonCoerce(import_zod15.z.array(import_zod15.z.string()).optional()),
5150
+ rbacDefaultRole: import_zod15.z.string().optional(),
2811
5151
  // Audit
2812
- auditEnabled: import_zod11.z.boolean().optional(),
2813
- auditRetentionDays: import_zod11.z.number().int().positive().optional(),
5152
+ auditEnabled: boolCoerce(import_zod15.z.boolean().optional()),
5153
+ auditRetentionDays: numCoerce(import_zod15.z.number().int().positive().optional()),
2814
5154
  // Routes
2815
- protectedRoutes: import_zod11.z.array(import_zod11.z.string()).optional(),
5155
+ protectedRoutes: jsonCoerce(import_zod15.z.array(import_zod15.z.string()).optional()),
2816
5156
  // Injection for tests
2817
- _cwd: import_zod11.z.string().optional()
5157
+ _cwd: import_zod15.z.string().optional(),
5158
+ devOnly: boolCoerce(import_zod15.z.boolean().optional()),
5159
+ mockUsers: jsonCoerce(import_zod15.z.array(import_zod15.z.object({ name: import_zod15.z.string(), email: import_zod15.z.string() })).optional()),
5160
+ nextMajorVersion: numCoerce(import_zod15.z.number().int().positive().optional())
2818
5161
  },
2819
5162
  async (params) => {
2820
5163
  const cwd = params._cwd ?? process.cwd();
@@ -2824,45 +5167,65 @@ function registerAuthTools(server2) {
2824
5167
  }
2825
5168
 
2826
5169
  // src/integrity.ts
2827
- var import_crypto2 = require("crypto");
2828
- var import_fs7 = require("fs");
2829
- var import_path7 = require("path");
5170
+ var import_crypto4 = require("crypto");
5171
+ var import_fs8 = require("fs");
5172
+ var import_path8 = require("path");
2830
5173
  var _checksums = /* @__PURE__ */ new Map([
2831
5174
  [
2832
5175
  "stackwright-pro-api-otter.json",
2833
- "f1cc9edf2dd1df3ebcea1d0ab33d17a358faaf8aa97ee232cd7994042f2eac0d"
5176
+ "1610b34c2bfd89aa18ef62fe052fe5aaba21cb2aa9c5d58a4fff06af2a1f0e6e"
2834
5177
  ],
2835
5178
  [
2836
5179
  "stackwright-pro-auth-otter.json",
2837
- "a19e06c503209a8a35fe321d30448623545b36b48c47a6ec064d13406ad1f725"
5180
+ "5a876d3614e62a7817e69bbe7fe7cc6976035ccaa0e7c29fb1e1a32caf8cea93"
2838
5181
  ],
2839
5182
  [
2840
5183
  "stackwright-pro-dashboard-otter.json",
2841
- "b3cb3d7554f2e9eed3b57d5e0e3bf85d6ba5b4db5d3af5514391cf0575fcc001"
5184
+ "9550e565fb467d7956cf6b50e7b30a481e6e4b26d609dfe1f0d8f991fc6681de"
2842
5185
  ],
2843
5186
  [
2844
5187
  "stackwright-pro-data-otter.json",
2845
- "bfacb87ae82867472a75982215554336a105a658d6cd3dd2c8b819fa1e11d7ac"
5188
+ "5cd8caca50bfcc00ebaf1f9a83158e5580e0e51d25495244f8465d9c20f31e17"
2846
5189
  ],
2847
5190
  [
2848
5191
  "stackwright-pro-designer-otter.json",
2849
- "c58fa7c7ead9e6398074e1c7ce3f31a8ef4eb3679f5fa18cc03cae3a87878c88"
5192
+ "d44b307299c2b65568a708920b819eec7d3b5fe1191ace24b166cbfb2d6e5209"
5193
+ ],
5194
+ [
5195
+ "stackwright-pro-domain-expert-otter.json",
5196
+ "dc060aacdf67ee5758921c72225aa669a76cb962f0f8eedf1741f58f18e870d3"
2850
5197
  ],
2851
5198
  [
2852
5199
  "stackwright-pro-foreman-otter.json",
2853
- "84e9a5d427f0fcdbe92b53ebd956806c88c094bca4cdf11aaa0db023f0a00c08"
5200
+ "ab3d821d9217ccbe112d68ce25798bfe637aef15814168037caa2a98994e8d2d"
5201
+ ],
5202
+ [
5203
+ "stackwright-pro-geo-otter.json",
5204
+ "3c9fc96e79d9ac22be8a293cf3ec904c4ed033842864107515aacdf71285791c"
2854
5205
  ],
2855
5206
  [
2856
5207
  "stackwright-pro-page-otter.json",
2857
- "65bec3a3a0dda6b7591bba2de9399f1e3a4fb99cfe1075342f4f4be98d917b67"
5208
+ "0057ea97f7c2e33a8673140f59a0237eb627d82c676af3fae4faa31033598e03"
5209
+ ],
5210
+ [
5211
+ "stackwright-pro-polish-otter.json",
5212
+ "1e534dfbc5644a5efbc566d77b512929760715365d54ce030da177a535c23ea6"
5213
+ ],
5214
+ [
5215
+ "stackwright-pro-scaffold-otter.json",
5216
+ "2ed0adb316aaecb849153d44f52b177de539f21d4a7ce5ae4cc1c3c7470e15d4"
2858
5217
  ],
2859
5218
  [
2860
5219
  "stackwright-pro-theme-otter.json",
2861
- "64ffaeeceacd739922788a1d074f6feaffc3f91d09706c2c104f0c0281677732"
5220
+ "730bc16b24b4612552389fe9de662f233044bcbf5ef1e0f27f2cc1e1af4c989f"
2862
5221
  ],
2863
5222
  [
2864
5223
  "stackwright-pro-workflow-otter.json",
2865
- "0eec9d6a731678cf547c2a7b0b6fc338ca143c35501365a1e4e5dd2779dd5510"
5224
+ "8ece2a1f1ec30163600b5ce8b666c915ab0d00a1fa70c38ed58d1bb20cbd9979"
5225
+ ],
5226
+ [
5227
+ "stackwright-services-otter.json",
5228
+ "2a36a07eaf34b59a2dab7059f3748a5742ff1f6b80b4bd6a739c59cf114703d6"
2866
5229
  ]
2867
5230
  ]);
2868
5231
  Object.freeze(_checksums);
@@ -2877,21 +5240,21 @@ for (const [name, digest] of CANONICAL_CHECKSUMS) {
2877
5240
  }
2878
5241
  var MAX_OTTER_BYTES = 1 * 1024 * 1024;
2879
5242
  function computeSha256(data) {
2880
- return (0, import_crypto2.createHash)("sha256").update(data).digest("hex");
5243
+ return (0, import_crypto4.createHash)("sha256").update(data).digest("hex");
2881
5244
  }
2882
5245
  function safeEqual(a, b) {
2883
5246
  if (a.length !== b.length) return false;
2884
- return (0, import_crypto2.timingSafeEqual)(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
5247
+ return (0, import_crypto4.timingSafeEqual)(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
2885
5248
  }
2886
5249
  function verifyOtterFile(filePath) {
2887
- const filename = (0, import_path7.basename)(filePath);
5250
+ const filename = (0, import_path8.basename)(filePath);
2888
5251
  const expected = CANONICAL_CHECKSUMS.get(filename);
2889
5252
  if (expected === void 0) {
2890
5253
  return { verified: false, filename, error: `Unknown otter file: not in canonical set` };
2891
5254
  }
2892
5255
  let stat;
2893
5256
  try {
2894
- stat = (0, import_fs7.lstatSync)(filePath);
5257
+ stat = (0, import_fs8.lstatSync)(filePath);
2895
5258
  } catch (err) {
2896
5259
  const msg = err instanceof Error ? err.message : String(err);
2897
5260
  return { verified: false, filename, error: `Cannot stat file: ${msg}` };
@@ -2909,7 +5272,7 @@ function verifyOtterFile(filePath) {
2909
5272
  }
2910
5273
  let raw;
2911
5274
  try {
2912
- raw = (0, import_fs7.readFileSync)(filePath);
5275
+ raw = (0, import_fs8.readFileSync)(filePath);
2913
5276
  } catch (err) {
2914
5277
  const msg = err instanceof Error ? err.message : String(err);
2915
5278
  return { verified: false, filename, error: `Cannot read file: ${msg}` };
@@ -2942,12 +5305,24 @@ function verifyOtterFile(filePath) {
2942
5305
  return { verified: true, filename };
2943
5306
  }
2944
5307
  function verifyAllOtters(otterDir) {
5308
+ if (/(?:^|[/\\])\.\.(?:[/\\]|$)/.test(otterDir) || otterDir.includes("..")) {
5309
+ return {
5310
+ verified: [],
5311
+ failed: [
5312
+ {
5313
+ filename: "<directory>",
5314
+ error: `Security: path traversal sequence detected in otter directory parameter`
5315
+ }
5316
+ ],
5317
+ unknown: []
5318
+ };
5319
+ }
2945
5320
  const verified = [];
2946
5321
  const failed = [];
2947
5322
  const unknown = [];
2948
5323
  let entries;
2949
5324
  try {
2950
- entries = (0, import_fs7.readdirSync)(otterDir);
5325
+ entries = (0, import_fs8.readdirSync)(otterDir);
2951
5326
  } catch (err) {
2952
5327
  const msg = err instanceof Error ? err.message : String(err);
2953
5328
  return {
@@ -2958,9 +5333,9 @@ function verifyAllOtters(otterDir) {
2958
5333
  }
2959
5334
  const otterFiles = entries.filter((f) => f.endsWith("-otter.json"));
2960
5335
  for (const filename of otterFiles) {
2961
- const filePath = (0, import_path7.join)(otterDir, filename);
5336
+ const filePath = (0, import_path8.join)(otterDir, filename);
2962
5337
  try {
2963
- if ((0, import_fs7.lstatSync)(filePath).isSymbolicLink()) {
5338
+ if ((0, import_fs8.lstatSync)(filePath).isSymbolicLink()) {
2964
5339
  failed.push({ filename, error: "Skipped: symlink" });
2965
5340
  continue;
2966
5341
  }
@@ -2986,15 +5361,30 @@ var DEFAULT_SEARCH_PATHS = ["node_modules/@stackwright-pro/otters/src/", "packag
2986
5361
  function resolveOtterDir() {
2987
5362
  const cwd = process.cwd();
2988
5363
  for (const relative of DEFAULT_SEARCH_PATHS) {
2989
- const candidate = (0, import_path7.join)(cwd, relative);
5364
+ const candidate = (0, import_path8.join)(cwd, relative);
2990
5365
  try {
2991
- (0, import_fs7.lstatSync)(candidate);
5366
+ (0, import_fs8.lstatSync)(candidate);
2992
5367
  return candidate;
2993
5368
  } catch {
2994
5369
  }
2995
5370
  }
2996
5371
  return null;
2997
5372
  }
5373
+ function emitIntegrityAuditEvent(params) {
5374
+ const record = JSON.stringify({
5375
+ level: "AUDIT",
5376
+ event: "INTEGRITY_FAIL",
5377
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5378
+ source: "stackwright_pro_verify_otter_integrity",
5379
+ otterDir: params.otterDir,
5380
+ failedCount: params.failed.length,
5381
+ unknownCount: params.unknown.length,
5382
+ failures: params.failed,
5383
+ unknown: params.unknown
5384
+ });
5385
+ process.stderr.write(`INTEGRITY_FAIL ${record}
5386
+ `);
5387
+ }
2998
5388
  function registerIntegrityTools(server2) {
2999
5389
  server2.tool(
3000
5390
  "stackwright_pro_verify_otter_integrity",
@@ -3018,6 +5408,13 @@ function registerIntegrityTools(server2) {
3018
5408
  }
3019
5409
  const result = verifyAllOtters(resolved);
3020
5410
  const allGood = result.failed.length === 0 && result.unknown.length === 0;
5411
+ if (!allGood) {
5412
+ emitIntegrityAuditEvent({
5413
+ otterDir: resolved,
5414
+ failed: result.failed,
5415
+ unknown: result.unknown
5416
+ });
5417
+ }
3021
5418
  return {
3022
5419
  content: [
3023
5420
  {
@@ -3030,7 +5427,10 @@ function registerIntegrityTools(server2) {
3030
5427
  unknownCount: result.unknown.length,
3031
5428
  verified: result.verified,
3032
5429
  failed: result.failed,
3033
- unknown: result.unknown
5430
+ unknown: result.unknown,
5431
+ ...allGood ? {} : {
5432
+ error: "INTEGRITY CHECK FAILED: SHA-256 mismatch detected in otter agent definitions. Do not proceed \u2014 otter files may have been tampered with."
5433
+ }
3034
5434
  })
3035
5435
  }
3036
5436
  ],
@@ -3041,14 +5441,14 @@ function registerIntegrityTools(server2) {
3041
5441
  }
3042
5442
 
3043
5443
  // src/tools/domain.ts
3044
- var import_zod12 = require("zod");
3045
- var import_fs8 = require("fs");
3046
- var import_path8 = require("path");
5444
+ var import_zod16 = require("zod");
5445
+ var import_fs9 = require("fs");
5446
+ var import_path9 = require("path");
3047
5447
  function handleListCollections(input) {
3048
5448
  const cwd = input._cwd ?? process.cwd();
3049
5449
  const sources = [
3050
5450
  {
3051
- path: (0, import_path8.join)(cwd, ".stackwright", "artifacts", "data-config.json"),
5451
+ path: (0, import_path9.join)(cwd, ".stackwright", "artifacts", "data-config.json"),
3052
5452
  source: "data-config.json",
3053
5453
  parse: (raw) => {
3054
5454
  const parsed = JSON.parse(raw);
@@ -3059,15 +5459,15 @@ function handleListCollections(input) {
3059
5459
  }
3060
5460
  },
3061
5461
  {
3062
- path: (0, import_path8.join)(cwd, "stackwright.yml"),
5462
+ path: (0, import_path9.join)(cwd, "stackwright.yml"),
3063
5463
  source: "stackwright.yml",
3064
5464
  parse: extractCollectionsFromYaml
3065
5465
  }
3066
5466
  ];
3067
5467
  for (const { path: path3, source, parse } of sources) {
3068
- if (!(0, import_fs8.existsSync)(path3)) continue;
5468
+ if (!(0, import_fs9.existsSync)(path3)) continue;
3069
5469
  try {
3070
- const collections = parse((0, import_fs8.readFileSync)(path3, "utf8"));
5470
+ const collections = parse((0, import_fs9.readFileSync)(path3, "utf8"));
3071
5471
  return {
3072
5472
  text: JSON.stringify({ collections, source, collectionCount: collections.length }),
3073
5473
  isError: false
@@ -3218,8 +5618,8 @@ function handleValidateWorkflow(input) {
3218
5618
  if (input.workflow && Object.keys(input.workflow).length > 0) {
3219
5619
  raw = input.workflow;
3220
5620
  } else {
3221
- const artifactPath = (0, import_path8.join)(cwd, ".stackwright", "artifacts", "workflow-config.json");
3222
- if (!(0, import_fs8.existsSync)(artifactPath)) {
5621
+ const artifactPath = (0, import_path9.join)(cwd, ".stackwright", "artifacts", "workflow-config.json");
5622
+ if (!(0, import_fs9.existsSync)(artifactPath)) {
3223
5623
  return fail([
3224
5624
  {
3225
5625
  code: "NO_WORKFLOW",
@@ -3228,7 +5628,7 @@ function handleValidateWorkflow(input) {
3228
5628
  ]);
3229
5629
  }
3230
5630
  try {
3231
- raw = JSON.parse((0, import_fs8.readFileSync)(artifactPath, "utf8"));
5631
+ raw = JSON.parse((0, import_fs9.readFileSync)(artifactPath, "utf8"));
3232
5632
  } catch (err) {
3233
5633
  return fail([{ code: "INVALID_JSON", message: `Failed to parse workflow artifact: ${err}` }]);
3234
5634
  }
@@ -3427,7 +5827,7 @@ function registerDomainTools(server2) {
3427
5827
  "stackwright_pro_resolve_data_strategy",
3428
5828
  "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
5829
  {
3430
- strategy: import_zod12.z.string().describe(
5830
+ strategy: import_zod16.z.string().describe(
3431
5831
  'The data-1 answer value: "pulse-fast", "isr-fast", "isr-standard", or "isr-slow"'
3432
5832
  )
3433
5833
  },
@@ -3437,7 +5837,7 @@ function registerDomainTools(server2) {
3437
5837
  "stackwright_pro_validate_workflow",
3438
5838
  "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
5839
  {
3440
- workflow: import_zod12.z.record(import_zod12.z.string(), import_zod12.z.unknown()).optional().describe(
5840
+ workflow: jsonCoerce(import_zod16.z.record(import_zod16.z.string(), import_zod16.z.unknown()).optional()).describe(
3441
5841
  "Parsed workflow object. If omitted, reads from .stackwright/artifacts/workflow-config.json"
3442
5842
  )
3443
5843
  },
@@ -3445,18 +5845,526 @@ function registerDomainTools(server2) {
3445
5845
  );
3446
5846
  }
3447
5847
 
5848
+ // src/tools/type-schemas.ts
5849
+ var import_zod17 = require("zod");
5850
+ function buildTypeSchemaSummary() {
5851
+ return {
5852
+ version: "1.0",
5853
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
5854
+ domains: {
5855
+ workflow: {
5856
+ description: "Workflow DSL \u2014 step definitions, auth blocks, field types, conditions",
5857
+ schemas: [
5858
+ "WorkflowFileSchema",
5859
+ "WorkflowDefinitionSchema",
5860
+ "WorkflowStepSchema",
5861
+ "WorkflowStepTypeSchema",
5862
+ "WorkflowFieldSchema",
5863
+ "WorkflowActionSchema",
5864
+ "WorkflowAuthSchema",
5865
+ "WorkflowThemeSchema",
5866
+ "TransitionConditionSchema",
5867
+ "PersistenceSchema"
5868
+ ],
5869
+ otter: "stackwright-pro-workflow-otter",
5870
+ artifactKey: "workflowConfig"
5871
+ },
5872
+ auth: {
5873
+ description: "Authentication providers \u2014 PKI/CAC, OIDC, RBAC configuration",
5874
+ schemas: [
5875
+ "authConfigSchema",
5876
+ "pkiConfigSchema",
5877
+ "oidcConfigSchema",
5878
+ "rbacConfigSchema",
5879
+ "componentAuthSchema",
5880
+ "authUserSchema",
5881
+ "authSessionSchema"
5882
+ ],
5883
+ otter: "stackwright-pro-auth-otter",
5884
+ artifactKey: "authConfig"
5885
+ },
5886
+ openapi: {
5887
+ description: "OpenAPI spec integration \u2014 collection config, endpoint filters, actions",
5888
+ interfaces: [
5889
+ "OpenAPIConfig",
5890
+ "ActionConfig",
5891
+ "EndpointFilter",
5892
+ "ApprovedSpec",
5893
+ "PrebuildSecurityConfig",
5894
+ "SiteConfig",
5895
+ "ValidationResult"
5896
+ ],
5897
+ otter: "stackwright-pro-api-otter",
5898
+ artifactKey: "apiConfig"
5899
+ },
5900
+ pulse: {
5901
+ description: "Real-time data polling \u2014 source-agnostic polling options and states",
5902
+ interfaces: ["PulseOptions", "PulseMeta", "PulseState"],
5903
+ note: "React-bound types (PulseProps, PulseIndicatorProps) remain in @stackwright-pro/pulse"
5904
+ },
5905
+ enterprise: {
5906
+ description: "Enterprise collection access \u2014 multi-tenant provider extension",
5907
+ interfaces: [
5908
+ "EnterpriseCollectionProvider",
5909
+ "CollectionProvider",
5910
+ "CollectionEntry",
5911
+ "CollectionListOptions",
5912
+ "CollectionListResult",
5913
+ "TenantFilter",
5914
+ "Collection"
5915
+ ],
5916
+ note: "CollectionProvider, CollectionEntry, CollectionListOptions, and CollectionListResult are re-exported from @stackwright/types (^1.5.0). EnterpriseCollectionProvider, TenantFilter, and Collection are Pro-only extensions."
5917
+ }
5918
+ }
5919
+ };
5920
+ }
5921
+ function registerTypeSchemasTool(server2) {
5922
+ server2.tool(
5923
+ "stackwright_pro_get_type_schemas",
5924
+ "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.",
5925
+ {
5926
+ format: import_zod17.z.enum(["full", "domains-only"]).optional().default("full").describe("full = complete summary with all fields; domains-only = just domain names")
5927
+ },
5928
+ async ({ format }) => {
5929
+ const summary = buildTypeSchemaSummary();
5930
+ const output = format === "domains-only" ? Object.keys(summary.domains) : summary;
5931
+ return {
5932
+ content: [{ type: "text", text: JSON.stringify(output, null, 2) }]
5933
+ };
5934
+ }
5935
+ );
5936
+ }
5937
+
5938
+ // src/tools/scaffold-cleanup.ts
5939
+ var import_fs10 = require("fs");
5940
+ var import_path10 = require("path");
5941
+ var SCAFFOLD_FILES_TO_DELETE = [
5942
+ "content/posts/getting-started.yaml",
5943
+ "content/posts/hello-world.yaml"
5944
+ ];
5945
+ var SCAFFOLD_DIRS_TO_PRUNE = [
5946
+ "content/posts"
5947
+ // Don't prune 'content' — user may have other content directories
5948
+ ];
5949
+ var NOT_FOUND_PATH = "app/not-found.tsx";
5950
+ var FALLBACK_COLORS = {
5951
+ background: "#ffffff",
5952
+ foreground: "#171717",
5953
+ primary: "#525252",
5954
+ mutedForeground: "#737373"
5955
+ };
5956
+ function readThemeColors(cwd) {
5957
+ const tokenPath = (0, import_path10.join)(cwd, ".stackwright", "artifacts", "theme-tokens.json");
5958
+ if (!(0, import_fs10.existsSync)(tokenPath)) return { ...FALLBACK_COLORS };
5959
+ const stat = (0, import_fs10.lstatSync)(tokenPath);
5960
+ if (stat.isSymbolicLink()) return { ...FALLBACK_COLORS };
5961
+ try {
5962
+ const raw = JSON.parse((0, import_fs10.readFileSync)(tokenPath, "utf-8"));
5963
+ const css = raw?.cssVariables ?? {};
5964
+ const toHsl = (hslValue) => {
5965
+ if (!hslValue || typeof hslValue !== "string") return null;
5966
+ return `hsl(${hslValue})`;
5967
+ };
5968
+ return {
5969
+ background: toHsl(css["--background"]) ?? FALLBACK_COLORS.background,
5970
+ foreground: toHsl(css["--foreground"]) ?? FALLBACK_COLORS.foreground,
5971
+ primary: toHsl(css["--primary"]) ?? FALLBACK_COLORS.primary,
5972
+ mutedForeground: toHsl(css["--muted-foreground"]) ?? FALLBACK_COLORS.mutedForeground
5973
+ };
5974
+ } catch {
5975
+ return { ...FALLBACK_COLORS };
5976
+ }
5977
+ }
5978
+ function generateNotFoundPage(colors) {
5979
+ return `export default function NotFound() {
5980
+ return (
5981
+ <div
5982
+ style={{
5983
+ display: 'flex',
5984
+ flexDirection: 'column',
5985
+ alignItems: 'center',
5986
+ justifyContent: 'center',
5987
+ minHeight: '100vh',
5988
+ backgroundColor: '${colors.background}',
5989
+ color: '${colors.foreground}',
5990
+ fontFamily: 'system-ui, -apple-system, sans-serif',
5991
+ padding: '2rem',
5992
+ textAlign: 'center',
5993
+ }}
5994
+ >
5995
+ <h1 style={{ fontSize: '4rem', fontWeight: 700, margin: 0, color: '${colors.primary}' }}>
5996
+ 404
5997
+ </h1>
5998
+ <p style={{ fontSize: '1.25rem', color: '${colors.mutedForeground}', marginTop: '0.5rem' }}>
5999
+ Page not found
6000
+ </p>
6001
+ <a
6002
+ href="/"
6003
+ style={{
6004
+ marginTop: '2rem',
6005
+ padding: '0.75rem 1.5rem',
6006
+ backgroundColor: '${colors.primary}',
6007
+ color: '${colors.background}',
6008
+ borderRadius: '0.5rem',
6009
+ textDecoration: 'none',
6010
+ fontSize: '0.875rem',
6011
+ fontWeight: 500,
6012
+ }}
6013
+ >
6014
+ Go Home
6015
+ </a>
6016
+ </div>
6017
+ );
6018
+ }
6019
+ `;
6020
+ }
6021
+ function isSafePath(fullPath) {
6022
+ if (!(0, import_fs10.existsSync)(fullPath)) return true;
6023
+ const stat = (0, import_fs10.lstatSync)(fullPath);
6024
+ return !stat.isSymbolicLink();
6025
+ }
6026
+ function isDirEmpty(dirPath) {
6027
+ if (!(0, import_fs10.existsSync)(dirPath)) return false;
6028
+ const stat = (0, import_fs10.lstatSync)(dirPath);
6029
+ if (!stat.isDirectory()) return false;
6030
+ return (0, import_fs10.readdirSync)(dirPath).length === 0;
6031
+ }
6032
+ function handleCleanupScaffold(_cwd) {
6033
+ const cwd = _cwd ?? process.cwd();
6034
+ const result = {
6035
+ deleted: [],
6036
+ rewritten: [],
6037
+ skipped: [],
6038
+ errors: [],
6039
+ prunedDirs: []
6040
+ };
6041
+ for (const relPath of SCAFFOLD_FILES_TO_DELETE) {
6042
+ const fullPath = (0, import_path10.join)(cwd, relPath);
6043
+ if (!(0, import_fs10.existsSync)(fullPath)) {
6044
+ result.skipped.push(relPath);
6045
+ continue;
6046
+ }
6047
+ if (!isSafePath(fullPath)) {
6048
+ result.errors.push(`Refusing to delete symlink: ${relPath}`);
6049
+ continue;
6050
+ }
6051
+ try {
6052
+ (0, import_fs10.unlinkSync)(fullPath);
6053
+ result.deleted.push(relPath);
6054
+ } catch (err) {
6055
+ result.errors.push(`Failed to delete ${relPath}: ${String(err)}`);
6056
+ }
6057
+ }
6058
+ for (const relDir of SCAFFOLD_DIRS_TO_PRUNE) {
6059
+ const fullDir = (0, import_path10.join)(cwd, relDir);
6060
+ if (!(0, import_fs10.existsSync)(fullDir)) continue;
6061
+ if (!isSafePath(fullDir)) {
6062
+ result.errors.push(`Refusing to prune symlink directory: ${relDir}`);
6063
+ continue;
6064
+ }
6065
+ if (isDirEmpty(fullDir)) {
6066
+ try {
6067
+ (0, import_fs10.rmdirSync)(fullDir);
6068
+ result.prunedDirs.push(relDir);
6069
+ } catch (err) {
6070
+ result.errors.push(`Failed to prune directory ${relDir}: ${String(err)}`);
6071
+ }
6072
+ }
6073
+ }
6074
+ {
6075
+ const fullPath = (0, import_path10.join)(cwd, NOT_FOUND_PATH);
6076
+ if (!(0, import_fs10.existsSync)(fullPath)) {
6077
+ result.skipped.push(NOT_FOUND_PATH);
6078
+ } else if (!isSafePath(fullPath)) {
6079
+ result.errors.push(`Refusing to rewrite symlink: ${NOT_FOUND_PATH}`);
6080
+ } else {
6081
+ try {
6082
+ const colors = readThemeColors(cwd);
6083
+ const content = generateNotFoundPage(colors);
6084
+ const dir = (0, import_path10.dirname)(fullPath);
6085
+ (0, import_fs10.mkdirSync)(dir, { recursive: true });
6086
+ (0, import_fs10.writeFileSync)(fullPath, content, "utf-8");
6087
+ result.rewritten.push(NOT_FOUND_PATH);
6088
+ } catch (err) {
6089
+ result.errors.push(`Failed to rewrite ${NOT_FOUND_PATH}: ${String(err)}`);
6090
+ }
6091
+ }
6092
+ }
6093
+ return {
6094
+ text: JSON.stringify(result),
6095
+ isError: false
6096
+ };
6097
+ }
6098
+ function registerScaffoldCleanupTools(server2) {
6099
+ const DESC = "Deterministic scaffold remnant cleanup \u2014 removes stale OSS scaffold files after raft run.";
6100
+ server2.tool(
6101
+ "stackwright_pro_cleanup_scaffold",
6102
+ `Remove/rewrite stale scaffold files (blog posts, hardcoded not-found page) after the raft pipeline completes. ${DESC}`,
6103
+ {},
6104
+ async () => {
6105
+ const r = handleCleanupScaffold();
6106
+ return {
6107
+ content: [{ type: "text", text: r.text }],
6108
+ isError: r.isError
6109
+ };
6110
+ }
6111
+ );
6112
+ }
6113
+
6114
+ // src/tools/contrast.ts
6115
+ var import_zod18 = require("zod");
6116
+ function linearizeChannel(c255) {
6117
+ const c = c255 / 255;
6118
+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
6119
+ }
6120
+ function relativeLuminance(r, g, b) {
6121
+ return 0.2126 * linearizeChannel(r) + 0.7152 * linearizeChannel(g) + 0.0722 * linearizeChannel(b);
6122
+ }
6123
+ function contrastRatioFromLuminance(l1, l2) {
6124
+ const lighter = Math.max(l1, l2);
6125
+ const darker = Math.min(l1, l2);
6126
+ return (lighter + 0.05) / (darker + 0.05);
6127
+ }
6128
+ function parseHex(hex) {
6129
+ const clean = hex.replace("#", "").trim().toLowerCase();
6130
+ if (clean.length === 3) {
6131
+ const r = parseInt(clean.charAt(0) + clean.charAt(0), 16);
6132
+ const g = parseInt(clean.charAt(1) + clean.charAt(1), 16);
6133
+ const b = parseInt(clean.charAt(2) + clean.charAt(2), 16);
6134
+ if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
6135
+ return [r, g, b];
6136
+ }
6137
+ if (clean.length === 6) {
6138
+ const r = parseInt(clean.slice(0, 2), 16);
6139
+ const g = parseInt(clean.slice(2, 4), 16);
6140
+ const b = parseInt(clean.slice(4, 6), 16);
6141
+ if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
6142
+ return [r, g, b];
6143
+ }
6144
+ return null;
6145
+ }
6146
+ function hslToRgb(h, s, l) {
6147
+ const hn = h / 360;
6148
+ const sn = s / 100;
6149
+ const ln = l / 100;
6150
+ const hue2rgb = (p, q, t) => {
6151
+ let tt = t;
6152
+ if (tt < 0) tt += 1;
6153
+ if (tt > 1) tt -= 1;
6154
+ if (tt < 1 / 6) return p + (q - p) * 6 * tt;
6155
+ if (tt < 1 / 2) return q;
6156
+ if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6;
6157
+ return p;
6158
+ };
6159
+ let r, g, b;
6160
+ if (sn === 0) {
6161
+ r = g = b = ln;
6162
+ } else {
6163
+ const q = ln < 0.5 ? ln * (1 + sn) : ln + sn - ln * sn;
6164
+ const p = 2 * ln - q;
6165
+ r = hue2rgb(p, q, hn + 1 / 3);
6166
+ g = hue2rgb(p, q, hn);
6167
+ b = hue2rgb(p, q, hn - 1 / 3);
6168
+ }
6169
+ return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
6170
+ }
6171
+ function parseHsl(hsl) {
6172
+ let str = hsl.replace(/^hsl\s*\(\s*/i, "").replace(/\s*\)$/, "").trim();
6173
+ str = str.replace(/%/g, "");
6174
+ const parts = str.split(/[\s,]+/).filter(Boolean);
6175
+ if (parts.length !== 3) return null;
6176
+ const h = parseFloat(parts[0]);
6177
+ const s = parseFloat(parts[1]);
6178
+ const l = parseFloat(parts[2]);
6179
+ if (isNaN(h) || isNaN(s) || isNaN(l)) return null;
6180
+ return hslToRgb(h, s, l);
6181
+ }
6182
+ function parseColor(color) {
6183
+ const trimmed = color.trim();
6184
+ if (trimmed.startsWith("#")) return parseHex(trimmed);
6185
+ if (/^hsl\s*\(/i.test(trimmed)) return parseHsl(trimmed);
6186
+ if (/^\d[\d.]*[\s,]+\d[\d.]*%?[\s,]+\d[\d.]*%?$/.test(trimmed)) return parseHsl(trimmed);
6187
+ return null;
6188
+ }
6189
+ function rgbToHex(r, g, b) {
6190
+ return "#" + [r, g, b].map(
6191
+ (c) => Math.max(0, Math.min(255, Math.round(c))).toString(16).padStart(2, "0")
6192
+ ).join("");
6193
+ }
6194
+ function handleCheckContrast(fg, bg) {
6195
+ const fgRgb = parseColor(fg);
6196
+ const bgRgb = parseColor(bg);
6197
+ if (!fgRgb) throw new Error(`Cannot parse foreground color: "${fg}"`);
6198
+ if (!bgRgb) throw new Error(`Cannot parse background color: "${bg}"`);
6199
+ const fgL = relativeLuminance(...fgRgb);
6200
+ const bgL = relativeLuminance(...bgRgb);
6201
+ const ratio = parseFloat(contrastRatioFromLuminance(fgL, bgL).toFixed(2));
6202
+ return {
6203
+ fgHex: rgbToHex(...fgRgb),
6204
+ bgHex: rgbToHex(...bgRgb),
6205
+ ratio,
6206
+ aa: ratio >= 4.5,
6207
+ aaLarge: ratio >= 3,
6208
+ aaa: ratio >= 7,
6209
+ aaaLarge: ratio >= 4.5
6210
+ };
6211
+ }
6212
+ function handleDeriveAccessiblePalette(seed, targetRatio) {
6213
+ const seedRgb = parseColor(seed);
6214
+ if (!seedRgb) throw new Error(`Cannot parse seed color: "${seed}"`);
6215
+ const seedHex = rgbToHex(...seedRgb);
6216
+ const seedL = relativeLuminance(...seedRgb);
6217
+ const whiteRatio = parseFloat(contrastRatioFromLuminance(1, seedL).toFixed(2));
6218
+ const blackRatio = parseFloat(contrastRatioFromLuminance(0, seedL).toFixed(2));
6219
+ const whiteWorks = whiteRatio >= targetRatio;
6220
+ const blackWorks = blackRatio >= targetRatio;
6221
+ let strategy;
6222
+ let foreground;
6223
+ let ratio;
6224
+ let alternativeForeground;
6225
+ let alternativeRatio;
6226
+ if (blackWorks && whiteWorks) {
6227
+ if (blackRatio >= whiteRatio) {
6228
+ strategy = "black";
6229
+ foreground = "#000000";
6230
+ ratio = blackRatio;
6231
+ alternativeForeground = "#ffffff";
6232
+ alternativeRatio = whiteRatio;
6233
+ } else {
6234
+ strategy = "white";
6235
+ foreground = "#ffffff";
6236
+ ratio = whiteRatio;
6237
+ alternativeForeground = "#000000";
6238
+ alternativeRatio = blackRatio;
6239
+ }
6240
+ } else if (blackWorks) {
6241
+ strategy = "black";
6242
+ foreground = "#000000";
6243
+ ratio = blackRatio;
6244
+ alternativeForeground = "#ffffff";
6245
+ alternativeRatio = whiteRatio;
6246
+ } else if (whiteWorks) {
6247
+ strategy = "white";
6248
+ foreground = "#ffffff";
6249
+ ratio = whiteRatio;
6250
+ alternativeForeground = "#000000";
6251
+ alternativeRatio = blackRatio;
6252
+ } else {
6253
+ strategy = "unachievable";
6254
+ if (blackRatio >= whiteRatio) {
6255
+ foreground = "#000000";
6256
+ ratio = blackRatio;
6257
+ alternativeForeground = "#ffffff";
6258
+ alternativeRatio = whiteRatio;
6259
+ } else {
6260
+ foreground = "#ffffff";
6261
+ ratio = whiteRatio;
6262
+ alternativeForeground = "#000000";
6263
+ alternativeRatio = blackRatio;
6264
+ }
6265
+ }
6266
+ return {
6267
+ seedHex,
6268
+ foreground,
6269
+ ratio,
6270
+ aa: ratio >= 4.5,
6271
+ aaLarge: ratio >= 3,
6272
+ aaa: ratio >= 7,
6273
+ meetsTarget: ratio >= targetRatio,
6274
+ strategy,
6275
+ alternativeForeground,
6276
+ alternativeRatio
6277
+ };
6278
+ }
6279
+ var PASS = "[PASS]";
6280
+ var FAIL = "[FAIL]";
6281
+ var mark = (ok) => ok ? PASS : FAIL;
6282
+ function registerContrastTools(server2) {
6283
+ server2.tool(
6284
+ "stackwright_pro_check_contrast",
6285
+ 'Compute the exact WCAG 2.1 contrast ratio between a foreground and background color. Returns the ratio and AA/AAA pass/fail flags. Use this to verify any foreground/background color pair before writing it to the token set. Accepts #RGB, #RRGGBB, hsl(...), or shadcn HSL format ("H S% L%").',
6286
+ {
6287
+ fg: import_zod18.z.string().describe("Foreground (text) color \u2014 hex or HSL"),
6288
+ bg: import_zod18.z.string().describe("Background color \u2014 hex or HSL")
6289
+ },
6290
+ async ({ fg, bg }) => {
6291
+ let result;
6292
+ try {
6293
+ result = handleCheckContrast(fg, bg);
6294
+ } catch (err) {
6295
+ return {
6296
+ content: [{ type: "text", text: `Error: ${err.message}` }]
6297
+ };
6298
+ }
6299
+ const text = [
6300
+ `WCAG 2.1 Contrast Check`,
6301
+ ``,
6302
+ ` Foreground : ${result.fgHex}`,
6303
+ ` Background : ${result.bgHex}`,
6304
+ ` Ratio : ${result.ratio}:1`,
6305
+ ``,
6306
+ ` ${mark(result.aa)} AA \u2014 normal text (\u22654.5:1)`,
6307
+ ` ${mark(result.aaLarge)} AA \u2014 large text (\u22653.0:1)`,
6308
+ ` ${mark(result.aaa)} AAA \u2014 normal text (\u22657.0:1)`,
6309
+ ` ${mark(result.aaaLarge)} AAA \u2014 large text (\u22654.5:1)`
6310
+ ].join("\n");
6311
+ return { content: [{ type: "text", text }] };
6312
+ }
6313
+ );
6314
+ server2.tool(
6315
+ "stackwright_pro_derive_accessible_palette",
6316
+ 'Given a seed color (treated as a background), derive the best accessible foreground (text) color that meets the target contrast ratio. Evaluates #ffffff and #000000 against the seed and picks whichever satisfies the target ratio with the highest contrast. Use this for every {name}-foreground token derivation instead of guessing white vs black. Accepts #RGB, #RRGGBB, hsl(...), or shadcn HSL format ("H S% L%").',
6317
+ {
6318
+ seed: import_zod18.z.string().describe("Background (seed) color \u2014 hex or HSL"),
6319
+ targetRatio: numCoerce(import_zod18.z.number().default(4.5)).describe(
6320
+ "Minimum required contrast ratio (default 4.5 for WCAG AA)"
6321
+ )
6322
+ },
6323
+ async ({ seed, targetRatio }) => {
6324
+ let result;
6325
+ try {
6326
+ result = handleDeriveAccessiblePalette(seed, targetRatio ?? 4.5);
6327
+ } catch (err) {
6328
+ return {
6329
+ content: [{ type: "text", text: `Error: ${err.message}` }]
6330
+ };
6331
+ }
6332
+ const metLine = result.meetsTarget ? `${PASS} Meets target (${targetRatio}:1)` : `${FAIL} Target (${targetRatio}:1) UNACHIEVABLE with white or black \u2014 best available used`;
6333
+ const altNote = result.alternativeRatio >= (targetRatio ?? 4.5) ? `also passes (${result.alternativeRatio}:1)` : `fails at ${result.alternativeRatio}:1`;
6334
+ const text = [
6335
+ `Accessible Palette Derivation`,
6336
+ ``,
6337
+ ` Background (seed) : ${result.seedHex}`,
6338
+ ` Foreground : ${result.foreground} (${result.strategy})`,
6339
+ ` Contrast ratio : ${result.ratio}:1`,
6340
+ ` ${metLine}`,
6341
+ ``,
6342
+ ` ${mark(result.aa)} AA \u2014 normal text (\u22654.5:1)`,
6343
+ ` ${mark(result.aaLarge)} AA \u2014 large text (\u22653.0:1)`,
6344
+ ` ${mark(result.aaa)} AAA \u2014 normal text (\u22657.0:1)`,
6345
+ ``,
6346
+ ` Alternative (${result.alternativeForeground}): ${altNote}`
6347
+ ].join("\n");
6348
+ return { content: [{ type: "text", text }] };
6349
+ }
6350
+ );
6351
+ }
6352
+
3448
6353
  // package.json
3449
6354
  var package_default = {
3450
6355
  dependencies: {
3451
6356
  "@modelcontextprotocol/sdk": "^1.10.0",
3452
6357
  "@stackwright-pro/cli-data-explorer": "workspace:*",
3453
- zod: "^4.3.6"
6358
+ "@stackwright-pro/types": "workspace:*",
6359
+ "@types/js-yaml": "^4.0.9",
6360
+ "js-yaml": "^4.2.0",
6361
+ zod: "^4.4.3"
3454
6362
  },
3455
6363
  devDependencies: {
3456
- "@types/node": "^24.1.0",
3457
- tsup: "^8.5.0",
3458
- typescript: "^5.8.3",
3459
- vitest: "^4.0.18"
6364
+ "@types/node": "catalog:",
6365
+ tsup: "catalog:",
6366
+ typescript: "catalog:",
6367
+ vitest: "catalog:"
3460
6368
  },
3461
6369
  scripts: {
3462
6370
  prepublishOnly: "node scripts/verify-integrity-sync.js",
@@ -3467,10 +6375,13 @@ var package_default = {
3467
6375
  "test:coverage": "vitest run --coverage"
3468
6376
  },
3469
6377
  name: "@stackwright-pro/mcp",
3470
- version: "0.2.0-alpha.8",
6378
+ version: "0.2.0-alpha.81",
3471
6379
  description: "MCP tools for Stackwright Pro - Data Explorer, Security, ISR, and Dashboard generation",
3472
- license: "PROPRIETARY",
6380
+ license: "SEE LICENSE IN LICENSE",
3473
6381
  main: "./dist/server.js",
6382
+ bin: {
6383
+ "stackwright-pro-mcp": "./dist/server.js"
6384
+ },
3474
6385
  module: "./dist/server.mjs",
3475
6386
  types: "./dist/server.d.ts",
3476
6387
  exports: {
@@ -3483,6 +6394,11 @@ var package_default = {
3483
6394
  types: "./dist/integrity.d.ts",
3484
6395
  import: "./dist/integrity.mjs",
3485
6396
  require: "./dist/integrity.js"
6397
+ },
6398
+ "./type-schemas": {
6399
+ types: "./dist/tools/type-schemas.d.ts",
6400
+ import: "./dist/tools/type-schemas.mjs",
6401
+ require: "./dist/tools/type-schemas.js"
3486
6402
  }
3487
6403
  },
3488
6404
  files: [
@@ -3510,9 +6426,24 @@ registerPipelineTools(server);
3510
6426
  registerSafeWriteTools(server);
3511
6427
  registerAuthTools(server);
3512
6428
  registerIntegrityTools(server);
6429
+ registerArtifactSigningTools(server);
3513
6430
  registerDomainTools(server);
6431
+ registerTypeSchemasTool(server);
6432
+ registerValidateYamlFragmentTool(server);
6433
+ registerGetSchemaTool(server);
6434
+ registerScaffoldCleanupTools(server);
6435
+ registerContrastTools(server);
3514
6436
  async function main() {
3515
6437
  const transport = new import_stdio.StdioServerTransport();
6438
+ try {
6439
+ const servicesRegisterPkg = "@stackwright-services/mcp/register";
6440
+ const mod = await import(servicesRegisterPkg);
6441
+ if (typeof mod.registerServicesTools === "function") {
6442
+ mod.registerServicesTools(server);
6443
+ console.error("Stackwright Services tools registered on pro MCP");
6444
+ }
6445
+ } catch {
6446
+ }
3516
6447
  await server.connect(transport);
3517
6448
  console.error("Stackwright Pro MCP server running on stdio");
3518
6449
  }