@stackwright-pro/mcp 0.2.0-alpha.9 → 0.2.0-alpha.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -3,15 +3,44 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
4
 
5
5
  // src/tools/data-explorer.ts
6
- import { z } from "zod";
6
+ import { z as z2 } from "zod";
7
7
  import { listEntities, generateFilter } from "@stackwright-pro/cli-data-explorer";
8
+
9
+ // src/coerce.ts
10
+ import { z } from "zod";
11
+ function jsonCoerce(schema) {
12
+ return z.preprocess((v) => {
13
+ if (typeof v === "string") {
14
+ try {
15
+ return JSON.parse(v);
16
+ } catch {
17
+ return v;
18
+ }
19
+ }
20
+ return v;
21
+ }, schema);
22
+ }
23
+ function boolCoerce(schema) {
24
+ return z.preprocess((v) => v === "true" ? true : v === "false" ? false : v, schema);
25
+ }
26
+ function numCoerce(schema) {
27
+ return z.preprocess((v) => {
28
+ if (typeof v === "string" && v.trim() !== "") {
29
+ const n = Number(v);
30
+ if (!Number.isNaN(n)) return n;
31
+ }
32
+ return v;
33
+ }, schema);
34
+ }
35
+
36
+ // src/tools/data-explorer.ts
8
37
  function registerDataExplorerTools(server2) {
9
38
  server2.tool(
10
39
  "stackwright_pro_list_entities",
11
40
  "List all available API entities from OpenAPI specs or generated Zod schemas. Use this to discover what entities are available before generating endpoint filters. Returns entity names, endpoints, and field counts. Part of the Pro Otter Raft for building API-integrated Stackwright applications.",
12
41
  {
13
- specPath: z.string().optional().describe("Path to OpenAPI spec file (YAML or JSON)"),
14
- projectRoot: z.string().optional().describe("Project root directory (auto-detected if omitted)")
42
+ specPath: z2.string().optional().describe("Path to OpenAPI spec file (YAML or JSON)"),
43
+ projectRoot: z2.string().optional().describe("Project root directory (auto-detected if omitted)")
15
44
  },
16
45
  async ({ specPath, projectRoot }) => {
17
46
  const result = listEntities({
@@ -59,9 +88,13 @@ function registerDataExplorerTools(server2) {
59
88
  "stackwright_pro_generate_filter",
60
89
  "Generate endpoint filter configuration from selected entities. Creates include/exclude patterns for stackwright.yml OpenAPI integration. Use this after stackwright_pro_list_entities to select which API endpoints the application needs. Only selected endpoints will generate client code, reducing bundle size and improving security.",
61
90
  {
62
- selectedEntities: z.array(z.string()).describe('Entity slugs to include (e.g., ["equipment", "supplies"])'),
63
- excludePatterns: z.array(z.string()).optional().describe('Glob patterns to exclude (e.g., ["/admin/**", "/reports/**"])'),
64
- projectRoot: z.string().optional().describe("Project root directory")
91
+ selectedEntities: jsonCoerce(z2.array(z2.string())).describe(
92
+ 'Entity slugs to include (e.g., ["equipment", "supplies"])'
93
+ ),
94
+ excludePatterns: jsonCoerce(z2.array(z2.string()).optional()).describe(
95
+ 'Glob patterns to exclude (e.g., ["/admin/**", "/reports/**"])'
96
+ ),
97
+ projectRoot: z2.string().optional().describe("Project root directory")
65
98
  },
66
99
  async ({ selectedEntities, excludePatterns, projectRoot }) => {
67
100
  const result = generateFilter({
@@ -117,7 +150,7 @@ function registerDataExplorerTools(server2) {
117
150
  }
118
151
 
119
152
  // src/tools/security.ts
120
- import { z as z2 } from "zod";
153
+ import { z as z3 } from "zod";
121
154
  import { createHash } from "crypto";
122
155
  import fs from "fs";
123
156
  import path from "path";
@@ -126,8 +159,8 @@ function registerSecurityTools(server2) {
126
159
  "stackwright_pro_validate_spec",
127
160
  "Validate an OpenAPI spec against the enterprise approved-specs configuration. Checks if the spec URL is on the allowlist and verifies SHA-256 hash integrity. Use this in enterprise environments where only pre-approved API specs are allowed. Fails build if spec is not approved or has been modified.",
128
161
  {
129
- specPath: z2.string().describe("URL or file path to the OpenAPI spec to validate"),
130
- configPath: z2.string().optional().describe("Path to stackwright.yml with prebuild.security config")
162
+ specPath: z3.string().describe("URL or file path to the OpenAPI spec to validate"),
163
+ configPath: z3.string().optional().describe("Path to stackwright.yml with prebuild.security config")
131
164
  },
132
165
  async ({ specPath, configPath }) => {
133
166
  let securityEnabled = false;
@@ -235,16 +268,15 @@ Status: Valid (${allowlist.length} specs on allowlist)`
235
268
  "stackwright_pro_add_approved_spec",
236
269
  "Add an OpenAPI spec to the approved-specs allowlist in stackwright.yml. Computes the SHA-256 hash of the spec and adds it to the security configuration. Use this when onboarding a new API in enterprise environments.",
237
270
  {
238
- name: z2.string().describe("Human-readable name for the spec"),
239
- url: z2.string().describe("URL or file path to the OpenAPI spec"),
240
- configPath: z2.string().optional().describe("Path to stackwright.yml")
271
+ name: z3.string().describe("Human-readable name for the spec"),
272
+ url: z3.string().describe("URL or file path to the OpenAPI spec"),
273
+ configPath: z3.string().optional().describe("Path to stackwright.yml")
241
274
  },
242
275
  async ({ name, url, configPath }) => {
243
276
  const configFile = configPath || path.join(process.cwd(), "stackwright.yml");
244
277
  let sha256 = "<computed-at-build>";
245
278
  try {
246
279
  if (url.startsWith("http://") || url.startsWith("https://")) {
247
- sha256 = "<computed-at-build>";
248
280
  } else if (fs.existsSync(url)) {
249
281
  const specContent = fs.readFileSync(url, "utf8");
250
282
  sha256 = createHash("sha256").update(specContent).digest("hex");
@@ -291,7 +323,7 @@ SHA-256 computed: ${sha256}`
291
323
  "stackwright_pro_list_approved_specs",
292
324
  "List all specs currently on the approved-specs allowlist. Shows spec names, URLs, and hash prefixes. Use this to audit what APIs are approved in the project.",
293
325
  {
294
- configPath: z2.string().optional().describe("Path to stackwright.yml")
326
+ configPath: z3.string().optional().describe("Path to stackwright.yml")
295
327
  },
296
328
  async ({ configPath }) => {
297
329
  const configFile = configPath || path.join(process.cwd(), "stackwright.yml");
@@ -360,16 +392,18 @@ SHA-256 computed: ${sha256}`
360
392
  }
361
393
 
362
394
  // src/tools/isr.ts
363
- import { z as z3 } from "zod";
395
+ import { z as z4 } from "zod";
364
396
  function registerIsrTools(server2) {
365
397
  server2.tool(
366
398
  "stackwright_pro_configure_isr",
367
399
  "Configure Incremental Static Regeneration (ISR) for an API-backed collection. ISR allows API data to be cached and refreshed on a schedule, providing real-time data with the performance of static generation. Use this after stackwright_pro_generate_filter to set revalidation intervals.",
368
400
  {
369
- collection: z3.string().describe('Collection name (e.g., "equipment", "supplies")'),
370
- revalidateSeconds: z3.number().optional().describe("Revalidation interval in seconds (default: 60)"),
371
- fallback: z3.enum(["blocking", "true", "false"]).optional().describe("Fallback behavior for new pages"),
372
- configPath: z3.string().optional().describe("Path to stackwright.yml")
401
+ collection: z4.string().describe('Collection name (e.g., "equipment", "supplies")'),
402
+ revalidateSeconds: numCoerce(z4.number().optional()).describe(
403
+ "Revalidation interval in seconds (default: 60)"
404
+ ),
405
+ fallback: z4.enum(["blocking", "true", "false"]).optional().describe("Fallback behavior for new pages"),
406
+ configPath: z4.string().optional().describe("Path to stackwright.yml")
373
407
  },
374
408
  async ({ collection, revalidateSeconds = 60, fallback = "blocking", configPath }) => {
375
409
  const revalidate = revalidateSeconds;
@@ -380,7 +414,7 @@ function registerIsrTools(server2) {
380
414
  isr:
381
415
  revalidate: ${revalidate}
382
416
  fallback: ${fallback}`;
383
- let description = "";
417
+ let description;
384
418
  if (revalidate < 60) {
385
419
  description = "\u26A1 Very fresh data (revalidate every " + revalidate + "s)";
386
420
  } else if (revalidate < 300) {
@@ -412,14 +446,16 @@ ${yamlSnippet}
412
446
  "stackwright_pro_configure_isr_batch",
413
447
  "Configure ISR for multiple collections at once. More efficient than calling stackwright_pro_configure_isr multiple times. Provide different revalidation intervals based on data freshness requirements.",
414
448
  {
415
- collections: z3.array(
416
- z3.object({
417
- name: z3.string().describe("Collection name"),
418
- revalidateSeconds: z3.number().optional().describe("Revalidation interval")
419
- })
449
+ collections: jsonCoerce(
450
+ z4.array(
451
+ z4.object({
452
+ name: z4.string().describe("Collection name"),
453
+ revalidateSeconds: numCoerce(z4.number().optional()).describe("Revalidation interval")
454
+ })
455
+ )
420
456
  ).describe("Array of collection configurations"),
421
- defaultFallback: z3.enum(["blocking", "true", "false"]).optional().describe("Default fallback behavior"),
422
- configPath: z3.string().optional().describe("Path to stackwright.yml")
457
+ defaultFallback: z4.enum(["blocking", "true", "false"]).optional().describe("Default fallback behavior"),
458
+ configPath: z4.string().optional().describe("Path to stackwright.yml")
423
459
  },
424
460
  async ({ collections, defaultFallback = "blocking", configPath }) => {
425
461
  const lines = [`\u2699\uFE0F Batch ISR Configuration:
@@ -447,17 +483,17 @@ Fallback: ${defaultFallback}`);
447
483
  }
448
484
 
449
485
  // src/tools/dashboard.ts
450
- import { z as z4 } from "zod";
486
+ import { z as z5 } from "zod";
451
487
  import { listEntities as listEntities2 } from "@stackwright-pro/cli-data-explorer";
452
488
  function registerDashboardTools(server2) {
453
489
  server2.tool(
454
490
  "stackwright_pro_generate_dashboard",
455
491
  "Generate a dashboard page configuration for displaying API data. Creates YAML content for a Stackwright page with grid, metric_card, data_table, and collection_list content types. Use this after stackwright_pro_generate_filter to create pages for your API collections.",
456
492
  {
457
- entities: z4.array(z4.string()).describe("Entity slugs to include in dashboard"),
458
- layout: z4.enum(["grid", "table", "mixed"]).optional().describe("Dashboard layout style"),
459
- pageTitle: z4.string().optional().describe("Page title"),
460
- specPath: z4.string().optional().describe("Path to OpenAPI spec for entity details")
493
+ entities: jsonCoerce(z5.array(z5.string())).describe("Entity slugs to include in dashboard"),
494
+ layout: z5.enum(["grid", "table", "mixed"]).optional().describe("Dashboard layout style"),
495
+ pageTitle: z5.string().optional().describe("Page title"),
496
+ specPath: z5.string().optional().describe("Path to OpenAPI spec for entity details")
461
497
  },
462
498
  async ({ entities, layout = "mixed", pageTitle, specPath }) => {
463
499
  let entityDetails = [];
@@ -543,9 +579,9 @@ ${yaml}
543
579
  "stackwright_pro_generate_detail_page",
544
580
  "Generate a detail view page for a single API entity. Creates YAML content for displaying all fields of an individual record. Use this to create detail pages that complement collection listing pages.",
545
581
  {
546
- entity: z4.string().describe('Entity slug (e.g., "equipment")'),
547
- slugField: z4.string().optional().describe('Field to use as URL slug (default: "id")'),
548
- specPath: z4.string().optional().describe("Path to OpenAPI spec for field details")
582
+ entity: z5.string().describe('Entity slug (e.g., "equipment")'),
583
+ slugField: z5.string().optional().describe('Field to use as URL slug (default: "id")'),
584
+ specPath: z5.string().optional().describe("Path to OpenAPI spec for field details")
549
585
  },
550
586
  async ({ entity, slugField = "id", specPath }) => {
551
587
  let fields = [];
@@ -568,39 +604,49 @@ ${yaml}
568
604
  ` title: "${entityName} Details | {{ ${entity}.${slugField} }}"`,
569
605
  "",
570
606
  " content_items:",
571
- " - main:",
572
- ' label: "detail-header"',
573
- " heading:",
574
- ` text: "{{ ${entity}.${slugField} }}"`,
575
- ' textSize: "h1"',
576
- " textBlocks:",
577
- ` - text: "Details for this ${entity}"`,
578
- ' textSize: "body1"',
579
- ' background: "primary"',
580
- ' color: "text"',
607
+ " - type: text_block",
608
+ ' label: "detail-header"',
609
+ " heading:",
610
+ ` text: "{{ ${entity}.${slugField} }}"`,
611
+ ' textSize: "h1"',
612
+ " textBlocks:",
613
+ ` - text: "Details for this ${entity}"`,
614
+ ' textSize: "body1"',
581
615
  "",
582
- " - grid:",
583
- ' label: "detail-fields"',
584
- " columns: 2",
585
- " items:"
616
+ " - type: grid",
617
+ ' label: "detail-fields"',
618
+ " columns:"
586
619
  ];
587
620
  const displayFields = fields.length > 0 ? fields.slice(0, 8) : [
588
621
  { name: slugField, type: "string" },
589
622
  { name: "created_at", type: "datetime" },
590
623
  { name: "updated_at", type: "datetime" }
591
624
  ];
592
- for (const field of displayFields) {
593
- const label = field.name.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
594
- yamlLines.push(` - card:`);
595
- yamlLines.push(` label: "${field.name}-field"`);
596
- yamlLines.push(` heading:`);
597
- yamlLines.push(` text: "${label}"`);
598
- yamlLines.push(` textSize: "h4"`);
599
- yamlLines.push(` content:`);
600
- yamlLines.push(` - text: "{{ ${entity}.${field.name} }}"`);
601
- yamlLines.push(` textSize: "body1"`);
602
- }
603
- yamlLines.push(' background: "background"');
625
+ const mid = Math.ceil(displayFields.length / 2);
626
+ const col1 = displayFields.slice(0, mid);
627
+ const col2 = displayFields.slice(mid);
628
+ for (const [colIndex, colFields] of [col1, col2].entries()) {
629
+ yamlLines.push(" - width: 1");
630
+ yamlLines.push(" content_items:");
631
+ for (const field of colFields) {
632
+ const label = field.name.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
633
+ yamlLines.push(" - type: text_block");
634
+ yamlLines.push(` label: "${field.name}-field"`);
635
+ yamlLines.push(" heading:");
636
+ yamlLines.push(` text: "${label}"`);
637
+ yamlLines.push(' textSize: "h4"');
638
+ yamlLines.push(" textBlocks:");
639
+ yamlLines.push(` - text: "{{ ${entity}.${field.name} }}"`);
640
+ yamlLines.push(' textSize: "body1"');
641
+ }
642
+ }
643
+ yamlLines.push("");
644
+ yamlLines.push(" - type: action_bar");
645
+ yamlLines.push(" actions:");
646
+ yamlLines.push(` - label: "<- Back to ${entityName}"`);
647
+ yamlLines.push(" action: navigate");
648
+ yamlLines.push(` href: "/${entity}"`);
649
+ yamlLines.push(" style: secondary");
604
650
  const yaml = yamlLines.join("\n");
605
651
  return {
606
652
  content: [
@@ -621,7 +667,7 @@ ${yaml}
621
667
  }
622
668
 
623
669
  // src/tools/clarification.ts
624
- import { z as z5 } from "zod";
670
+ import { z as z6 } from "zod";
625
671
  var CONTRADICTION_PATTERNS = [
626
672
  {
627
673
  keywords: ["minimal", "clean", "simple"],
@@ -709,12 +755,14 @@ function registerClarificationTools(server2) {
709
755
  "stackwright_pro_clarify",
710
756
  "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).",
711
757
  {
712
- context: z5.string().optional().describe("Context about what the otter is trying to do"),
713
- question_type: z5.enum(["closed_choice", "open_text"]).describe("Type of question being asked"),
714
- question: z5.string().describe("The clarification question to ask the user"),
715
- choices: z5.array(z5.string()).optional().describe("Options for closed_choice questions"),
716
- priority: z5.enum(["blocking", "preferred", "optional"]).optional().default("preferred").describe("How critical is this clarification? Default: preferred"),
717
- target_field: z5.string().optional().describe("What field/config does this clarify?")
758
+ context: z6.string().optional().describe("Context about what the otter is trying to do"),
759
+ question_type: z6.enum(["closed_choice", "open_text"]).describe("Type of question being asked"),
760
+ question: z6.string().describe("The clarification question to ask the user"),
761
+ choices: jsonCoerce(z6.array(z6.string()).optional()).describe(
762
+ "Options for closed_choice questions"
763
+ ),
764
+ priority: z6.enum(["blocking", "preferred", "optional"]).optional().default("preferred").describe("How critical is this clarification? Default: preferred"),
765
+ target_field: z6.string().optional().describe("What field/config does this clarify?")
718
766
  },
719
767
  async ({ context, question_type, question, choices, priority, target_field }) => {
720
768
  const result = handleClarify({
@@ -743,8 +791,10 @@ function registerClarificationTools(server2) {
743
791
  "stackwright_pro_detect_conflict",
744
792
  "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.",
745
793
  {
746
- stated_preference: z5.string().describe("What the user said they wanted"),
747
- selected_values: z5.record(z5.string(), z5.string()).describe("What the user actually selected (field \u2192 value)")
794
+ stated_preference: z6.string().describe("What the user said they wanted"),
795
+ selected_values: jsonCoerce(z6.record(z6.string(), z6.string())).describe(
796
+ "What the user actually selected (field \u2192 value)"
797
+ )
748
798
  },
749
799
  async ({ stated_preference, selected_values }) => {
750
800
  const result = handleDetectConflict({ stated_preference, selected_values });
@@ -789,7 +839,7 @@ ${result.resolution_options?.map((o) => ` \u2022 ${o}`).join("\n")}
789
839
  }
790
840
 
791
841
  // src/tools/packages.ts
792
- import { z as z6 } from "zod";
842
+ import { z as z7 } from "zod";
793
843
  import { readFileSync, writeFileSync, existsSync, realpathSync, lstatSync } from "fs";
794
844
  import { execSync } from "child_process";
795
845
  import path2 from "path";
@@ -810,17 +860,23 @@ function registerPackageTools(server2) {
810
860
  "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.",
811
861
  {
812
862
  // FIX 3 (B-new-1): Zod v4 requires two-arg z.record(keySchema, valueSchema)
813
- packages: z6.record(z6.string(), z6.string()).describe(
814
- 'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }'
863
+ packages: jsonCoerce(z7.record(z7.string(), z7.string()).optional().default({})).describe(
864
+ 'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }. Omit or pass {} when using includeBaseline: true.'
865
+ ),
866
+ devPackages: jsonCoerce(z7.record(z7.string(), z7.string()).optional()).describe(
867
+ "devDependencies to add. Same format as packages."
815
868
  ),
816
- devPackages: z6.record(z6.string(), z6.string()).optional().describe("devDependencies to add. Same format as packages."),
817
- scripts: z6.record(z6.string(), z6.string()).optional().describe("npm scripts to add. Only adds if key does not already exist."),
818
- targetDir: z6.string().optional().describe(
869
+ scripts: jsonCoerce(z7.record(z7.string(), z7.string()).optional()).describe(
870
+ "npm scripts to add. Only adds if key does not already exist."
871
+ ),
872
+ targetDir: z7.string().optional().describe(
819
873
  "Project directory containing package.json. Defaults to process.cwd(). Must be an absolute path within the current working directory."
820
874
  ),
821
- runInstall: z6.boolean().optional().default(true).describe("Run pnpm install after writing package.json. Defaults to true."),
822
- includeBaseline: z6.boolean().optional().default(false).describe(
823
- "When true, automatically merges BASELINE_DEPS and BASELINE_DEV_DEPS before applying packages/devPackages args. Safe to call on existing projects \u2014 never overwrites pinned versions."
875
+ runInstall: boolCoerce(z7.boolean().optional().default(true)).describe(
876
+ "Run pnpm install after writing package.json. Defaults to true. Pass boolean true/false."
877
+ ),
878
+ includeBaseline: boolCoerce(z7.boolean().optional().default(false)).describe(
879
+ "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."
824
880
  )
825
881
  },
826
882
  async ({ packages, devPackages, scripts, targetDir, runInstall, includeBaseline }) => {
@@ -978,11 +1034,11 @@ function setupPackages(opts) {
978
1034
  }
979
1035
  }
980
1036
  const raw = readFileSync(realPackageJsonPath, "utf8");
981
- const PackageJsonSchema = z6.object({
1037
+ const PackageJsonSchema = z7.object({
982
1038
  // Zod v4: z.record(keySchema, valueSchema) — two-arg form required
983
- dependencies: z6.record(z6.string(), z6.string()).optional(),
984
- devDependencies: z6.record(z6.string(), z6.string()).optional(),
985
- scripts: z6.record(z6.string(), z6.string()).optional()
1039
+ dependencies: z7.record(z7.string(), z7.string()).optional(),
1040
+ devDependencies: z7.record(z7.string(), z7.string()).optional(),
1041
+ scripts: z7.record(z7.string(), z7.string()).optional()
986
1042
  }).passthrough();
987
1043
  const schemaResult = PackageJsonSchema.safeParse(JSON.parse(raw));
988
1044
  if (!schemaResult.success) {
@@ -1063,9 +1119,10 @@ function setupPackages(opts) {
1063
1119
  }
1064
1120
 
1065
1121
  // src/tools/questions.ts
1066
- import { readFile } from "fs/promises";
1122
+ import { readFile, writeFile } from "fs/promises";
1123
+ import { existsSync as existsSync2, lstatSync as lstatSync2, mkdirSync, renameSync } from "fs";
1067
1124
  import { join } from "path";
1068
- import { z as z7 } from "zod";
1125
+ import { z as z8 } from "zod";
1069
1126
 
1070
1127
  // src/question-adapter.ts
1071
1128
  function truncate(str, maxLength) {
@@ -1250,23 +1307,30 @@ function answersToManifestFormat(answers, questions) {
1250
1307
  return result;
1251
1308
  }
1252
1309
 
1310
+ // src/validation.ts
1311
+ var SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
1312
+ var SAFE_QUESTION_ID = /^[a-z0-9][a-z0-9-]{0,63}$/i;
1313
+ function isValidPhase(phase) {
1314
+ return SAFE_PHASE.test(phase);
1315
+ }
1316
+
1253
1317
  // src/tools/questions.ts
1254
- var ManifestQuestionSchema = z7.object({
1255
- id: z7.string(),
1256
- question: z7.string(),
1257
- type: z7.enum(["text", "select", "multi-select", "confirm"]),
1258
- required: z7.boolean().optional(),
1259
- options: z7.array(
1260
- z7.object({
1261
- label: z7.string(),
1262
- value: z7.string()
1318
+ var ManifestQuestionSchema = z8.object({
1319
+ id: z8.string(),
1320
+ question: z8.string(),
1321
+ type: z8.enum(["text", "select", "multi-select", "confirm"]),
1322
+ required: z8.boolean().optional(),
1323
+ options: z8.array(
1324
+ z8.object({
1325
+ label: z8.string(),
1326
+ value: z8.string()
1263
1327
  })
1264
1328
  ).optional(),
1265
- default: z7.union([z7.string(), z7.boolean(), z7.array(z7.string())]).optional(),
1266
- help: z7.string().optional(),
1267
- dependsOn: z7.object({
1268
- questionId: z7.string(),
1269
- value: z7.union([z7.string(), z7.array(z7.string())])
1329
+ default: z8.union([z8.string(), z8.boolean(), z8.array(z8.string())]).optional(),
1330
+ help: z8.string().optional(),
1331
+ dependsOn: z8.object({
1332
+ questionId: z8.string(),
1333
+ value: z8.union([z8.string(), z8.array(z8.string())])
1270
1334
  }).optional()
1271
1335
  });
1272
1336
  function registerQuestionTools(server2) {
@@ -1274,15 +1338,16 @@ function registerQuestionTools(server2) {
1274
1338
  "stackwright_pro_present_phase_questions",
1275
1339
  "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.",
1276
1340
  {
1277
- phase: z7.string().describe('Phase name for display context, e.g. "designer", "api", "auth"'),
1278
- questions: z7.array(ManifestQuestionSchema).optional().describe(
1341
+ phase: z8.string().describe('Phase name for display context, e.g. "designer", "api", "auth"'),
1342
+ questions: jsonCoerce(z8.array(ManifestQuestionSchema).optional()).describe(
1279
1343
  "Questions in Question Manifest format. If omitted, questions are read from .stackwright/question-manifest.json using the phase name."
1280
1344
  ),
1281
- answers: z7.record(z7.union([z7.string(), z7.array(z7.string()), z7.boolean()])).optional().describe("Previously collected answers used to resolve dependsOn conditions")
1345
+ answers: jsonCoerce(
1346
+ z8.record(z8.string(), z8.union([z8.string(), z8.array(z8.string()), z8.boolean()])).optional()
1347
+ ).describe("Previously collected answers used to resolve dependsOn conditions")
1282
1348
  },
1283
1349
  async ({ phase, questions, answers }) => {
1284
1350
  let resolvedQuestions;
1285
- const SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
1286
1351
  if (!SAFE_PHASE.test(phase)) {
1287
1352
  return {
1288
1353
  content: [
@@ -1329,17 +1394,36 @@ function registerQuestionTools(server2) {
1329
1394
  }
1330
1395
  }
1331
1396
  const adapted = adaptQuestions(resolvedQuestions, answers ?? {});
1397
+ const labelSchema = z8.string().max(50, "Value should have at most 50 characters");
1398
+ for (const q of adapted) {
1399
+ for (const opt of q.options) {
1400
+ const check = labelSchema.safeParse(opt.label);
1401
+ if (!check.success) {
1402
+ return {
1403
+ content: [
1404
+ {
1405
+ type: "text",
1406
+ text: JSON.stringify({
1407
+ 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.`
1408
+ })
1409
+ }
1410
+ ],
1411
+ isError: true
1412
+ };
1413
+ }
1414
+ }
1415
+ }
1332
1416
  if (adapted.length === 0) {
1333
1417
  return {
1334
1418
  content: [
1335
1419
  {
1336
1420
  type: "text",
1337
- text: JSON.stringify({
1338
- phase,
1339
- skipped: true,
1340
- reason: "No questions to present (all filtered by dependsOn conditions)",
1341
- answers: []
1342
- })
1421
+ 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.`
1422
+ },
1423
+ {
1424
+ type: "text",
1425
+ // Empty array — second block always present so the foreman's two-block contract holds
1426
+ text: JSON.stringify([])
1343
1427
  }
1344
1428
  ],
1345
1429
  isError: false
@@ -1360,31 +1444,175 @@ function registerQuestionTools(server2) {
1360
1444
  };
1361
1445
  }
1362
1446
  );
1447
+ server2.tool(
1448
+ "stackwright_pro_get_next_question",
1449
+ "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.",
1450
+ { phase: z8.string().describe('Phase name e.g. "designer", "api", "auth"') },
1451
+ async ({ phase }) => {
1452
+ if (!SAFE_PHASE.test(phase)) {
1453
+ return {
1454
+ content: [
1455
+ {
1456
+ type: "text",
1457
+ text: JSON.stringify({ error: `Invalid phase name: "${phase.slice(0, 50)}"` })
1458
+ }
1459
+ ],
1460
+ isError: true
1461
+ };
1462
+ }
1463
+ const cwd = process.cwd();
1464
+ const questionsPath = join(cwd, ".stackwright", "questions", `${phase}.json`);
1465
+ let questions = [];
1466
+ try {
1467
+ const raw = await readFile(questionsPath, "utf-8");
1468
+ const parsed = JSON.parse(raw);
1469
+ questions = parsed.questions ?? [];
1470
+ } catch {
1471
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1472
+ }
1473
+ if (questions.length === 0) {
1474
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1475
+ }
1476
+ const answersPath = join(cwd, ".stackwright", "answers", `${phase}.json`);
1477
+ let answeredIds = /* @__PURE__ */ new Set();
1478
+ try {
1479
+ const raw = await readFile(answersPath, "utf-8");
1480
+ const parsed = JSON.parse(raw);
1481
+ answeredIds = new Set(Object.keys(parsed.answers ?? {}));
1482
+ } catch {
1483
+ }
1484
+ const next = questions.find((q) => !answeredIds.has(q.id));
1485
+ if (!next) {
1486
+ return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
1487
+ }
1488
+ return {
1489
+ content: [
1490
+ {
1491
+ type: "text",
1492
+ text: JSON.stringify({
1493
+ done: false,
1494
+ questionId: next.id,
1495
+ question: next.question,
1496
+ type: next.type,
1497
+ options: next.options ?? null,
1498
+ help: next.help ?? null,
1499
+ index: questions.indexOf(next) + 1,
1500
+ total: questions.length
1501
+ })
1502
+ }
1503
+ ]
1504
+ };
1505
+ }
1506
+ );
1507
+ server2.tool(
1508
+ "stackwright_pro_record_answer",
1509
+ "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.",
1510
+ {
1511
+ phase: z8.string().describe('Phase name e.g. "designer"'),
1512
+ questionId: z8.string().describe('The question ID from get_next_question, e.g. "designer-1"'),
1513
+ answer: z8.string().describe("The user's free-text answer")
1514
+ },
1515
+ async ({ phase, questionId, answer }) => {
1516
+ if (!SAFE_PHASE.test(phase)) {
1517
+ return {
1518
+ content: [
1519
+ { type: "text", text: JSON.stringify({ error: "Invalid phase name" }) }
1520
+ ],
1521
+ isError: true
1522
+ };
1523
+ }
1524
+ if (!SAFE_QUESTION_ID.test(questionId)) {
1525
+ return {
1526
+ content: [
1527
+ { type: "text", text: JSON.stringify({ error: "Invalid questionId" }) }
1528
+ ],
1529
+ isError: true
1530
+ };
1531
+ }
1532
+ const safeAnswer = answer.slice(0, 2e3);
1533
+ const cwd = process.cwd();
1534
+ const answersDir = join(cwd, ".stackwright", "answers");
1535
+ const answersPath = join(answersDir, `${phase}.json`);
1536
+ if (existsSync2(answersDir) && lstatSync2(answersDir).isSymbolicLink()) {
1537
+ return {
1538
+ content: [
1539
+ {
1540
+ type: "text",
1541
+ text: JSON.stringify({ error: "answers dir is a symlink \u2014 refusing to write" })
1542
+ }
1543
+ ],
1544
+ isError: true
1545
+ };
1546
+ }
1547
+ mkdirSync(answersDir, { recursive: true });
1548
+ let existing = {
1549
+ version: "1.0",
1550
+ phase,
1551
+ answers: {}
1552
+ };
1553
+ try {
1554
+ if (existsSync2(answersPath)) {
1555
+ if (lstatSync2(answersPath).isSymbolicLink()) {
1556
+ return {
1557
+ content: [
1558
+ {
1559
+ type: "text",
1560
+ text: JSON.stringify({ error: "answers file is a symlink \u2014 refusing to write" })
1561
+ }
1562
+ ],
1563
+ isError: true
1564
+ };
1565
+ }
1566
+ const raw = await readFile(answersPath, "utf-8");
1567
+ existing = JSON.parse(raw);
1568
+ }
1569
+ } catch {
1570
+ }
1571
+ existing.answers[questionId] = safeAnswer;
1572
+ existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1573
+ const tmp = `${answersPath}.tmp`;
1574
+ await writeFile(tmp, JSON.stringify(existing, null, 2), "utf-8");
1575
+ renameSync(tmp, answersPath);
1576
+ return {
1577
+ content: [
1578
+ { type: "text", text: JSON.stringify({ recorded: true, phase, questionId }) }
1579
+ ]
1580
+ };
1581
+ }
1582
+ );
1363
1583
  }
1364
1584
 
1365
1585
  // src/tools/orchestration.ts
1366
- import { z as z8 } from "zod";
1367
- import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync2, mkdirSync, lstatSync as lstatSync2 } from "fs";
1586
+ import { z as z9 } from "zod";
1587
+ import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync3, mkdirSync as mkdirSync2, lstatSync as lstatSync3 } from "fs";
1368
1588
  import { join as join2 } from "path";
1369
1589
  var OTTER_NAME_TO_PHASE = [
1370
1590
  ["designer", "designer"],
1371
1591
  ["theme", "theme"],
1592
+ ["scaffold", "scaffold"],
1372
1593
  ["api", "api"],
1373
1594
  ["auth", "auth"],
1374
1595
  ["dashboard", "dashboard"],
1375
1596
  ["data", "data"],
1376
1597
  ["page", "pages"],
1377
- ["workflow", "workflow"]
1598
+ ["workflow", "workflow"],
1599
+ ["services", "services"],
1600
+ ["polish", "polish"],
1601
+ ["geo", "geo"]
1378
1602
  ];
1379
1603
  var PHASE_TO_OTTER = {
1380
1604
  designer: "stackwright-pro-designer-otter",
1381
1605
  theme: "stackwright-pro-theme-otter",
1606
+ scaffold: "stackwright-pro-scaffold-otter",
1382
1607
  api: "stackwright-pro-api-otter",
1383
1608
  auth: "stackwright-pro-auth-otter",
1384
1609
  pages: "stackwright-pro-page-otter",
1385
1610
  dashboard: "stackwright-pro-dashboard-otter",
1386
1611
  data: "stackwright-pro-data-otter",
1387
- workflow: "stackwright-pro-workflow-otter"
1612
+ workflow: "stackwright-pro-workflow-otter",
1613
+ services: "stackwright-services-otter",
1614
+ polish: "stackwright-pro-polish-otter",
1615
+ geo: "stackwright-pro-geo-otter"
1388
1616
  };
1389
1617
  function detectPhase(otterName) {
1390
1618
  const lower = otterName.toLowerCase();
@@ -1420,9 +1648,9 @@ function handleSaveManifest(input) {
1420
1648
  const dir = join2(cwd, ".stackwright");
1421
1649
  const filePath = join2(dir, "question-manifest.json");
1422
1650
  try {
1423
- mkdirSync(dir, { recursive: true });
1424
- if (existsSync2(filePath)) {
1425
- const stat = lstatSync2(filePath);
1651
+ mkdirSync2(dir, { recursive: true });
1652
+ if (existsSync3(filePath)) {
1653
+ const stat = lstatSync3(filePath);
1426
1654
  if (stat.isSymbolicLink()) {
1427
1655
  const message = `Refusing to write to symlink: ${filePath}`;
1428
1656
  return {
@@ -1450,14 +1678,78 @@ function handleSaveManifest(input) {
1450
1678
  }
1451
1679
  }
1452
1680
  function handleSavePhaseAnswers(input) {
1681
+ if (!isValidPhase(input.phase)) {
1682
+ return {
1683
+ text: JSON.stringify({
1684
+ success: false,
1685
+ error: `Invalid phase name: "${input.phase.slice(0, 50)}". Must be lowercase alphanumeric with hyphens, max 31 chars.`
1686
+ }),
1687
+ isError: true
1688
+ };
1689
+ }
1690
+ for (let i = 0; i < input.rawAnswers.length; i++) {
1691
+ const a = input.rawAnswers[i];
1692
+ if (!a.question_header || a.question_header.trim().length === 0) {
1693
+ return {
1694
+ text: JSON.stringify({
1695
+ success: false,
1696
+ error: `rawAnswers[${i}].question_header is empty \u2014 every answer must have a non-empty question_header.`
1697
+ }),
1698
+ isError: true
1699
+ };
1700
+ }
1701
+ if (!a.selected_options || a.selected_options.length === 0) {
1702
+ return {
1703
+ text: JSON.stringify({
1704
+ success: false,
1705
+ error: `rawAnswers[${i}].selected_options is empty for question_header "${a.question_header}" \u2014 every answer must have at least one selected option.`
1706
+ }),
1707
+ isError: true
1708
+ };
1709
+ }
1710
+ }
1711
+ if (input.questions && input.questions.length > 0 && input.rawAnswers.length === 0) {
1712
+ return {
1713
+ text: JSON.stringify({
1714
+ success: false,
1715
+ 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.`
1716
+ }),
1717
+ isError: true
1718
+ };
1719
+ }
1453
1720
  const cwd = input._cwd ?? process.cwd();
1454
1721
  const dir = join2(cwd, ".stackwright", "answers");
1455
1722
  const filePath = join2(dir, `${input.phase}.json`);
1456
1723
  try {
1457
- mkdirSync(dir, { recursive: true });
1724
+ mkdirSync2(dir, { recursive: true });
1725
+ const warnings = [];
1458
1726
  let answers;
1459
1727
  if (input.questions && input.questions.length > 0) {
1460
- answers = answersToManifestFormat(input.rawAnswers, input.questions);
1728
+ try {
1729
+ answers = answersToManifestFormat(input.rawAnswers, input.questions);
1730
+ } catch (mapErr) {
1731
+ answers = {};
1732
+ warnings.push(
1733
+ `Reverse-mapping threw (${mapErr instanceof Error ? mapErr.message : String(mapErr)}) \u2014 falling back to direct key mapping.`
1734
+ );
1735
+ }
1736
+ if (Object.keys(answers).length === 0 && input.rawAnswers.length > 0) {
1737
+ answers = Object.fromEntries(
1738
+ input.rawAnswers.map((a) => [
1739
+ a.question_header,
1740
+ a.selected_options.length > 1 ? a.selected_options : a.selected_options[0] ?? ""
1741
+ ])
1742
+ );
1743
+ warnings.push(
1744
+ `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).`
1745
+ );
1746
+ }
1747
+ const requiredCount = input.questions.filter((q) => q.required !== false).length;
1748
+ if (input.rawAnswers.length < requiredCount) {
1749
+ warnings.push(
1750
+ `Only ${input.rawAnswers.length} answers provided for ${requiredCount} required questions (${input.questions.length} total) \u2014 answers may be incomplete.`
1751
+ );
1752
+ }
1461
1753
  } else {
1462
1754
  answers = Object.fromEntries(
1463
1755
  input.rawAnswers.map((a) => [a.question_header, a.selected_options[0] ?? ""])
@@ -1469,8 +1761,8 @@ function handleSavePhaseAnswers(input) {
1469
1761
  completedAt: (/* @__PURE__ */ new Date()).toISOString(),
1470
1762
  answers
1471
1763
  };
1472
- if (existsSync2(filePath)) {
1473
- const stat = lstatSync2(filePath);
1764
+ if (existsSync3(filePath)) {
1765
+ const stat = lstatSync3(filePath);
1474
1766
  if (stat.isSymbolicLink()) {
1475
1767
  const message = `Refusing to write to symlink: ${filePath}`;
1476
1768
  return {
@@ -1484,7 +1776,8 @@ function handleSavePhaseAnswers(input) {
1484
1776
  text: JSON.stringify({
1485
1777
  success: true,
1486
1778
  path: filePath,
1487
- answersCount: Object.keys(answers).length
1779
+ answersCount: Object.keys(answers).length,
1780
+ ...warnings.length > 0 ? { warnings } : {}
1488
1781
  }),
1489
1782
  isError: false
1490
1783
  };
@@ -1499,7 +1792,7 @@ function handleSavePhaseAnswers(input) {
1499
1792
  function handleReadPhaseAnswers(input) {
1500
1793
  const cwd = input._cwd ?? process.cwd();
1501
1794
  const filePath = join2(cwd, ".stackwright", "answers", `${input.phase}.json`);
1502
- if (!existsSync2(filePath)) {
1795
+ if (!existsSync3(filePath)) {
1503
1796
  return {
1504
1797
  text: JSON.stringify({ missing: true, phase: input.phase }),
1505
1798
  isError: false
@@ -1531,13 +1824,63 @@ function handleGetOtterName(input) {
1531
1824
  isError: false
1532
1825
  };
1533
1826
  }
1827
+ function handleSaveBuildContext(input) {
1828
+ const cwd = input._cwd ?? process.cwd();
1829
+ const dir = join2(cwd, ".stackwright");
1830
+ const filePath = join2(dir, "build-context.json");
1831
+ try {
1832
+ mkdirSync2(dir, { recursive: true });
1833
+ if (existsSync3(filePath)) {
1834
+ const stat = lstatSync3(filePath);
1835
+ if (stat.isSymbolicLink()) {
1836
+ return {
1837
+ text: JSON.stringify({
1838
+ success: false,
1839
+ error: `Refusing to write to symlink: ${filePath}`
1840
+ }),
1841
+ isError: true
1842
+ };
1843
+ }
1844
+ }
1845
+ const payload = {
1846
+ version: "1.0",
1847
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
1848
+ buildContext: input.buildContext
1849
+ };
1850
+ writeFileSync2(filePath, JSON.stringify(payload, null, 2) + "\n");
1851
+ return {
1852
+ text: JSON.stringify({ success: true, path: filePath }),
1853
+ isError: false
1854
+ };
1855
+ } catch (err) {
1856
+ const message = err instanceof Error ? err.message : String(err);
1857
+ return {
1858
+ text: JSON.stringify({ success: false, error: message }),
1859
+ isError: true
1860
+ };
1861
+ }
1862
+ }
1534
1863
  function registerOrchestrationTools(server2) {
1864
+ server2.tool(
1865
+ "stackwright_pro_save_build_context",
1866
+ `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.`,
1867
+ {
1868
+ buildContext: z9.string().describe("Free-text description of what the user wants to build")
1869
+ },
1870
+ async ({ buildContext }) => {
1871
+ const { text, isError } = handleSaveBuildContext({ buildContext });
1872
+ return {
1873
+ content: [{ type: "text", text }],
1874
+ isError
1875
+ };
1876
+ }
1877
+ );
1535
1878
  server2.tool(
1536
1879
  "stackwright_pro_parse_otter_response",
1537
1880
  "Parse and validate a specialist otter's QUESTION_COLLECTION_MODE JSON response. Handles JSON extraction from LLM responses (strips markdown, fixes single quotes, trailing commas). Detects the phase from the otter name. Use this immediately after invoke_agent() to get a validated manifest phase object.",
1538
1881
  {
1539
- otterName: z8.string().describe('The agent name, e.g. "stackwright-pro-api-otter"'),
1540
- responseText: z8.string().describe("Raw text response from the otter's QUESTION_COLLECTION_MODE invocation")
1882
+ otterName: z9.string().describe('The agent name, e.g. "stackwright-pro-api-otter"'),
1883
+ responseText: z9.string().describe("Raw text response from the otter's QUESTION_COLLECTION_MODE invocation")
1541
1884
  },
1542
1885
  async ({ otterName, responseText }) => {
1543
1886
  const { result, isError } = handleParseOtterResponse({ otterName, responseText });
@@ -1551,16 +1894,18 @@ function registerOrchestrationTools(server2) {
1551
1894
  "stackwright_pro_save_manifest",
1552
1895
  "Write the question manifest to .stackwright/question-manifest.json. Call this after collecting and parsing questions from all otters via stackwright_pro_parse_otter_response.",
1553
1896
  {
1554
- phases: z8.array(
1555
- z8.object({
1556
- phase: z8.string(),
1557
- otter: z8.string(),
1558
- questions: z8.array(z8.any()),
1559
- requiredPackages: z8.object({
1560
- dependencies: z8.record(z8.string(), z8.string()).optional(),
1561
- devPackages: z8.record(z8.string(), z8.string()).optional()
1562
- }).optional()
1563
- })
1897
+ phases: jsonCoerce(
1898
+ z9.array(
1899
+ z9.object({
1900
+ phase: z9.string(),
1901
+ otter: z9.string(),
1902
+ questions: z9.array(z9.any()),
1903
+ requiredPackages: z9.object({
1904
+ dependencies: z9.record(z9.string(), z9.string()).optional(),
1905
+ devPackages: z9.record(z9.string(), z9.string()).optional()
1906
+ }).optional()
1907
+ })
1908
+ )
1564
1909
  ).describe("Array of parsed phase objects from stackwright_pro_parse_otter_response")
1565
1910
  },
1566
1911
  async ({ phases }) => {
@@ -1575,15 +1920,37 @@ function registerOrchestrationTools(server2) {
1575
1920
  "stackwright_pro_save_phase_answers",
1576
1921
  "Save user answers for a phase to .stackwright/answers/{phase}.json. Pass rawAnswers directly from ask_user_question and the original manifest questions for label-to-value reverse mapping.",
1577
1922
  {
1578
- phase: z8.string().describe('Phase name, e.g. "designer"'),
1579
- rawAnswers: z8.array(
1580
- z8.object({
1581
- question_header: z8.string(),
1582
- selected_options: z8.array(z8.string()),
1583
- other_text: z8.string().nullable().optional()
1584
- })
1585
- ).describe("Answers as returned by ask_user_question"),
1586
- questions: z8.array(z8.any()).optional().describe("Original manifest questions for label\u2192value reverse-mapping")
1923
+ phase: z9.string().describe('Phase name, e.g. "designer"'),
1924
+ rawAnswers: jsonCoerce(
1925
+ z9.array(
1926
+ z9.object({
1927
+ question_header: z9.string().min(1, "question_header must not be empty"),
1928
+ selected_options: z9.array(z9.string()).min(1, "selected_options must have at least one entry"),
1929
+ other_text: z9.string().nullable().optional()
1930
+ })
1931
+ )
1932
+ ).describe(
1933
+ "Answers as returned by ask_user_question \u2014 pass the native array, not a JSON string"
1934
+ ),
1935
+ questions: jsonCoerce(
1936
+ z9.array(
1937
+ z9.object({
1938
+ id: z9.string(),
1939
+ question: z9.string(),
1940
+ type: z9.string(),
1941
+ options: z9.array(z9.object({ label: z9.string(), value: z9.string() })).optional(),
1942
+ required: z9.boolean().optional(),
1943
+ default: z9.union([z9.string(), z9.boolean(), z9.array(z9.string())]).optional(),
1944
+ help: z9.string().optional(),
1945
+ dependsOn: z9.object({
1946
+ questionId: z9.string(),
1947
+ value: z9.union([z9.string(), z9.array(z9.string())])
1948
+ }).optional()
1949
+ }).passthrough()
1950
+ ).optional()
1951
+ ).describe(
1952
+ "Original manifest questions for label\u2192value reverse-mapping \u2014 pass the native array, not a JSON string"
1953
+ )
1587
1954
  },
1588
1955
  async ({ phase, rawAnswers, questions }) => {
1589
1956
  const { text, isError } = handleSavePhaseAnswers({
@@ -1601,7 +1968,7 @@ function registerOrchestrationTools(server2) {
1601
1968
  "stackwright_pro_read_phase_answers",
1602
1969
  "Read saved answers for a phase from .stackwright/answers/{phase}.json. Returns { missing: true } when no answers exist yet \u2014 use this to skip phases safely in the execution loop.",
1603
1970
  {
1604
- phase: z8.string().describe('Phase name, e.g. "designer"')
1971
+ phase: z9.string().describe('Phase name, e.g. "designer"')
1605
1972
  },
1606
1973
  async ({ phase }) => {
1607
1974
  const { text, isError } = handleReadPhaseAnswers({ phase });
@@ -1615,7 +1982,7 @@ function registerOrchestrationTools(server2) {
1615
1982
  "stackwright_pro_get_otter_name",
1616
1983
  "Get the agent name for a phase (e.g. 'designer' \u2192 'stackwright-pro-designer-otter'). Use this in the execution loop to invoke the correct specialist otter without hardcoding names in the prompt.",
1617
1984
  {
1618
- phase: z8.string().describe('Phase name, e.g. "designer", "api", "pages"')
1985
+ phase: z9.string().describe('Phase name, e.g. "designer", "api", "pages"')
1619
1986
  },
1620
1987
  async ({ phase }) => {
1621
1988
  const { text, isError } = handleGetOtterName({ phase });
@@ -1628,53 +1995,777 @@ function registerOrchestrationTools(server2) {
1628
1995
  }
1629
1996
 
1630
1997
  // src/tools/pipeline.ts
1631
- import { z as z9 } from "zod";
1632
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, existsSync as existsSync3, mkdirSync as mkdirSync2, lstatSync as lstatSync3 } from "fs";
1998
+ import { z as z13 } from "zod";
1999
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync4, existsSync as existsSync5, mkdirSync as mkdirSync4, lstatSync as lstatSync5 } from "fs";
2000
+ import { join as join4 } from "path";
2001
+ import { createHash as createHash3 } from "crypto";
2002
+
2003
+ // src/artifact-signing.ts
2004
+ import {
2005
+ createHash as createHash2,
2006
+ generateKeyPairSync,
2007
+ createPublicKey,
2008
+ createPrivateKey,
2009
+ sign,
2010
+ verify,
2011
+ timingSafeEqual
2012
+ } from "crypto";
2013
+ import {
2014
+ readFileSync as readFileSync3,
2015
+ writeFileSync as writeFileSync3,
2016
+ existsSync as existsSync4,
2017
+ mkdirSync as mkdirSync3,
2018
+ lstatSync as lstatSync4,
2019
+ unlinkSync,
2020
+ readdirSync
2021
+ } from "fs";
1633
2022
  import { join as join3 } from "path";
1634
- var PHASE_ORDER = [
1635
- "designer",
1636
- "theme",
1637
- "api",
1638
- "auth",
1639
- "data",
1640
- "pages",
1641
- "dashboard",
1642
- "workflow"
1643
- ];
1644
- var PHASE_DEPENDENCIES = {
1645
- designer: [],
1646
- theme: ["designer"],
1647
- api: [],
1648
- auth: [],
1649
- data: ["api"],
1650
- pages: ["designer", "theme", "api", "data", "auth"],
1651
- dashboard: ["designer", "theme", "api", "data"],
1652
- workflow: ["auth"]
1653
- };
1654
- var PHASE_ARTIFACT = {
1655
- designer: "design-language.json",
1656
- theme: "theme-tokens.json",
1657
- api: "api-config.json",
1658
- auth: "auth-config.json",
1659
- data: "data-config.json",
1660
- pages: "pages-manifest.json",
1661
- dashboard: "dashboard-manifest.json",
1662
- workflow: "workflow-config.json"
1663
- };
1664
- var PHASE_TO_OTTER2 = {
1665
- designer: "stackwright-pro-designer-otter",
1666
- theme: "stackwright-pro-theme-otter",
1667
- api: "stackwright-pro-api-otter",
1668
- auth: "stackwright-pro-auth-otter",
1669
- data: "stackwright-pro-data-otter",
1670
- pages: "stackwright-pro-page-otter",
1671
- dashboard: "stackwright-pro-dashboard-otter",
1672
- workflow: "stackwright-pro-workflow-otter"
1673
- };
1674
- function isValidPhase(phase) {
1675
- return PHASE_ORDER.includes(phase);
1676
- }
1677
- function defaultPhaseStatus() {
2023
+ import { z as z10 } from "zod";
2024
+ var ALGORITHM = "ECDSA-P384-SHA384";
2025
+ var KEY_FILE = "pipeline-keys.json";
2026
+ var KEY_DIR = ".stackwright";
2027
+ var SIGNATURE_MANIFEST = "signatures.json";
2028
+ var ARTIFACTS_DIR = ".stackwright/artifacts";
2029
+ function rejectSymlink(filePath, context) {
2030
+ if (!existsSync4(filePath)) return;
2031
+ const stat = lstatSync4(filePath);
2032
+ if (stat.isSymbolicLink()) {
2033
+ throw new Error(`Security: refusing to follow symlink at ${context}: ${filePath}`);
2034
+ }
2035
+ }
2036
+ function computeSha384(data) {
2037
+ return createHash2("sha384").update(data).digest("hex");
2038
+ }
2039
+ function safeDigestEqual(a, b) {
2040
+ if (a.length !== b.length) return false;
2041
+ return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
2042
+ }
2043
+ function emptyManifest() {
2044
+ return {
2045
+ version: "1.0",
2046
+ algorithm: ALGORITHM,
2047
+ signatures: {}
2048
+ };
2049
+ }
2050
+ function initPipelineKeys(cwd) {
2051
+ const keyDir = join3(cwd, KEY_DIR);
2052
+ const keyPath = join3(keyDir, KEY_FILE);
2053
+ rejectSymlink(keyPath, "pipeline-keys.json");
2054
+ mkdirSync3(keyDir, { recursive: true });
2055
+ const { publicKey, privateKey } = generateKeyPairSync("ec", {
2056
+ namedCurve: "P-384"
2057
+ });
2058
+ const publicKeyPem = publicKey.export({ type: "spki", format: "pem" });
2059
+ const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" });
2060
+ const fingerprint = createHash2("sha256").update(publicKeyPem).digest("hex");
2061
+ const keyFile = {
2062
+ version: "1.0",
2063
+ algorithm: ALGORITHM,
2064
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2065
+ publicKeyPem,
2066
+ privateKeyPem
2067
+ };
2068
+ writeFileSync3(keyPath, JSON.stringify(keyFile, null, 2), { encoding: "utf-8" });
2069
+ return { publicKeyPem, fingerprint };
2070
+ }
2071
+ function loadPipelineKeys(cwd) {
2072
+ const keyPath = join3(cwd, KEY_DIR, KEY_FILE);
2073
+ rejectSymlink(keyPath, "pipeline-keys.json");
2074
+ if (!existsSync4(keyPath)) {
2075
+ throw new Error("Pipeline keys not found \u2014 call initPipelineKeys() first");
2076
+ }
2077
+ let raw;
2078
+ try {
2079
+ raw = readFileSync3(keyPath, "utf-8");
2080
+ } catch (err) {
2081
+ const msg = err instanceof Error ? err.message : String(err);
2082
+ throw new Error(`Cannot read pipeline keys: ${msg}`, { cause: err });
2083
+ }
2084
+ let parsed;
2085
+ try {
2086
+ parsed = JSON.parse(raw);
2087
+ } catch {
2088
+ throw new Error("Pipeline keys file is not valid JSON");
2089
+ }
2090
+ if (typeof parsed.publicKeyPem !== "string" || !parsed.publicKeyPem.includes("-----BEGIN PUBLIC KEY-----")) {
2091
+ throw new Error("Invalid public key PEM in pipeline keys file");
2092
+ }
2093
+ if (typeof parsed.privateKeyPem !== "string" || !parsed.privateKeyPem.includes("-----BEGIN")) {
2094
+ throw new Error("Invalid private key PEM in pipeline keys file");
2095
+ }
2096
+ const publicKey = createPublicKey(parsed.publicKeyPem);
2097
+ const privateKey = createPrivateKey(parsed.privateKeyPem);
2098
+ return { privateKey, publicKey };
2099
+ }
2100
+ function signArtifact(artifactBytes, privateKey) {
2101
+ const digest = computeSha384(artifactBytes);
2102
+ const sig = sign("SHA384", artifactBytes, privateKey);
2103
+ return {
2104
+ digest,
2105
+ signature: sig.toString("base64"),
2106
+ algorithm: ALGORITHM,
2107
+ signedAt: (/* @__PURE__ */ new Date()).toISOString()
2108
+ };
2109
+ }
2110
+ function verifyArtifact(artifactBytes, signature, publicKey) {
2111
+ const sigValid = verify(
2112
+ "SHA384",
2113
+ artifactBytes,
2114
+ publicKey,
2115
+ Buffer.from(signature.signature, "base64")
2116
+ );
2117
+ if (!sigValid) return false;
2118
+ const actualDigest = computeSha384(artifactBytes);
2119
+ return safeDigestEqual(actualDigest, signature.digest);
2120
+ }
2121
+ function loadSignatureManifest(cwd) {
2122
+ const manifestPath = join3(cwd, ARTIFACTS_DIR, SIGNATURE_MANIFEST);
2123
+ rejectSymlink(manifestPath, "signatures.json");
2124
+ if (!existsSync4(manifestPath)) return emptyManifest();
2125
+ let raw;
2126
+ try {
2127
+ raw = readFileSync3(manifestPath, "utf-8");
2128
+ } catch (err) {
2129
+ const msg = err instanceof Error ? err.message : String(err);
2130
+ throw new Error(`Cannot read signature manifest: ${msg}`, { cause: err });
2131
+ }
2132
+ try {
2133
+ const parsed = JSON.parse(raw);
2134
+ if (parsed.version !== "1.0" || typeof parsed.signatures !== "object") {
2135
+ throw new Error("Malformed signature manifest: invalid version or missing signatures object");
2136
+ }
2137
+ return parsed;
2138
+ } catch (err) {
2139
+ if (err instanceof Error && err.message.startsWith("Malformed")) throw err;
2140
+ throw new Error("Signature manifest is not valid JSON", { cause: err });
2141
+ }
2142
+ }
2143
+ function saveArtifactSignature(cwd, artifactFilename, sig, signerOtter) {
2144
+ const artifactsDir = join3(cwd, ARTIFACTS_DIR);
2145
+ const manifestPath = join3(artifactsDir, SIGNATURE_MANIFEST);
2146
+ rejectSymlink(manifestPath, "signatures.json (save)");
2147
+ mkdirSync3(artifactsDir, { recursive: true });
2148
+ const manifest = loadSignatureManifest(cwd);
2149
+ manifest.signatures[artifactFilename] = {
2150
+ ...sig,
2151
+ signedBy: signerOtter
2152
+ };
2153
+ writeFileSync3(manifestPath, JSON.stringify(manifest, null, 2), { encoding: "utf-8" });
2154
+ }
2155
+ function getArtifactSignature(cwd, artifactFilename) {
2156
+ const manifest = loadSignatureManifest(cwd);
2157
+ const entry = manifest.signatures[artifactFilename];
2158
+ if (!entry) return null;
2159
+ return {
2160
+ digest: entry.digest,
2161
+ signature: entry.signature,
2162
+ algorithm: entry.algorithm,
2163
+ signedAt: entry.signedAt
2164
+ };
2165
+ }
2166
+ function emitSignatureAuditEvent(params) {
2167
+ const record = JSON.stringify({
2168
+ level: "AUDIT",
2169
+ event: "ARTIFACT_SIGNATURE_FAIL",
2170
+ timestamp: params.timestamp,
2171
+ source: params.source,
2172
+ artifactFilename: params.artifactFilename,
2173
+ expectedDigest: params.expectedDigest,
2174
+ actualDigest: params.actualDigest,
2175
+ phase: params.phase
2176
+ });
2177
+ process.stderr.write(`ARTIFACT_SIGNATURE_FAIL ${record}
2178
+ `);
2179
+ }
2180
+ function registerArtifactSigningTools(server2) {
2181
+ server2.tool(
2182
+ "stackwright_pro_verify_artifact_signatures",
2183
+ "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.",
2184
+ {
2185
+ cwd: z10.string().optional().describe("Project root directory. Defaults to process.cwd().")
2186
+ },
2187
+ async ({ cwd: cwdParam }) => {
2188
+ const cwd = cwdParam ?? process.cwd();
2189
+ let publicKey;
2190
+ try {
2191
+ const keys = loadPipelineKeys(cwd);
2192
+ publicKey = keys.publicKey;
2193
+ } catch (err) {
2194
+ const msg = err instanceof Error ? err.message : String(err);
2195
+ return {
2196
+ content: [
2197
+ {
2198
+ type: "text",
2199
+ text: JSON.stringify({
2200
+ error: true,
2201
+ message: `Cannot load pipeline keys: ${msg}`
2202
+ })
2203
+ }
2204
+ ],
2205
+ isError: true
2206
+ };
2207
+ }
2208
+ let manifest;
2209
+ try {
2210
+ manifest = loadSignatureManifest(cwd);
2211
+ } catch (err) {
2212
+ const msg = err instanceof Error ? err.message : String(err);
2213
+ return {
2214
+ content: [
2215
+ {
2216
+ type: "text",
2217
+ text: JSON.stringify({
2218
+ error: true,
2219
+ message: `Cannot load signature manifest: ${msg}`
2220
+ })
2221
+ }
2222
+ ],
2223
+ isError: true
2224
+ };
2225
+ }
2226
+ const artifactsPath = join3(cwd, ARTIFACTS_DIR);
2227
+ let artifactFiles = [];
2228
+ try {
2229
+ if (existsSync4(artifactsPath)) {
2230
+ artifactFiles = readdirSync(artifactsPath).filter(
2231
+ (f) => f.endsWith(".json") && f !== SIGNATURE_MANIFEST
2232
+ );
2233
+ }
2234
+ } catch {
2235
+ }
2236
+ const results = [];
2237
+ let hasFailure = false;
2238
+ for (const filename of artifactFiles) {
2239
+ const filePath = join3(artifactsPath, filename);
2240
+ try {
2241
+ rejectSymlink(filePath, `artifact ${filename}`);
2242
+ } catch {
2243
+ results.push({
2244
+ filename,
2245
+ verified: false,
2246
+ error: "Refusing to verify symlink"
2247
+ });
2248
+ hasFailure = true;
2249
+ continue;
2250
+ }
2251
+ let artifactBytes;
2252
+ try {
2253
+ artifactBytes = readFileSync3(filePath);
2254
+ } catch (err) {
2255
+ const msg = err instanceof Error ? err.message : String(err);
2256
+ results.push({
2257
+ filename,
2258
+ verified: false,
2259
+ error: `Cannot read artifact: ${msg}`
2260
+ });
2261
+ hasFailure = true;
2262
+ continue;
2263
+ }
2264
+ const entry = manifest.signatures[filename];
2265
+ if (!entry) {
2266
+ results.push({
2267
+ filename,
2268
+ verified: false,
2269
+ error: "No signature found in manifest"
2270
+ });
2271
+ hasFailure = true;
2272
+ continue;
2273
+ }
2274
+ const sig = {
2275
+ digest: entry.digest,
2276
+ signature: entry.signature,
2277
+ algorithm: entry.algorithm,
2278
+ signedAt: entry.signedAt
2279
+ };
2280
+ const verified = verifyArtifact(artifactBytes, sig, publicKey);
2281
+ if (!verified) {
2282
+ const actualDigest = computeSha384(artifactBytes);
2283
+ emitSignatureAuditEvent({
2284
+ artifactFilename: filename,
2285
+ expectedDigest: sig.digest,
2286
+ actualDigest,
2287
+ phase: entry.signedBy ?? "unknown",
2288
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2289
+ source: "stackwright_pro_verify_artifact_signatures"
2290
+ });
2291
+ results.push({
2292
+ filename,
2293
+ verified: false,
2294
+ error: `Signature verification failed \u2014 artifact may have been tampered with`,
2295
+ signedBy: entry.signedBy,
2296
+ signedAt: entry.signedAt
2297
+ });
2298
+ hasFailure = true;
2299
+ } else {
2300
+ results.push({
2301
+ filename,
2302
+ verified: true,
2303
+ signedBy: entry.signedBy,
2304
+ signedAt: entry.signedAt
2305
+ });
2306
+ }
2307
+ }
2308
+ for (const manifestFilename of Object.keys(manifest.signatures)) {
2309
+ if (!artifactFiles.includes(manifestFilename)) {
2310
+ results.push({
2311
+ filename: manifestFilename,
2312
+ verified: false,
2313
+ error: "Artifact referenced in manifest but missing from disk"
2314
+ });
2315
+ hasFailure = true;
2316
+ }
2317
+ }
2318
+ const verifiedCount = results.filter((r) => r.verified).length;
2319
+ const failedCount = results.filter((r) => !r.verified).length;
2320
+ return {
2321
+ content: [
2322
+ {
2323
+ type: "text",
2324
+ text: JSON.stringify({
2325
+ totalArtifacts: artifactFiles.length,
2326
+ verifiedCount,
2327
+ failedCount,
2328
+ results,
2329
+ ...hasFailure ? {
2330
+ error: "SIGNATURE VERIFICATION FAILED: One or more artifact signatures are invalid. Do not proceed \u2014 artifacts may have been tampered with."
2331
+ } : {}
2332
+ })
2333
+ }
2334
+ ],
2335
+ isError: hasFailure
2336
+ };
2337
+ }
2338
+ );
2339
+ }
2340
+
2341
+ // src/tools/pipeline.ts
2342
+ import { WorkflowFileSchema, authConfigSchema as authConfigSchema3 } from "@stackwright-pro/types";
2343
+
2344
+ // src/tools/get-schema.ts
2345
+ import { z as z12 } from "zod";
2346
+ import {
2347
+ WorkflowStepSchema as WorkflowStepSchema2,
2348
+ WorkflowDefinitionSchema as WorkflowDefinitionSchema2,
2349
+ WorkflowFieldSchema as WorkflowFieldSchema2,
2350
+ WorkflowActionSchema as WorkflowActionSchema2,
2351
+ authConfigSchema as authConfigSchema2
2352
+ } from "@stackwright-pro/types";
2353
+
2354
+ // src/tools/validate-yaml-fragment.ts
2355
+ import { z as z11 } from "zod";
2356
+ import { load as yamlLoad } from "js-yaml";
2357
+ import {
2358
+ WorkflowStepSchema,
2359
+ WorkflowDefinitionSchema,
2360
+ WorkflowFieldSchema,
2361
+ WorkflowActionSchema,
2362
+ authConfigSchema
2363
+ } from "@stackwright-pro/types";
2364
+ var SUPPORTED_SCHEMA_NAMES = [
2365
+ "workflow_step",
2366
+ "workflow_definition",
2367
+ "workflow_field",
2368
+ "workflow_action",
2369
+ "navigation_item",
2370
+ "auth_config"
2371
+ ];
2372
+ var NavigationLinkSchema = z11.lazy(
2373
+ () => z11.object({
2374
+ label: z11.string().min(1),
2375
+ href: z11.string().min(1),
2376
+ children: z11.array(NavigationLinkSchema).optional()
2377
+ })
2378
+ );
2379
+ var NavigationSectionSchema = z11.object({
2380
+ section: z11.string().min(1),
2381
+ items: z11.array(NavigationLinkSchema)
2382
+ });
2383
+ var NavigationItemSchema = z11.union([
2384
+ NavigationLinkSchema,
2385
+ NavigationSectionSchema
2386
+ ]);
2387
+ var FIELD_SYNONYMS = {
2388
+ workflow_step: {
2389
+ title: "label",
2390
+ name: "label (at step level, use label: not name:)",
2391
+ description: "message (use message: for step-level descriptive text)",
2392
+ style: 'theme.variant \u2014 use theme: { variant: "primary" } not style: "primary"',
2393
+ transitions: 'on_submit.transition \u2014 use on_submit: { transition: "next_step" } not transitions: [{then:...}]'
2394
+ },
2395
+ workflow_definition: {
2396
+ title: "label",
2397
+ name: "label (workflow-level label, not name:)",
2398
+ description: "description is valid here \u2014 but message: is not (that is a step field)",
2399
+ type: "id (workflows are identified by id:, not type:)"
2400
+ },
2401
+ workflow_field: {
2402
+ id: "name (field-level identifier is name:, NOT id:)",
2403
+ title: "label (field display text is label:, NOT title:)",
2404
+ description: "placeholder or label (no description field on WorkflowField)"
2405
+ },
2406
+ workflow_action: {
2407
+ style: 'theme.variant \u2014 use theme: { variant: "primary" } not style: "primary"',
2408
+ then: "transition (action-level next-step is transition:, NOT then:)",
2409
+ on_click: 'action: "service:..." (extract the service reference from on_click.action)',
2410
+ title: "label (action display text is label:, NOT title:)",
2411
+ name: "label (action display text is label:, NOT name:)"
2412
+ },
2413
+ navigation_item: {
2414
+ children: "items (NavigationSection uses items: not children: \u2014 also use section: instead of label: for section headers)",
2415
+ label: 'section (if this is a nav group/section, use section: "Title" and items: [...], not label:)',
2416
+ title: "section (NavigationSection header field is section:, NOT title:)"
2417
+ },
2418
+ auth_config: {
2419
+ method: 'type \u2014 auth config discriminates on type: "oidc" | "pki", NOT method:',
2420
+ provider_type: 'type \u2014 use type: "oidc" or type: "pki"',
2421
+ strategy: "type \u2014 top-level discriminator is type:, not strategy:"
2422
+ }
2423
+ };
2424
+ function getSchema(name) {
2425
+ switch (name) {
2426
+ case "workflow_step":
2427
+ return WorkflowStepSchema;
2428
+ case "workflow_definition":
2429
+ return WorkflowDefinitionSchema;
2430
+ case "workflow_field":
2431
+ return WorkflowFieldSchema;
2432
+ case "workflow_action":
2433
+ return WorkflowActionSchema;
2434
+ case "navigation_item":
2435
+ return NavigationItemSchema;
2436
+ case "auth_config":
2437
+ return authConfigSchema;
2438
+ }
2439
+ }
2440
+ function enrichErrors(issues, synonyms) {
2441
+ return issues.map((issue) => {
2442
+ const pathStr = issue.path.join(".");
2443
+ const lastSegment = issue.path[issue.path.length - 1];
2444
+ const fieldName = typeof lastSegment === "string" ? lastSegment : void 0;
2445
+ const didYouMean = fieldName ? synonyms[fieldName] : void 0;
2446
+ return {
2447
+ path: pathStr || "(root)",
2448
+ message: issue.message,
2449
+ ...didYouMean ? { didYouMean } : {}
2450
+ };
2451
+ });
2452
+ }
2453
+ function handleValidateYamlFragment(input) {
2454
+ const { schemaName, yaml } = input;
2455
+ if (!SUPPORTED_SCHEMA_NAMES.includes(schemaName)) {
2456
+ return {
2457
+ valid: false,
2458
+ parseError: `Unknown schemaName: "${schemaName}". Supported: ${SUPPORTED_SCHEMA_NAMES.join(", ")}`
2459
+ };
2460
+ }
2461
+ const name = schemaName;
2462
+ let parsed;
2463
+ try {
2464
+ parsed = yamlLoad(yaml);
2465
+ } catch (err) {
2466
+ return {
2467
+ valid: false,
2468
+ parseError: `YAML parse error: ${err instanceof Error ? err.message : String(err)}`
2469
+ };
2470
+ }
2471
+ const schema = getSchema(name);
2472
+ const result = schema.safeParse(parsed);
2473
+ if (result.success) {
2474
+ return { valid: true };
2475
+ }
2476
+ const synonyms = FIELD_SYNONYMS[name];
2477
+ const errors = enrichErrors(result.error.issues, synonyms);
2478
+ return { valid: false, errors };
2479
+ }
2480
+ function registerValidateYamlFragmentTool(server2) {
2481
+ server2.tool(
2482
+ "stackwright_pro_validate_yaml_fragment",
2483
+ '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.',
2484
+ {
2485
+ schemaName: z11.enum(SUPPORTED_SCHEMA_NAMES).describe(
2486
+ "Schema to validate against. One of: workflow_step, workflow_definition, workflow_field, workflow_action, navigation_item, auth_config"
2487
+ ),
2488
+ yaml: z11.string().describe("YAML string to validate (can also be JSON \u2014 js-yaml parses both)")
2489
+ },
2490
+ async ({ schemaName, yaml }) => {
2491
+ const result = handleValidateYamlFragment({ schemaName, yaml });
2492
+ return {
2493
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
2494
+ };
2495
+ }
2496
+ );
2497
+ }
2498
+
2499
+ // src/tools/get-schema.ts
2500
+ var NavigationLinkSchema2 = z12.lazy(
2501
+ () => z12.object({
2502
+ label: z12.string().min(1),
2503
+ href: z12.string().min(1),
2504
+ children: z12.array(NavigationLinkSchema2).optional()
2505
+ })
2506
+ );
2507
+ var NavigationSectionSchema2 = z12.object({
2508
+ section: z12.string().min(1),
2509
+ items: z12.array(NavigationLinkSchema2)
2510
+ });
2511
+ var NavigationItemSchema2 = z12.union([
2512
+ NavigationLinkSchema2,
2513
+ NavigationSectionSchema2
2514
+ ]);
2515
+ function getZodSchema(name) {
2516
+ switch (name) {
2517
+ case "workflow_step":
2518
+ return WorkflowStepSchema2;
2519
+ case "workflow_definition":
2520
+ return WorkflowDefinitionSchema2;
2521
+ case "workflow_field":
2522
+ return WorkflowFieldSchema2;
2523
+ case "workflow_action":
2524
+ return WorkflowActionSchema2;
2525
+ case "navigation_item":
2526
+ return NavigationItemSchema2;
2527
+ case "auth_config":
2528
+ return authConfigSchema2;
2529
+ }
2530
+ }
2531
+ function formatType(node, depth = 0) {
2532
+ if (node.const !== void 0) return JSON.stringify(node.const);
2533
+ if (node.enum) return node.enum.map((v) => JSON.stringify(v)).join(" | ");
2534
+ if (node.oneOf || node.anyOf) {
2535
+ const branches = node.oneOf ?? node.anyOf ?? [];
2536
+ return branches.map((b) => {
2537
+ const disc = b.properties ? Object.entries(b.properties).filter(([, v]) => v.const !== void 0).map(([k, v]) => `${k}: ${JSON.stringify(v.const)}`).join(", ") : "";
2538
+ return disc ? `{ ${disc}, ... }` : "{ ... }";
2539
+ }).join(" | ");
2540
+ }
2541
+ if (node.type === "array" && node.items) {
2542
+ return `${formatType(node.items, depth)}[]`;
2543
+ }
2544
+ if (node.type === "object" && node.properties && depth < 2) {
2545
+ const inner = Object.entries(node.properties).map(([k, v]) => `${k}: ${formatType(v, depth + 1)}`).join(", ");
2546
+ return `{ ${inner} }`;
2547
+ }
2548
+ const base = Array.isArray(node.type) ? node.type.join(" | ") : node.type ?? "unknown";
2549
+ const constraints = [];
2550
+ if (node.maxLength !== void 0) constraints.push(`max ${node.maxLength} chars`);
2551
+ if (node.minLength !== void 0) constraints.push(`min ${node.minLength} chars`);
2552
+ if (node.pattern) constraints.push(`pattern: ${node.pattern}`);
2553
+ if (node.minimum !== void 0) constraints.push(`min ${node.minimum}`);
2554
+ if (node.maximum !== void 0) constraints.push(`max ${node.maximum}`);
2555
+ return constraints.length > 0 ? `${base} (${constraints.join(", ")})` : base;
2556
+ }
2557
+ function formatObjectSchema(node, schemaName, synonyms) {
2558
+ const lines = [];
2559
+ const displayName = schemaName.split("_").map((w) => w[0].toUpperCase() + w.slice(1)).join("");
2560
+ lines.push(`${displayName}:`);
2561
+ if (node.oneOf || node.anyOf) {
2562
+ const branches = node.oneOf ?? node.anyOf ?? [];
2563
+ lines.push(" Discriminated union \u2014 choose one variant:");
2564
+ for (const branch of branches) {
2565
+ const req = new Set(branch.required ?? []);
2566
+ const disc = Object.entries(branch.properties ?? {}).filter(([, v]) => v.const !== void 0).map(([k, v]) => `${k}: ${JSON.stringify(v.const)}`).join(", ");
2567
+ lines.push(` VARIANT (${disc}):`);
2568
+ for (const [field, fieldNode] of Object.entries(branch.properties ?? {})) {
2569
+ if (fieldNode.const !== void 0) continue;
2570
+ const isRequired = req.has(field);
2571
+ const hint = synonyms[field] ? ` -- WARNING: use ${field}: not ${synonyms[field]}` : "";
2572
+ lines.push(
2573
+ ` ${isRequired ? "REQUIRED" : "optional"}: ${field}: ${formatType(fieldNode)}${hint}`
2574
+ );
2575
+ }
2576
+ }
2577
+ return lines.join("\n");
2578
+ }
2579
+ const required = new Set(node.required ?? []);
2580
+ const properties = node.properties ?? {};
2581
+ const requiredFields = Object.entries(properties).filter(([k]) => required.has(k));
2582
+ const optionalFields = Object.entries(properties).filter(([k]) => !required.has(k));
2583
+ if (requiredFields.length > 0) {
2584
+ lines.push(" REQUIRED:");
2585
+ for (const [field, fieldNode] of requiredFields) {
2586
+ const typeStr = formatType(fieldNode);
2587
+ const warn = synonyms[field] ? ` -- CAUTION: this schema uses ${field}` : "";
2588
+ lines.push(` ${field}: ${typeStr}${warn}`);
2589
+ }
2590
+ }
2591
+ if (optionalFields.length > 0) {
2592
+ lines.push(" OPTIONAL:");
2593
+ for (const [field, fieldNode] of optionalFields) {
2594
+ const typeStr = formatType(fieldNode);
2595
+ lines.push(` ${field}: ${typeStr}`);
2596
+ }
2597
+ }
2598
+ return lines.join("\n");
2599
+ }
2600
+ function handleGetSchema(input) {
2601
+ const { schemaName } = input;
2602
+ if (!SUPPORTED_SCHEMA_NAMES.includes(schemaName)) {
2603
+ return {
2604
+ error: `Unknown schemaName: "${schemaName}". Supported: ${SUPPORTED_SCHEMA_NAMES.join(", ")}`
2605
+ };
2606
+ }
2607
+ const name = schemaName;
2608
+ const schema = getZodSchema(name);
2609
+ const synonyms = FIELD_SYNONYMS[name];
2610
+ let jsonSchema;
2611
+ try {
2612
+ const raw = z12.toJSONSchema(schema, { unrepresentable: "any" });
2613
+ jsonSchema = raw;
2614
+ } catch {
2615
+ jsonSchema = { type: "object", description: "Schema introspection unavailable for this type" };
2616
+ }
2617
+ const summary = formatObjectSchema(jsonSchema, name, synonyms);
2618
+ const synonymWarnings = Object.entries(synonyms).map(
2619
+ ([wrong, correct]) => ` WARNING: use "${correct}" \u2014 NOT "${wrong}"`
2620
+ );
2621
+ const fullText = [
2622
+ summary,
2623
+ "",
2624
+ "FIELD NAME WARNINGS (common drift patterns):",
2625
+ ...synonymWarnings
2626
+ ].join("\n");
2627
+ const tokenEstimate = Math.ceil(fullText.length / 4);
2628
+ return {
2629
+ schemaName: name,
2630
+ summary,
2631
+ synonymWarnings,
2632
+ tokenEstimate
2633
+ };
2634
+ }
2635
+ var PHASE_SCHEMA_NAMES = {
2636
+ workflow: ["workflow_step", "workflow_definition", "workflow_field", "workflow_action"],
2637
+ pages: ["navigation_item"],
2638
+ dashboard: ["navigation_item"],
2639
+ polish: ["navigation_item"],
2640
+ auth: ["auth_config"]
2641
+ };
2642
+ function buildSchemaReferenceBlock(phase) {
2643
+ const schemaNames = PHASE_SCHEMA_NAMES[phase];
2644
+ if (!schemaNames || schemaNames.length === 0) return null;
2645
+ const sections = [
2646
+ "CANONICAL_SCHEMA_REFERENCE (authoritative \u2014 use exact field names below):",
2647
+ ""
2648
+ ];
2649
+ for (const name of schemaNames) {
2650
+ const result = handleGetSchema({ schemaName: name });
2651
+ if ("error" in result) continue;
2652
+ sections.push(result.summary);
2653
+ if (result.synonymWarnings.length > 0) {
2654
+ sections.push(" Common mistakes to avoid:");
2655
+ sections.push(...result.synonymWarnings);
2656
+ }
2657
+ sections.push("");
2658
+ }
2659
+ return sections.join("\n");
2660
+ }
2661
+ function registerGetSchemaTool(server2) {
2662
+ server2.tool(
2663
+ "stackwright_pro_get_schema",
2664
+ '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.',
2665
+ {
2666
+ schemaName: z12.enum(SUPPORTED_SCHEMA_NAMES).describe(
2667
+ "Schema to summarize. One of: workflow_step, workflow_definition, workflow_field, workflow_action, navigation_item, auth_config"
2668
+ )
2669
+ },
2670
+ async ({ schemaName }) => {
2671
+ const result = handleGetSchema({ schemaName });
2672
+ if ("error" in result) {
2673
+ return {
2674
+ content: [{ type: "text", text: JSON.stringify({ error: result.error }) }],
2675
+ isError: true
2676
+ };
2677
+ }
2678
+ return {
2679
+ content: [
2680
+ {
2681
+ type: "text",
2682
+ text: JSON.stringify(result, null, 2)
2683
+ }
2684
+ ]
2685
+ };
2686
+ }
2687
+ );
2688
+ }
2689
+
2690
+ // src/tools/pipeline.ts
2691
+ var PHASE_ORDER = [
2692
+ "designer",
2693
+ "theme",
2694
+ "scaffold",
2695
+ // generates app/ directory from config
2696
+ "api",
2697
+ "data",
2698
+ "geo",
2699
+ "workflow",
2700
+ "services",
2701
+ "pages",
2702
+ "dashboard",
2703
+ "auth",
2704
+ "polish"
2705
+ ];
2706
+ var PHASE_DEPENDENCIES = {
2707
+ designer: [],
2708
+ theme: ["designer"],
2709
+ scaffold: ["designer", "theme"],
2710
+ // needs stackwright.yml + theme-tokens
2711
+ api: [],
2712
+ data: ["api"],
2713
+ geo: ["data"],
2714
+ // workflow: no hard deps — uses service: references with Prism mock fallback
2715
+ // when API artifacts aren't available; roles come from user answers
2716
+ workflow: [],
2717
+ // services: needs API endpoints to know what to wire, and optionally
2718
+ // workflow states as trigger sources. Produces OpenAPI specs consumed
2719
+ // by pages and dashboard for typed data wiring.
2720
+ services: ["api", "workflow"],
2721
+ // pages/dashboard: depend on services for typed endpoint wiring (OpenAPI
2722
+ // specs) and on geo so the specialist prompt includes geo-manifest.json
2723
+ // — page/dashboard otters see which page slugs are already claimed and
2724
+ // won't attempt to overwrite them (swp-73c). 'api' is still transitive
2725
+ // through 'data'; auth removed — page-otter has graceful fallback.
2726
+ pages: ["designer", "theme", "data", "services", "geo", "scaffold"],
2727
+ dashboard: ["designer", "theme", "data", "services", "geo", "scaffold"],
2728
+ // auth is the penultimate phase — runs after all content-producing phases
2729
+ // so it can read pages, dashboard, workflow, and geo artifacts for route
2730
+ // protection and RBAC wiring. Skipped upstream phases still satisfy deps
2731
+ // (the foreman marks them executed=true), so auth always runs.
2732
+ auth: ["pages", "dashboard", "workflow", "geo"],
2733
+ // polish is the terminal phase — runs after auth so the landing page and
2734
+ // nav reflect the final set of protected routes and all generated pages.
2735
+ polish: ["auth"]
2736
+ };
2737
+ var PHASE_ARTIFACT = {
2738
+ designer: "design-language.json",
2739
+ theme: "theme-tokens.json",
2740
+ scaffold: "scaffold-manifest.json",
2741
+ api: "api-config.json",
2742
+ auth: "auth-config.json",
2743
+ data: "data-config.json",
2744
+ pages: "pages-manifest.json",
2745
+ dashboard: "dashboard-manifest.json",
2746
+ workflow: "workflow-config.json",
2747
+ services: "services-config.json",
2748
+ polish: "polish-manifest.json",
2749
+ geo: "geo-manifest.json"
2750
+ };
2751
+ var PHASE_TO_OTTER2 = {
2752
+ designer: "stackwright-pro-designer-otter",
2753
+ theme: "stackwright-pro-theme-otter",
2754
+ scaffold: "stackwright-pro-scaffold-otter",
2755
+ api: "stackwright-pro-api-otter",
2756
+ auth: "stackwright-pro-auth-otter",
2757
+ data: "stackwright-pro-data-otter",
2758
+ pages: "stackwright-pro-page-otter",
2759
+ dashboard: "stackwright-pro-dashboard-otter",
2760
+ workflow: "stackwright-pro-workflow-otter",
2761
+ services: "stackwright-services-otter",
2762
+ polish: "stackwright-pro-polish-otter",
2763
+ geo: "stackwright-pro-geo-otter"
2764
+ };
2765
+ function isValidPhase2(phase) {
2766
+ return PHASE_ORDER.includes(phase);
2767
+ }
2768
+ function defaultPhaseStatus() {
1678
2769
  return {
1679
2770
  questionsCollected: false,
1680
2771
  answered: false,
@@ -1699,11 +2790,11 @@ function createDefaultState() {
1699
2790
  };
1700
2791
  }
1701
2792
  function statePath(cwd) {
1702
- return join3(cwd, ".stackwright", "pipeline-state.json");
2793
+ return join4(cwd, ".stackwright", "pipeline-state.json");
1703
2794
  }
1704
2795
  function readState(cwd) {
1705
2796
  const p = statePath(cwd);
1706
- if (!existsSync3(p)) return createDefaultState();
2797
+ if (!existsSync5(p)) return createDefaultState();
1707
2798
  const raw = JSON.parse(safeReadSync(p));
1708
2799
  if (typeof raw !== "object" || raw === null || raw.version !== "1.0") {
1709
2800
  return createDefaultState();
@@ -1711,26 +2802,26 @@ function readState(cwd) {
1711
2802
  return raw;
1712
2803
  }
1713
2804
  function safeWriteSync(filePath, content) {
1714
- if (existsSync3(filePath)) {
1715
- const stat = lstatSync3(filePath);
2805
+ if (existsSync5(filePath)) {
2806
+ const stat = lstatSync5(filePath);
1716
2807
  if (stat.isSymbolicLink()) {
1717
2808
  throw new Error(`Refusing to write to symlink: ${filePath}`);
1718
2809
  }
1719
2810
  }
1720
- writeFileSync3(filePath, content);
2811
+ writeFileSync4(filePath, content);
1721
2812
  }
1722
2813
  function safeReadSync(filePath) {
1723
- if (existsSync3(filePath)) {
1724
- const stat = lstatSync3(filePath);
2814
+ if (existsSync5(filePath)) {
2815
+ const stat = lstatSync5(filePath);
1725
2816
  if (stat.isSymbolicLink()) {
1726
2817
  throw new Error(`Refusing to read symlink: ${filePath}`);
1727
2818
  }
1728
2819
  }
1729
- return readFileSync3(filePath, "utf-8");
2820
+ return readFileSync4(filePath, "utf-8");
1730
2821
  }
1731
2822
  function writeState(cwd, state) {
1732
- const dir = join3(cwd, ".stackwright");
1733
- mkdirSync2(dir, { recursive: true });
2823
+ const dir = join4(cwd, ".stackwright");
2824
+ mkdirSync4(dir, { recursive: true });
1734
2825
  state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1735
2826
  safeWriteSync(statePath(cwd), JSON.stringify(state, null, 2) + "\n");
1736
2827
  }
@@ -1751,6 +2842,15 @@ function handleGetPipelineState(_cwd) {
1751
2842
  const cwd = _cwd ?? process.cwd();
1752
2843
  try {
1753
2844
  const state = readState(cwd);
2845
+ const keyPath = join4(cwd, ".stackwright", "pipeline-keys.json");
2846
+ if (!existsSync5(keyPath)) {
2847
+ try {
2848
+ const { fingerprint } = initPipelineKeys(cwd);
2849
+ state["signingKeyFingerprint"] = fingerprint;
2850
+ writeState(cwd, state);
2851
+ } catch {
2852
+ }
2853
+ }
1754
2854
  return { text: JSON.stringify(state), isError: false };
1755
2855
  } catch (err) {
1756
2856
  return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
@@ -1758,7 +2858,7 @@ function handleGetPipelineState(_cwd) {
1758
2858
  }
1759
2859
  function handleSetPipelineState(input) {
1760
2860
  const cwd = input._cwd ?? process.cwd();
1761
- if (input.phase && !isValidPhase(input.phase)) {
2861
+ if (input.phase && !isValidPhase2(input.phase)) {
1762
2862
  return {
1763
2863
  text: JSON.stringify({
1764
2864
  error: true,
@@ -1777,6 +2877,28 @@ function handleSetPipelineState(input) {
1777
2877
  isError: true
1778
2878
  };
1779
2879
  }
2880
+ if (input.updates && input.updates.length > 0) {
2881
+ for (const update of input.updates) {
2882
+ if (!isValidPhase2(update.phase)) {
2883
+ return {
2884
+ text: JSON.stringify({
2885
+ error: true,
2886
+ message: `Invalid phase in batch update: ${update.phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
2887
+ }),
2888
+ isError: true
2889
+ };
2890
+ }
2891
+ if (!VALID_FIELDS.includes(update.field)) {
2892
+ return {
2893
+ text: JSON.stringify({
2894
+ error: true,
2895
+ message: `Invalid field in batch update: ${update.field}. Valid fields are: ${VALID_FIELDS.join(", ")}`
2896
+ }),
2897
+ isError: true
2898
+ };
2899
+ }
2900
+ }
2901
+ }
1780
2902
  try {
1781
2903
  const state = readState(cwd);
1782
2904
  if (input.status) {
@@ -1796,34 +2918,78 @@ function handleSetPipelineState(input) {
1796
2918
  }
1797
2919
  state.currentPhase = phase;
1798
2920
  }
2921
+ if (input.updates && input.updates.length > 0) {
2922
+ for (const update of input.updates) {
2923
+ if (!state.phases[update.phase]) {
2924
+ state.phases[update.phase] = defaultPhaseStatus();
2925
+ }
2926
+ const batchPhaseState = state.phases[update.phase];
2927
+ batchPhaseState[update.field] = update.value;
2928
+ state.currentPhase = update.phase;
2929
+ }
2930
+ }
1799
2931
  writeState(cwd, state);
1800
2932
  return { text: JSON.stringify(state), isError: false };
1801
2933
  } catch (err) {
1802
2934
  return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
1803
2935
  }
1804
2936
  }
1805
- function handleCheckExecutionReady(_cwd) {
2937
+ function handleCheckExecutionReady(_cwd, phase) {
1806
2938
  const cwd = _cwd ?? process.cwd();
2939
+ if (phase) {
2940
+ if (!isValidPhase2(phase)) {
2941
+ return {
2942
+ text: JSON.stringify({
2943
+ error: true,
2944
+ message: `Invalid phase: ${phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
2945
+ }),
2946
+ isError: true
2947
+ };
2948
+ }
2949
+ const answerFile = join4(cwd, ".stackwright", "answers", `${phase}.json`);
2950
+ if (!existsSync5(answerFile)) {
2951
+ return {
2952
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file not found" }),
2953
+ isError: false
2954
+ };
2955
+ }
2956
+ try {
2957
+ const raw = safeReadSync(answerFile);
2958
+ const parsed = JSON.parse(raw);
2959
+ if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
2960
+ return {
2961
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file is malformed" }),
2962
+ isError: false
2963
+ };
2964
+ }
2965
+ return { text: JSON.stringify({ ready: true, phase }), isError: false };
2966
+ } catch {
2967
+ return {
2968
+ text: JSON.stringify({ ready: false, phase, reason: "Answer file could not be parsed" }),
2969
+ isError: false
2970
+ };
2971
+ }
2972
+ }
1807
2973
  try {
1808
- const answersDir = join3(cwd, ".stackwright", "answers");
2974
+ const answersDir = join4(cwd, ".stackwright", "answers");
1809
2975
  const answeredPhases = [];
1810
2976
  const missingPhases = [];
1811
- for (const phase of PHASE_ORDER) {
1812
- const answerFile = join3(answersDir, `${phase}.json`);
1813
- if (existsSync3(answerFile)) {
2977
+ for (const phase2 of PHASE_ORDER) {
2978
+ const answerFile = join4(answersDir, `${phase2}.json`);
2979
+ if (existsSync5(answerFile)) {
1814
2980
  try {
1815
2981
  const raw = safeReadSync(answerFile);
1816
2982
  const parsed = JSON.parse(raw);
1817
2983
  if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
1818
- missingPhases.push(phase);
2984
+ missingPhases.push(phase2);
1819
2985
  continue;
1820
2986
  }
1821
- answeredPhases.push(phase);
2987
+ answeredPhases.push(phase2);
1822
2988
  } catch {
1823
- missingPhases.push(phase);
2989
+ missingPhases.push(phase2);
1824
2990
  }
1825
2991
  } else {
1826
- missingPhases.push(phase);
2992
+ missingPhases.push(phase2);
1827
2993
  }
1828
2994
  }
1829
2995
  return {
@@ -1839,18 +3005,74 @@ function handleCheckExecutionReady(_cwd) {
1839
3005
  return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
1840
3006
  }
1841
3007
  }
3008
+ function handleGetReadyPhases(_cwd) {
3009
+ const cwd = _cwd ?? process.cwd();
3010
+ try {
3011
+ const state = readState(cwd);
3012
+ const completed = [];
3013
+ const ready = [];
3014
+ const blocked = [];
3015
+ for (const phase of PHASE_ORDER) {
3016
+ const ps = state.phases[phase];
3017
+ if (ps?.executed) {
3018
+ completed.push(phase);
3019
+ continue;
3020
+ }
3021
+ const deps = PHASE_DEPENDENCIES[phase];
3022
+ const unmetDeps = deps.filter((dep) => !state.phases[dep]?.executed);
3023
+ if (unmetDeps.length === 0) {
3024
+ ready.push(phase);
3025
+ } else {
3026
+ blocked.push(phase);
3027
+ }
3028
+ }
3029
+ return {
3030
+ text: JSON.stringify({
3031
+ readyPhases: ready,
3032
+ completedPhases: completed,
3033
+ blockedPhases: blocked,
3034
+ waveSize: ready.length,
3035
+ allComplete: ready.length === 0 && blocked.length === 0
3036
+ }),
3037
+ isError: false
3038
+ };
3039
+ } catch (err) {
3040
+ const message = err instanceof Error ? err.message : String(err);
3041
+ return { text: JSON.stringify({ error: true, message }), isError: true };
3042
+ }
3043
+ }
1842
3044
  function handleListArtifacts(_cwd) {
1843
3045
  const cwd = _cwd ?? process.cwd();
1844
3046
  try {
1845
- const artifactsDir = join3(cwd, ".stackwright", "artifacts");
3047
+ const artifactsDir = join4(cwd, ".stackwright", "artifacts");
3048
+ let manifest = null;
3049
+ try {
3050
+ manifest = loadSignatureManifest(cwd);
3051
+ } catch {
3052
+ }
1846
3053
  const artifacts = [];
1847
3054
  let completedCount = 0;
1848
3055
  for (const phase of PHASE_ORDER) {
1849
3056
  const expectedFile = PHASE_ARTIFACT[phase];
1850
- const fullPath = join3(artifactsDir, expectedFile);
1851
- const exists = existsSync3(fullPath);
3057
+ const fullPath = join4(artifactsDir, expectedFile);
3058
+ const exists = existsSync5(fullPath);
1852
3059
  if (exists) completedCount++;
1853
- artifacts.push({ phase, expectedFile, exists, path: fullPath });
3060
+ let signed = false;
3061
+ let signatureValid = null;
3062
+ if (exists && manifest) {
3063
+ const entry = manifest.signatures[expectedFile];
3064
+ if (entry) {
3065
+ signed = true;
3066
+ try {
3067
+ const rawBytes = Buffer.from(safeReadSync(fullPath), "utf-8");
3068
+ const { publicKey } = loadPipelineKeys(cwd);
3069
+ signatureValid = verifyArtifact(rawBytes, entry, publicKey);
3070
+ } catch {
3071
+ signatureValid = null;
3072
+ }
3073
+ }
3074
+ }
3075
+ artifacts.push({ phase, expectedFile, exists, path: fullPath, signed, signatureValid });
1854
3076
  }
1855
3077
  return {
1856
3078
  text: JSON.stringify({ artifacts, completedCount, totalCount: PHASE_ORDER.length }),
@@ -1863,7 +3085,7 @@ function handleListArtifacts(_cwd) {
1863
3085
  function handleWritePhaseQuestions(input) {
1864
3086
  const cwd = input._cwd ?? process.cwd();
1865
3087
  const { phase, responseText } = input;
1866
- if (!isValidPhase(phase)) {
3088
+ if (!isValidPhase2(phase)) {
1867
3089
  return {
1868
3090
  text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
1869
3091
  isError: true
@@ -1886,9 +3108,9 @@ function handleWritePhaseQuestions(input) {
1886
3108
  }
1887
3109
  } catch {
1888
3110
  }
1889
- const questionsDir = join3(cwd, ".stackwright", "questions");
1890
- mkdirSync2(questionsDir, { recursive: true });
1891
- const filePath = join3(questionsDir, `${phase}.json`);
3111
+ const questionsDir = join4(cwd, ".stackwright", "questions");
3112
+ mkdirSync4(questionsDir, { recursive: true });
3113
+ const filePath = join4(questionsDir, `${phase}.json`);
1892
3114
  const payload = {
1893
3115
  version: "1.0",
1894
3116
  phase,
@@ -1921,127 +3143,494 @@ function handleWritePhaseQuestions(input) {
1921
3143
  function handleBuildSpecialistPrompt(input) {
1922
3144
  const cwd = input._cwd ?? process.cwd();
1923
3145
  const { phase } = input;
1924
- if (!isValidPhase(phase)) {
3146
+ if (!isValidPhase2(phase)) {
1925
3147
  return {
1926
3148
  text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
1927
3149
  isError: true
1928
3150
  };
1929
3151
  }
1930
3152
  try {
1931
- const answersPath = join3(cwd, ".stackwright", "answers", `${phase}.json`);
3153
+ const answersPath = join4(cwd, ".stackwright", "answers", `${phase}.json`);
1932
3154
  let answers = {};
1933
- if (existsSync3(answersPath)) {
3155
+ if (existsSync5(answersPath)) {
1934
3156
  answers = JSON.parse(safeReadSync(answersPath));
1935
3157
  }
3158
+ let buildContextText = "";
3159
+ const buildContextPath = join4(cwd, ".stackwright", "build-context.json");
3160
+ if (existsSync5(buildContextPath)) {
3161
+ try {
3162
+ const bcRaw = JSON.parse(safeReadSync(buildContextPath));
3163
+ if (typeof bcRaw.buildContext === "string" && bcRaw.buildContext.trim().length > 0) {
3164
+ buildContextText = bcRaw.buildContext.trim();
3165
+ }
3166
+ } catch {
3167
+ }
3168
+ }
1936
3169
  const deps = PHASE_DEPENDENCIES[phase];
1937
3170
  const artifactSections = [];
1938
3171
  const missingDependencies = [];
1939
3172
  for (const dep of deps) {
1940
3173
  const artifactFile = PHASE_ARTIFACT[dep];
1941
- const artifactPath = join3(cwd, ".stackwright", "artifacts", artifactFile);
1942
- if (existsSync3(artifactPath)) {
1943
- const content = JSON.parse(safeReadSync(artifactPath));
3174
+ const artifactPath = join4(cwd, ".stackwright", "artifacts", artifactFile);
3175
+ if (existsSync5(artifactPath)) {
3176
+ const rawContent = safeReadSync(artifactPath);
3177
+ const rawBytes = Buffer.from(rawContent, "utf-8");
3178
+ const content = JSON.parse(rawContent);
3179
+ let signatureVerified = false;
3180
+ let signatureAvailable = false;
3181
+ try {
3182
+ const sig = getArtifactSignature(cwd, artifactFile);
3183
+ if (sig) {
3184
+ signatureAvailable = true;
3185
+ const { publicKey } = loadPipelineKeys(cwd);
3186
+ signatureVerified = verifyArtifact(rawBytes, sig, publicKey);
3187
+ if (!signatureVerified) {
3188
+ const actualDigest = createHash3("sha384").update(rawBytes).digest("hex");
3189
+ emitSignatureAuditEvent({
3190
+ artifactFilename: artifactFile,
3191
+ expectedDigest: sig.digest,
3192
+ actualDigest,
3193
+ phase: dep,
3194
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3195
+ source: "stackwright_pro_build_specialist_prompt"
3196
+ });
3197
+ missingDependencies.push(dep);
3198
+ artifactSections.push(
3199
+ `[${artifactFile}]:
3200
+ (integrity check failed: ECDSA-P384 signature verification failed \u2014 artifact may have been tampered with)`
3201
+ );
3202
+ continue;
3203
+ }
3204
+ }
3205
+ } catch {
3206
+ }
1944
3207
  const expectedOtter = PHASE_TO_OTTER2[dep];
1945
3208
  const artifactOtter = content["generatedBy"];
3209
+ const normalizedOtter = artifactOtter?.replace(/-[a-f0-9]{6}$/, "");
1946
3210
  if (!artifactOtter) {
1947
3211
  missingDependencies.push(dep);
1948
3212
  artifactSections.push(
1949
3213
  `[${artifactFile}]:
1950
3214
  (integrity check failed: missing generatedBy field)`
1951
3215
  );
1952
- } else if (artifactOtter !== expectedOtter) {
3216
+ } else if (normalizedOtter !== expectedOtter) {
1953
3217
  missingDependencies.push(dep);
1954
3218
  artifactSections.push(
1955
3219
  `[${artifactFile}]:
1956
3220
  (integrity check failed: artifact claims generatedBy="${artifactOtter}" but expected="${expectedOtter}")`
1957
3221
  );
1958
3222
  } else {
1959
- artifactSections.push(`[${artifactFile}]:
1960
- ${JSON.stringify(content, null, 2)}`);
3223
+ const sigStatus = signatureAvailable ? signatureVerified ? " [signature verified]" : " [signature check skipped]" : " [unsigned]";
3224
+ artifactSections.push(
3225
+ `[${artifactFile}]${sigStatus}:
3226
+ ${JSON.stringify(content, null, 2)}`
3227
+ );
3228
+ }
3229
+ } else {
3230
+ missingDependencies.push(dep);
3231
+ artifactSections.push(`[${artifactFile}]:
3232
+ (not yet available)`);
3233
+ }
3234
+ }
3235
+ const parts = [];
3236
+ if (buildContextText) {
3237
+ parts.push("BUILD_CONTEXT:", buildContextText, "");
3238
+ }
3239
+ if (phase === "auth") {
3240
+ const initContextPath = join4(cwd, ".stackwright", "init-context.json");
3241
+ if (existsSync5(initContextPath)) {
3242
+ try {
3243
+ const initContext = JSON.parse(safeReadSync(initContextPath));
3244
+ if (initContext.devOnly === true || initContext.nonInteractive === true) {
3245
+ answers["devOnly"] = true;
3246
+ }
3247
+ } catch {
3248
+ }
3249
+ }
3250
+ }
3251
+ parts.push("ANSWERS:", JSON.stringify(answers, null, 2));
3252
+ if (artifactSections.length > 0) {
3253
+ parts.push("", "UPSTREAM ARTIFACTS:", "", ...artifactSections);
3254
+ }
3255
+ const artifactSchema = PHASE_ARTIFACT_SCHEMA[phase];
3256
+ parts.push("", "REQUIRED_ARTIFACT_SCHEMA:");
3257
+ parts.push(artifactSchema);
3258
+ const schemaRef = buildSchemaReferenceBlock(phase);
3259
+ if (schemaRef) {
3260
+ parts.push("", schemaRef);
3261
+ }
3262
+ parts.push("", "Execute using these answers and the upstream artifacts provided.");
3263
+ const prompt = parts.join("\n");
3264
+ const dependenciesSatisfied = missingDependencies.length === 0;
3265
+ return {
3266
+ text: JSON.stringify({
3267
+ otterName: PHASE_TO_OTTER2[phase],
3268
+ phase,
3269
+ prompt,
3270
+ dependenciesSatisfied,
3271
+ missingDependencies
3272
+ }),
3273
+ isError: false
3274
+ };
3275
+ } catch (err) {
3276
+ const message = err instanceof Error ? err.message : String(err);
3277
+ return { text: JSON.stringify({ error: true, phase, message }), isError: true };
3278
+ }
3279
+ }
3280
+ var OFF_SCRIPT_PATTERNS = [
3281
+ {
3282
+ pattern: /```(?:ts|tsx|js|jsx|python|bash|sh|sql|ruby|go|rust|java|csharp|c\+\+)\b/,
3283
+ label: "code fence"
3284
+ },
3285
+ { pattern: /\bimport\s+[\w{]/, label: "import statement" },
3286
+ { pattern: /\bexport\s+(?:const|function|default|class)\b/, label: "export statement" },
3287
+ { pattern: /\brequire\s*\(/, label: "require() call" },
3288
+ { pattern: /\beval\s*\(/, label: "eval() call" },
3289
+ { pattern: /^#!/m, label: "shebang" },
3290
+ { pattern: /<script[\s>]/i, label: "script tag" },
3291
+ { pattern: /\.(ts|tsx|js|jsx)\b.*\bfile\b/i, label: "code file reference" }
3292
+ ];
3293
+ var PHASE_REQUIRED_KEYS = {
3294
+ designer: ["designLanguage", "themeTokenSeeds"],
3295
+ theme: ["tokens"],
3296
+ scaffold: ["version", "generatedBy", "appRouterFiles"],
3297
+ api: ["entities", "version", "generatedBy"],
3298
+ auth: ["version", "generatedBy"],
3299
+ data: ["version", "generatedBy", "strategy", "collections"],
3300
+ pages: ["version", "generatedBy"],
3301
+ dashboard: ["version", "generatedBy"],
3302
+ workflow: ["version", "generatedBy"],
3303
+ services: ["version", "generatedBy", "flows"],
3304
+ polish: ["version", "generatedBy"],
3305
+ geo: ["version", "generatedBy", "geoCollections"]
3306
+ };
3307
+ var PHASE_ARTIFACT_SCHEMA = {
3308
+ designer: JSON.stringify(
3309
+ {
3310
+ version: "1.0",
3311
+ generatedBy: "stackwright-pro-designer-otter",
3312
+ application: {
3313
+ type: "<operational|data-explorer|admin|logistics|general>",
3314
+ environment: "<workstation|field|control-room|mixed>",
3315
+ density: "<compact|balanced|spacious>",
3316
+ accessibility: "<wcag-aa|section-508|none>",
3317
+ colorScheme: "<light|dark|both>"
3318
+ },
3319
+ designLanguage: {
3320
+ rationale: "<design rationale>",
3321
+ spacingScale: { base: 8, scale: [0, 4, 8, 16, 24, 32, 48, 64] },
3322
+ colorSemantics: { primary: "#1a365d", accent: "#e53e3e" },
3323
+ typography: {
3324
+ dataFont: "Inter",
3325
+ headingFont: "Inter",
3326
+ monoFont: "monospace",
3327
+ dataSizePx: 12,
3328
+ bodySizePx: 14
3329
+ },
3330
+ contrastRatio: "4.5",
3331
+ borderRadius: "4",
3332
+ shadowElevation: "standard"
3333
+ },
3334
+ themeTokenSeeds: {
3335
+ light: {
3336
+ background: "#ffffff",
3337
+ foreground: "#1a1a1a",
3338
+ primary: "#1a365d",
3339
+ surface: "#f7f7f7",
3340
+ border: "#e2e8f0"
3341
+ },
3342
+ dark: {
3343
+ background: "#1a1a1a",
3344
+ foreground: "#ffffff",
3345
+ primary: "#90cdf4",
3346
+ surface: "#2d2d2d",
3347
+ border: "#4a5568"
3348
+ }
3349
+ },
3350
+ conformsTo: null,
3351
+ operationalNotes: []
3352
+ },
3353
+ null,
3354
+ 2
3355
+ ),
3356
+ theme: JSON.stringify(
3357
+ {
3358
+ version: "1.0",
3359
+ generatedBy: "stackwright-pro-theme-otter",
3360
+ componentLibrary: "shadcn",
3361
+ colorScheme: "<light|dark|both>",
3362
+ tokens: {
3363
+ colors: { "primary-500": "#1a365d", background: "#ffffff" },
3364
+ spacing: { "spacing-1": "8px", "spacing-2": "16px" },
3365
+ typography: { "font-data": "Inter", "text-sm": "12px" },
3366
+ shape: { "radius-sm": "4px", "radius-md": "8px" },
3367
+ shadows: { "shadow-sm": "0 1px 2px rgba(0,0,0,0.08)" }
3368
+ },
3369
+ cssVariables: {
3370
+ "--background": "0 0% 100%",
3371
+ "--foreground": "222.2 84% 4.9%",
3372
+ "--primary": "222.2 47.4% 11.2%",
3373
+ "--primary-foreground": "210 40% 98%",
3374
+ "--surface": "210 40% 98%",
3375
+ "--border": "214.3 31.8% 91.4%"
3376
+ },
3377
+ dark: { "--background": "222.2 84% 4.9%", "--foreground": "210 40% 98%" }
3378
+ },
3379
+ null,
3380
+ 2
3381
+ ),
3382
+ scaffold: JSON.stringify(
3383
+ {
3384
+ version: "1.0",
3385
+ generatedBy: "stackwright-pro-scaffold-otter",
3386
+ // REQUIRED: appRouterFiles is a required key — NOT 'files' (see swp-k3mb)
3387
+ appRouterFiles: [
3388
+ "app/layout.tsx",
3389
+ "app/_components/page-client.tsx",
3390
+ "app/page.tsx",
3391
+ "app/[...slug]/page.tsx",
3392
+ "app/_components/providers.tsx",
3393
+ "app/not-found.tsx"
3394
+ ],
3395
+ title: "<title from stackwright.yml>",
3396
+ hasCollectionEndpoints: false,
3397
+ hasAuthConfig: true
3398
+ },
3399
+ null,
3400
+ 2
3401
+ ),
3402
+ api: JSON.stringify(
3403
+ {
3404
+ version: "1.0",
3405
+ generatedBy: "stackwright-pro-api-otter",
3406
+ entities: [
3407
+ {
3408
+ name: "Shipment",
3409
+ endpoint: "/shipments",
3410
+ method: "GET",
3411
+ revalidate: 60,
3412
+ mutationType: null
3413
+ }
3414
+ ],
3415
+ skipped: [
3416
+ {
3417
+ spec: "ais-message-models.yaml",
3418
+ format: "asyncapi",
3419
+ reason: "AsyncAPI spec \u2014 WebSocket/event integration required (no REST endpoints)"
3420
+ }
3421
+ ],
3422
+ warnings: [
3423
+ "Spec contains external $ref URLs \u2014 recommend bundle: true in stackwright.yml integration config"
3424
+ ],
3425
+ auth: { type: "bearer", header: "Authorization", envVar: "API_TOKEN" },
3426
+ baseUrl: "https://api.example.mil/v2",
3427
+ specPath: "./specs/api.yaml"
3428
+ },
3429
+ null,
3430
+ 2
3431
+ ),
3432
+ data: JSON.stringify(
3433
+ {
3434
+ version: "1.0",
3435
+ generatedBy: "stackwright-pro-data-otter",
3436
+ strategy: "<pulse-fast|isr-fast|isr-standard|isr-slow>",
3437
+ pulseMode: false,
3438
+ collections: [{ name: "equipment", revalidate: 60, pulse: false }],
3439
+ endpoints: { included: ["/equipment/**"], excluded: ["/admin/**"] },
3440
+ requiredPackages: { dependencies: {}, devPackages: {} }
3441
+ },
3442
+ null,
3443
+ 2
3444
+ ),
3445
+ geo: JSON.stringify(
3446
+ {
3447
+ version: "1.0",
3448
+ generatedBy: "stackwright-pro-geo-otter",
3449
+ geoCollections: [
3450
+ {
3451
+ collection: "vessels",
3452
+ latField: "latitude",
3453
+ lngField: "longitude",
3454
+ labelField: "vesselName",
3455
+ colorField: "navigationStatus"
3456
+ }
3457
+ ],
3458
+ pages: [
3459
+ {
3460
+ slug: "fleet-tracker",
3461
+ type: "<tracker|zone|route|combined>",
3462
+ collections: ["vessels"],
3463
+ hasLayers: false
3464
+ }
3465
+ ]
3466
+ },
3467
+ null,
3468
+ 2
3469
+ ),
3470
+ workflow: JSON.stringify(
3471
+ {
3472
+ version: "1.0",
3473
+ generatedBy: "stackwright-pro-workflow-otter",
3474
+ // Root key is `workflow` — NOT `workflowConfig` (see swp-k7cl)
3475
+ workflow: {
3476
+ id: "procurement-approval",
3477
+ route: "/procurement",
3478
+ files: ["workflows/procurement-approval.yml"],
3479
+ serviceDependencies: ["service:workflow-state"],
3480
+ warnings: []
3481
+ }
3482
+ },
3483
+ null,
3484
+ 2
3485
+ ),
3486
+ services: JSON.stringify(
3487
+ {
3488
+ version: "1.0",
3489
+ generatedBy: "stackwright-services-otter",
3490
+ flows: [
3491
+ {
3492
+ name: "at-risk-patients",
3493
+ trigger: "<http|event|schedule|queue>",
3494
+ steps: 3,
3495
+ outputSpec: "at-risk-patients.openapi.json"
1961
3496
  }
1962
- } else {
1963
- missingDependencies.push(dep);
1964
- artifactSections.push(`[${artifactFile}]:
1965
- (not yet available)`);
3497
+ ],
3498
+ workflows: [
3499
+ {
3500
+ name: "evacuation-coordination",
3501
+ states: 4,
3502
+ transitions: 5
3503
+ }
3504
+ ],
3505
+ openApiSpecs: ["at-risk-patients.openapi.json"],
3506
+ capabilitiesUsed: ["service.call", "collection.join", "collection.filter"]
3507
+ },
3508
+ null,
3509
+ 2
3510
+ ),
3511
+ pages: JSON.stringify(
3512
+ {
3513
+ version: "1.0",
3514
+ generatedBy: "stackwright-pro-page-otter",
3515
+ pages: [
3516
+ {
3517
+ slug: "catalog",
3518
+ type: "collection_listing",
3519
+ collection: "products",
3520
+ themeApplied: true,
3521
+ authRequired: false
3522
+ },
3523
+ {
3524
+ slug: "admin",
3525
+ type: "protected",
3526
+ collection: null,
3527
+ themeApplied: true,
3528
+ authRequired: true
3529
+ }
3530
+ ]
3531
+ },
3532
+ null,
3533
+ 2
3534
+ ),
3535
+ dashboard: JSON.stringify(
3536
+ {
3537
+ version: "1.0",
3538
+ generatedBy: "stackwright-pro-dashboard-otter",
3539
+ pages: [
3540
+ {
3541
+ slug: "dashboard",
3542
+ layout: "<grid|table|mixed>",
3543
+ collections: ["equipment", "supplies"],
3544
+ mode: "<ISR|Pulse>"
3545
+ }
3546
+ ]
3547
+ },
3548
+ null,
3549
+ 2
3550
+ ),
3551
+ // type: 'pki' = CAC/DoD certificate auth | 'oidc' = enterprise SSO
3552
+ // For dev-only mock auth: use type: 'oidc' with devOnly: true (Zod strips devOnly — it's a convention only)
3553
+ auth: JSON.stringify(
3554
+ {
3555
+ version: "1.0",
3556
+ generatedBy: "stackwright-pro-auth-otter",
3557
+ authConfig: {
3558
+ type: "<pki|oidc>",
3559
+ // OIDC-only fields (omit for pki):
3560
+ provider: "<azure_ad|okta|cognito|auth0|authentik|keycloak|custom>",
3561
+ discoveryUrl: "<IdP OIDC discovery URL>",
3562
+ clientId: "<OIDC client ID>",
3563
+ clientSecret: "<OIDC client secret>",
3564
+ rbacRoles: ["ADMIN", "ANALYST"],
3565
+ rbacDefaultRole: "ANALYST",
3566
+ protectedRoutes: ["/dashboard/:path*", "/procurement/:path*"],
3567
+ auditEnabled: true,
3568
+ auditRetentionDays: 90
3569
+ },
3570
+ // devScripts is OPTIONAL — only present when devOnly: true was used
3571
+ // Polish otter and foreman MUST check devScripts.written before referencing scripts
3572
+ devScripts: {
3573
+ written: true,
3574
+ scripts: { "dev:admin": "MOCK_USER=admin next dev" }
1966
3575
  }
1967
- }
1968
- const parts = ["ANSWERS:", JSON.stringify(answers, null, 2)];
1969
- if (artifactSections.length > 0) {
1970
- parts.push("", "UPSTREAM ARTIFACTS:", "", ...artifactSections);
1971
- }
1972
- parts.push("", "Execute using these answers and the upstream artifacts provided.");
1973
- const prompt = parts.join("\n");
1974
- const dependenciesSatisfied = missingDependencies.length === 0;
1975
- return {
1976
- text: JSON.stringify({
1977
- otterName: PHASE_TO_OTTER2[phase],
1978
- phase,
1979
- prompt,
1980
- dependenciesSatisfied,
1981
- missingDependencies
1982
- }),
1983
- isError: false
1984
- };
1985
- } catch (err) {
1986
- const message = err instanceof Error ? err.message : String(err);
1987
- return { text: JSON.stringify({ error: true, phase, message }), isError: true };
1988
- }
1989
- }
1990
- var OFF_SCRIPT_PATTERNS = [
1991
- {
1992
- pattern: /```(?:ts|tsx|js|jsx|python|bash|sh|sql|ruby|go|rust|java|csharp|c\+\+)\b/,
1993
- label: "code fence"
1994
- },
1995
- { pattern: /\bimport\s+[\w{]/, label: "import statement" },
1996
- { pattern: /\bexport\s+(?:const|function|default|class)\b/, label: "export statement" },
1997
- { pattern: /\brequire\s*\(/, label: "require() call" },
1998
- { pattern: /\beval\s*\(/, label: "eval() call" },
1999
- { pattern: /^#!/m, label: "shebang" },
2000
- { pattern: /<script[\s>]/i, label: "script tag" },
2001
- { pattern: /\.(ts|tsx|js|jsx)\b.*\bfile\b/i, label: "code file reference" }
2002
- ];
2003
- var PHASE_REQUIRED_KEYS = {
2004
- designer: ["designLanguage", "themeTokenSeeds"],
2005
- theme: ["tokens"],
2006
- api: ["entities"],
2007
- auth: ["version", "generatedBy"],
2008
- data: ["version", "generatedBy"],
2009
- pages: ["version", "generatedBy"],
2010
- dashboard: ["version", "generatedBy"],
2011
- workflow: ["version", "generatedBy"]
3576
+ },
3577
+ null,
3578
+ 2
3579
+ ),
3580
+ polish: JSON.stringify(
3581
+ {
3582
+ version: "1.0",
3583
+ generatedBy: "stackwright-pro-polish-otter",
3584
+ landingPage: { slug: "", rewritten: true },
3585
+ navigation: { itemCount: 5, items: ["/dashboard", "/equipment", "/workflows"] },
3586
+ gettingStarted: "<rewritten|redirected|not-found>",
3587
+ scaffoldCleanup: {
3588
+ deleted: ["content/posts/getting-started.yaml"],
3589
+ rewritten: ["app/not-found.tsx"],
3590
+ skipped: []
3591
+ }
3592
+ },
3593
+ null,
3594
+ 2
3595
+ )
2012
3596
  };
2013
3597
  function handleValidateArtifact(input) {
2014
3598
  const cwd = input._cwd ?? process.cwd();
2015
- const { phase, responseText } = input;
2016
- if (!isValidPhase(phase)) {
3599
+ const { phase, responseText, artifact: directArtifact } = input;
3600
+ if (!isValidPhase2(phase)) {
2017
3601
  return {
2018
3602
  text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
2019
3603
  isError: true
2020
3604
  };
2021
3605
  }
2022
- for (const { pattern, label } of OFF_SCRIPT_PATTERNS) {
2023
- if (pattern.test(responseText)) {
3606
+ let artifact;
3607
+ if (directArtifact) {
3608
+ artifact = directArtifact;
3609
+ } else {
3610
+ const text = responseText ?? "";
3611
+ for (const { pattern, label } of OFF_SCRIPT_PATTERNS) {
3612
+ if (pattern.test(text)) {
3613
+ const result = {
3614
+ valid: false,
3615
+ phase,
3616
+ violation: "off-script",
3617
+ retryPrompt: `You returned code output (detected: ${label}). Return ONLY a JSON artifact \u2014 no code, no files.`
3618
+ };
3619
+ return { text: JSON.stringify(result), isError: false };
3620
+ }
3621
+ }
3622
+ try {
3623
+ artifact = extractJsonFromResponse(text);
3624
+ } catch {
2024
3625
  const result = {
2025
3626
  valid: false,
2026
3627
  phase,
2027
- violation: "off-script",
2028
- retryPrompt: `You returned code output (detected: ${label}). Return ONLY a JSON artifact \u2014 no code, no files.`
3628
+ violation: "invalid-json",
3629
+ retryPrompt: "Your response did not contain valid JSON. Return a single JSON object with no surrounding text."
2029
3630
  };
2030
3631
  return { text: JSON.stringify(result), isError: false };
2031
3632
  }
2032
3633
  }
2033
- let artifact;
2034
- try {
2035
- artifact = extractJsonFromResponse(responseText);
2036
- } catch {
2037
- const result = {
2038
- valid: false,
2039
- phase,
2040
- violation: "invalid-json",
2041
- retryPrompt: "Your response did not contain valid JSON. Return a single JSON object with no surrounding text."
2042
- };
2043
- return { text: JSON.stringify(result), isError: false };
2044
- }
2045
3634
  if (!artifact.version || !artifact.generatedBy) {
2046
3635
  const result = {
2047
3636
  valid: false,
@@ -2062,12 +3651,68 @@ function handleValidateArtifact(input) {
2062
3651
  };
2063
3652
  return { text: JSON.stringify(result), isError: false };
2064
3653
  }
3654
+ const PHASE_ZOD_VALIDATORS = {
3655
+ workflow: (artifact2) => {
3656
+ const workflowData = artifact2["workflow"];
3657
+ if (!workflowData) {
3658
+ if (artifact2["workflowConfig"]) {
3659
+ console.warn(
3660
+ '[pipeline] DEPRECATED: workflow artifact uses "workflowConfig" key; rename to "workflow"'
3661
+ );
3662
+ return { success: true };
3663
+ }
3664
+ return { success: true };
3665
+ }
3666
+ if (typeof workflowData === "object" && workflowData !== null && "workflow" in workflowData) {
3667
+ const result = WorkflowFileSchema.safeParse(workflowData);
3668
+ if (!result.success) {
3669
+ const issues = result.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
3670
+ return { success: false, error: { message: issues } };
3671
+ }
3672
+ }
3673
+ return { success: true };
3674
+ },
3675
+ auth: (artifact2) => {
3676
+ const authConfig = artifact2["authConfig"];
3677
+ if (!authConfig) return { success: true };
3678
+ const result = authConfigSchema3.safeParse(authConfig);
3679
+ if (!result.success) {
3680
+ const issues = result.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
3681
+ return { success: false, error: { message: issues } };
3682
+ }
3683
+ return { success: true };
3684
+ }
3685
+ };
3686
+ const zodValidator = PHASE_ZOD_VALIDATORS[phase];
3687
+ if (zodValidator) {
3688
+ const zodResult = zodValidator(artifact);
3689
+ if (!zodResult.success) {
3690
+ const result = {
3691
+ valid: false,
3692
+ phase,
3693
+ violation: "schema-mismatch",
3694
+ retryPrompt: `Your artifact failed schema validation: ${zodResult.error?.message}. Fix these fields and return the corrected JSON artifact.`
3695
+ };
3696
+ return { text: JSON.stringify(result), isError: false };
3697
+ }
3698
+ }
2065
3699
  try {
2066
- const artifactsDir = join3(cwd, ".stackwright", "artifacts");
2067
- mkdirSync2(artifactsDir, { recursive: true });
3700
+ const artifactsDir = join4(cwd, ".stackwright", "artifacts");
3701
+ mkdirSync4(artifactsDir, { recursive: true });
2068
3702
  const artifactFile = PHASE_ARTIFACT[phase];
2069
- const artifactPath = join3(artifactsDir, artifactFile);
2070
- safeWriteSync(artifactPath, JSON.stringify(artifact, null, 2) + "\n");
3703
+ const artifactPath = join4(artifactsDir, artifactFile);
3704
+ const serialized = JSON.stringify(artifact, null, 2) + "\n";
3705
+ const artifactBytes = Buffer.from(serialized, "utf-8");
3706
+ safeWriteSync(artifactPath, serialized);
3707
+ let signed = false;
3708
+ try {
3709
+ const { privateKey } = loadPipelineKeys(cwd);
3710
+ const sig = signArtifact(artifactBytes, privateKey);
3711
+ const signerOtter = PHASE_TO_OTTER2[phase];
3712
+ saveArtifactSignature(cwd, artifactFile, sig, signerOtter);
3713
+ signed = true;
3714
+ } catch {
3715
+ }
2071
3716
  const state = readState(cwd);
2072
3717
  if (!state.phases[phase]) state.phases[phase] = defaultPhaseStatus();
2073
3718
  const ps = state.phases[phase];
@@ -2078,7 +3723,7 @@ function handleValidateArtifact(input) {
2078
3723
  valid: true,
2079
3724
  phase,
2080
3725
  artifactPath,
2081
- summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})`
3726
+ summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})${signed ? " [signed]" : ""}`
2082
3727
  };
2083
3728
  return { text: JSON.stringify(result), isError: false };
2084
3729
  } catch (err) {
@@ -2102,11 +3747,24 @@ function registerPipelineTools(server2) {
2102
3747
  "stackwright_pro_set_pipeline_state",
2103
3748
  `Atomic read\u2192modify\u2192write pipeline state. ${DESC}`,
2104
3749
  {
2105
- phase: z9.string().optional().describe('Phase to update, e.g. "designer"'),
2106
- field: z9.enum(["questionsCollected", "answered", "executed", "artifactWritten"]).optional().describe("Boolean field to set"),
2107
- value: z9.boolean().optional().describe("Value for the field"),
2108
- status: z9.enum(["setup", "questions", "execution", "done"]).optional().describe("Top-level status override"),
2109
- incrementRetry: z9.boolean().optional().describe("Bump retryCount by 1")
3750
+ phase: z13.string().optional().describe('Phase to update, e.g. "designer"'),
3751
+ field: z13.enum(["questionsCollected", "answered", "executed", "artifactWritten"]).optional().describe("Boolean field to set"),
3752
+ value: boolCoerce(z13.boolean().optional()).describe(
3753
+ 'Value for the field \u2014 must be a JSON boolean (true/false), NOT the string "true"/"false"'
3754
+ ),
3755
+ status: z13.enum(["setup", "questions", "execution", "done"]).optional().describe("Top-level status override"),
3756
+ incrementRetry: boolCoerce(z13.boolean().optional()).describe(
3757
+ "Bump retryCount by 1 \u2014 must be a JSON boolean"
3758
+ ),
3759
+ updates: jsonCoerce(
3760
+ z13.array(
3761
+ z13.object({
3762
+ phase: z13.string(),
3763
+ field: z13.enum(["questionsCollected", "answered", "executed", "artifactWritten"]),
3764
+ value: z13.boolean()
3765
+ })
3766
+ ).optional()
3767
+ ).describe("Batch updates \u2014 apply multiple field changes in one atomic read\u2192modify\u2192write")
2110
3768
  },
2111
3769
  async (args) => res(
2112
3770
  handleSetPipelineState({
@@ -2114,15 +3772,24 @@ function registerPipelineTools(server2) {
2114
3772
  ...args.field != null ? { field: args.field } : {},
2115
3773
  ...args.value != null ? { value: args.value } : {},
2116
3774
  ...args.status != null ? { status: args.status } : {},
2117
- ...args.incrementRetry != null ? { incrementRetry: args.incrementRetry } : {}
3775
+ ...args.incrementRetry != null ? { incrementRetry: args.incrementRetry } : {},
3776
+ ...args.updates != null ? { updates: args.updates } : {}
2118
3777
  })
2119
3778
  )
2120
3779
  );
2121
3780
  server2.tool(
2122
3781
  "stackwright_pro_check_execution_ready",
2123
- `Check all phases have answer files in .stackwright/answers/. ${DESC}`,
3782
+ `Check all phases have answer files in .stackwright/answers/. If phase is provided, check only that phase. ${DESC}`,
3783
+ {
3784
+ phase: z13.string().optional().describe("If provided, check only this phase's readiness. Omit to check all phases.")
3785
+ },
3786
+ async ({ phase }) => res(handleCheckExecutionReady(void 0, phase))
3787
+ );
3788
+ server2.tool(
3789
+ "stackwright_pro_get_ready_phases",
3790
+ `Return phases whose dependencies are all satisfied (executed=true). Use to determine which phases can run next \u2014 enables wave-based execution. ${DESC}`,
2124
3791
  {},
2125
- async () => res(handleCheckExecutionReady())
3792
+ async () => res(handleGetReadyPhases())
2126
3793
  );
2127
3794
  server2.tool(
2128
3795
  "stackwright_pro_list_artifacts",
@@ -2132,40 +3799,91 @@ function registerPipelineTools(server2) {
2132
3799
  );
2133
3800
  server2.tool(
2134
3801
  "stackwright_pro_write_phase_questions",
2135
- `Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. ${DESC}`,
3802
+ `Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. Specialists may also call this directly with a parsed questions array. ${DESC}`,
2136
3803
  {
2137
- phase: z9.string().describe('Phase name, e.g. "designer"'),
2138
- responseText: z9.string().describe("Raw LLM response from QUESTION_COLLECTION_MODE")
3804
+ phase: z13.string().optional().describe('Phase name, e.g. "designer" (required for direct write)'),
3805
+ responseText: z13.string().optional().describe("Raw LLM response from QUESTION_COLLECTION_MODE"),
3806
+ questions: jsonCoerce(z13.array(z13.any()).optional()).describe(
3807
+ "Questions array for direct specialist write"
3808
+ )
2139
3809
  },
2140
- async ({ phase, responseText }) => res(handleWritePhaseQuestions({ phase, responseText }))
3810
+ async ({ phase, responseText, questions }) => {
3811
+ if (phase && questions && Array.isArray(questions)) {
3812
+ if (!SAFE_PHASE.test(phase)) {
3813
+ return {
3814
+ content: [
3815
+ { type: "text", text: JSON.stringify({ error: `Invalid phase name` }) }
3816
+ ],
3817
+ isError: true
3818
+ };
3819
+ }
3820
+ const questionsDir = join4(process.cwd(), ".stackwright", "questions");
3821
+ mkdirSync4(questionsDir, { recursive: true });
3822
+ const outPath = join4(questionsDir, `${phase}.json`);
3823
+ writeFileSync4(
3824
+ outPath,
3825
+ JSON.stringify({ phase, questions, writtenAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2)
3826
+ );
3827
+ return {
3828
+ content: [
3829
+ {
3830
+ type: "text",
3831
+ text: JSON.stringify({
3832
+ written: true,
3833
+ phase,
3834
+ count: questions.length
3835
+ })
3836
+ }
3837
+ ]
3838
+ };
3839
+ }
3840
+ return res(
3841
+ handleWritePhaseQuestions({ phase: phase ?? "", responseText: responseText ?? "" })
3842
+ );
3843
+ }
2141
3844
  );
2142
3845
  server2.tool(
2143
3846
  "stackwright_pro_build_specialist_prompt",
2144
3847
  `Assemble execution prompt from answers + upstream artifacts. Foreman passes verbatim. ${DESC}`,
2145
- { phase: z9.string().describe('Phase to build prompt for, e.g. "pages"') },
3848
+ { phase: z13.string().describe('Phase to build prompt for, e.g. "pages"') },
2146
3849
  async ({ phase }) => res(handleBuildSpecialistPrompt({ phase }))
2147
3850
  );
2148
3851
  server2.tool(
2149
3852
  "stackwright_pro_validate_artifact",
2150
- `Validate specialist response + write artifact to .stackwright/artifacts/. Returns retryPrompt on failure. ${DESC}`,
3853
+ `Validate and write artifact to .stackwright/artifacts/. Returns retryPrompt on failure. ${DESC}`,
2151
3854
  {
2152
- phase: z9.string().describe('Phase that produced this artifact, e.g. "designer"'),
2153
- responseText: z9.string().describe("Raw response text from the specialist otter")
3855
+ phase: z13.string().describe('Phase that produced this artifact, e.g. "designer"'),
3856
+ responseText: z13.string().optional().describe("Raw response text from the specialist otter (Foreman-mediated path, legacy)"),
3857
+ artifact: jsonCoerce(z13.record(z13.string(), z13.unknown()).optional()).describe(
3858
+ "Artifact object to validate and write directly (specialist direct path \u2014 skips off-script detection and JSON parsing)"
3859
+ )
2154
3860
  },
2155
- async ({ phase, responseText }) => res(handleValidateArtifact({ phase, responseText }))
3861
+ async ({ phase, responseText, artifact }) => {
3862
+ if (artifact) {
3863
+ return res(
3864
+ handleValidateArtifact({ phase, artifact })
3865
+ );
3866
+ }
3867
+ return res(handleValidateArtifact({ phase, responseText: responseText ?? "" }));
3868
+ }
2156
3869
  );
2157
3870
  }
2158
3871
 
2159
3872
  // src/tools/safe-write.ts
2160
- import { z as z10 } from "zod";
2161
- import { writeFileSync as writeFileSync4, existsSync as existsSync4, mkdirSync as mkdirSync3, lstatSync as lstatSync4 } from "fs";
2162
- import { normalize, isAbsolute, dirname, join as join4 } from "path";
3873
+ import { z as z14 } from "zod";
3874
+ import { writeFileSync as writeFileSync5, readFileSync as readFileSync5, existsSync as existsSync6, mkdirSync as mkdirSync5, lstatSync as lstatSync6 } from "fs";
3875
+ import { normalize, isAbsolute, dirname, join as join5 } from "path";
2163
3876
  var OTTER_WRITE_ALLOWLISTS = {
2164
3877
  "stackwright-pro-designer-otter": [
2165
3878
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Design language artifact" }
2166
3879
  ],
2167
3880
  "stackwright-pro-theme-otter": [
2168
- { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" }
3881
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" },
3882
+ {
3883
+ prefix: "stackwright.theme.",
3884
+ suffix: ".yml",
3885
+ description: "Theme config YAML (merged at build time)"
3886
+ }
2169
3887
  ],
2170
3888
  "stackwright-pro-auth-otter": [
2171
3889
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Auth config artifact" },
@@ -2175,6 +3893,16 @@ var OTTER_WRITE_ALLOWLISTS = {
2175
3893
  prefix: ".env",
2176
3894
  suffix: "",
2177
3895
  description: "Dotenv files (.env, .env.local, .env.production, etc.)"
3896
+ },
3897
+ {
3898
+ prefix: "lib/mock-auth",
3899
+ suffix: ".ts",
3900
+ description: "Mock auth module (DEV_ONLY_MODE role updates)"
3901
+ },
3902
+ {
3903
+ prefix: "package.json",
3904
+ suffix: ".json",
3905
+ description: "Project package.json (DEV_ONLY_MODE script cleanup)"
2178
3906
  }
2179
3907
  ],
2180
3908
  "stackwright-pro-data-otter": [
@@ -2196,18 +3924,135 @@ var OTTER_WRITE_ALLOWLISTS = {
2196
3924
  { prefix: "workflows/", suffix: ".yaml", description: "Workflow definition" },
2197
3925
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Workflow config" }
2198
3926
  ],
3927
+ "stackwright-pro-scaffold-otter": [
3928
+ { prefix: "app/", suffix: ".tsx", description: "Next.js App Router shell files" },
3929
+ {
3930
+ prefix: ".stackwright/artifacts/",
3931
+ suffix: ".json",
3932
+ description: "Scaffold manifest artifact"
3933
+ }
3934
+ ],
2199
3935
  "stackwright-pro-api-otter": [
2200
3936
  { prefix: ".stackwright/artifacts/", suffix: ".json", description: "API config artifact" }
3937
+ ],
3938
+ "stackwright-pro-geo-otter": [
3939
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Geo manifest artifact" },
3940
+ { prefix: "pages/", suffix: "/content.yml", description: "Map page content" },
3941
+ { prefix: "pages/", suffix: "/content.yaml", description: "Map page content" }
3942
+ ],
3943
+ "stackwright-pro-polish-otter": [
3944
+ {
3945
+ prefix: "stackwright.yml",
3946
+ suffix: "",
3947
+ description: "Stackwright config (navigation updates)"
3948
+ },
3949
+ {
3950
+ prefix: "stackwright.navigation.",
3951
+ suffix: ".yml",
3952
+ description: "Navigation config YAML (merged at build time)"
3953
+ },
3954
+ { prefix: "pages/", suffix: "/content.yml", description: "Landing page content" },
3955
+ { prefix: "pages/", suffix: "/content.yaml", description: "Landing page content" },
3956
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Polish artifact" },
3957
+ { prefix: "README.md", suffix: "", description: "Project README rewrite" }
3958
+ ],
3959
+ // domain-expert-otter is a reader/answerer only — it writes via stackwright_pro_save_phase_answers,
3960
+ // not via safe_write. Entry required here because the MCP tool availability guard boilerplate
3961
+ // in its system prompt mentions stackwright_pro_safe_write (triggering the coherence test).
3962
+ "stackwright-pro-domain-expert-otter": [],
3963
+ "stackwright-services-otter": [
3964
+ { prefix: ".stackwright/artifacts/", suffix: ".json", description: "Services config artifact" },
3965
+ { prefix: "services/", suffix: ".ts", description: "Service implementation files" },
3966
+ { prefix: "services/", suffix: ".yaml", description: "Service flow definitions" },
3967
+ { prefix: "services/", suffix: ".yml", description: "Service flow definitions" },
3968
+ { prefix: "lib/seeds/", suffix: ".ts", description: "Seed data files" },
3969
+ { prefix: "specs/", suffix: ".json", description: "Generated OpenAPI specs" },
3970
+ { prefix: "specs/", suffix: ".yaml", description: "Generated OpenAPI specs" },
3971
+ { prefix: "stackwright-generated/", suffix: ".json", description: "Services manifest" }
2201
3972
  ]
2202
3973
  };
2203
3974
  var PROTECTED_PATH_PREFIXES = [
2204
3975
  ".stackwright/pipeline-state.json",
3976
+ ".stackwright/pipeline-keys.json",
3977
+ // ephemeral signing keys
3978
+ ".stackwright/artifacts/signatures.json",
3979
+ // artifact signature manifest
2205
3980
  ".stackwright/questions/",
2206
- ".stackwright/answers/"
3981
+ ".stackwright/answers/",
3982
+ ".stackwright/page-registry.json"
3983
+ // page ownership — managed by safe_write internally
2207
3984
  ];
3985
+ var MAX_SAFE_WRITE_BYTES_JSON = 512 * 1024;
3986
+ var MAX_SAFE_WRITE_BYTES_YAML = 256 * 1024;
3987
+ var MAX_SAFE_WRITE_BYTES_ENV = 4 * 1024;
3988
+ var MAX_SAFE_WRITE_BYTES_DEFAULT = 256 * 1024;
3989
+ function getMaxBytesForPath(filePath) {
3990
+ if (filePath.endsWith(".json")) return { limit: MAX_SAFE_WRITE_BYTES_JSON, label: "JSON" };
3991
+ if (filePath.endsWith(".yml") || filePath.endsWith(".yaml"))
3992
+ return { limit: MAX_SAFE_WRITE_BYTES_YAML, label: "YAML" };
3993
+ if (filePath === ".env" || /^\.env\.[a-zA-Z0-9]+/.test(filePath))
3994
+ return { limit: MAX_SAFE_WRITE_BYTES_ENV, label: "env" };
3995
+ return { limit: MAX_SAFE_WRITE_BYTES_DEFAULT, label: "default" };
3996
+ }
3997
+ var PAGE_REGISTRY_FILE = ".stackwright/page-registry.json";
3998
+ function extractPageSlug(filePath) {
3999
+ const match = normalize(filePath).match(/^pages\/(.+?)\/content\.ya?ml$/);
4000
+ return match?.[1] ?? null;
4001
+ }
4002
+ function extractContentTypes(yamlContent) {
4003
+ const typePattern = /^\s*-?\s*type:\s*(\S+)/gm;
4004
+ const types = [];
4005
+ let m;
4006
+ while ((m = typePattern.exec(yamlContent)) !== null) {
4007
+ const typeName = m[1];
4008
+ if (typeName && !types.includes(typeName)) {
4009
+ types.push(typeName);
4010
+ }
4011
+ }
4012
+ return types.length > 0 ? types : ["unknown"];
4013
+ }
4014
+ function readPageRegistry(cwd) {
4015
+ const regPath = join5(cwd, PAGE_REGISTRY_FILE);
4016
+ if (!existsSync6(regPath)) return {};
4017
+ try {
4018
+ const stat = lstatSync6(regPath);
4019
+ if (stat.isSymbolicLink()) return {};
4020
+ return JSON.parse(readFileSync5(regPath, "utf-8"));
4021
+ } catch {
4022
+ return {};
4023
+ }
4024
+ }
4025
+ function writePageRegistry(cwd, registry) {
4026
+ const dir = join5(cwd, ".stackwright");
4027
+ mkdirSync5(dir, { recursive: true });
4028
+ const regPath = join5(cwd, PAGE_REGISTRY_FILE);
4029
+ if (existsSync6(regPath)) {
4030
+ const stat = lstatSync6(regPath);
4031
+ if (stat.isSymbolicLink()) {
4032
+ throw new Error("Refusing to write page registry through symlink");
4033
+ }
4034
+ }
4035
+ writeFileSync5(regPath, JSON.stringify(registry, null, 2) + "\n", { encoding: "utf-8" });
4036
+ }
4037
+ function checkPageOwnership(cwd, slug, callerOtter) {
4038
+ const registry = readPageRegistry(cwd);
4039
+ const existing = registry[slug];
4040
+ if (!existing || existing.claimedBy === callerOtter) {
4041
+ return { allowed: true };
4042
+ }
4043
+ return {
4044
+ allowed: false,
4045
+ owner: existing.claimedBy,
4046
+ contentTypes: existing.contentTypes
4047
+ };
4048
+ }
4049
+ var NEXTJS_BRACKET_SEGMENT_RE = /\[\[\.{3}[a-zA-Z_][a-zA-Z0-9_]*\]\]|\[\.{3}[a-zA-Z_][a-zA-Z0-9_]*\]|\[[a-zA-Z_][a-zA-Z0-9_]*\]/g;
4050
+ function stripNextjsBracketSegments(path3) {
4051
+ return path3.replace(NEXTJS_BRACKET_SEGMENT_RE, "");
4052
+ }
2208
4053
  function checkPathAllowed(callerOtter, filePath) {
2209
4054
  const normalized = normalize(filePath);
2210
- if (normalized.includes("..")) {
4055
+ if (stripNextjsBracketSegments(normalized).includes("..")) {
2211
4056
  return { allowed: false, error: 'Path traversal detected: ".." segments are not allowed' };
2212
4057
  }
2213
4058
  if (isAbsolute(normalized)) {
@@ -2246,6 +4091,16 @@ function checkPathAllowed(callerOtter, filePath) {
2246
4091
  continue;
2247
4092
  }
2248
4093
  }
4094
+ if (rule.prefix === "lib/mock-auth" && rule.suffix === ".ts") {
4095
+ if (normalized !== "lib/mock-auth.ts") {
4096
+ continue;
4097
+ }
4098
+ }
4099
+ if (rule.prefix === "package.json" && rule.suffix === ".json") {
4100
+ if (normalized !== "package.json") {
4101
+ continue;
4102
+ }
4103
+ }
2249
4104
  return { allowed: true, rule: rule.description };
2250
4105
  }
2251
4106
  }
@@ -2330,11 +4185,23 @@ function handleSafeWrite(input) {
2330
4185
  };
2331
4186
  return { text: JSON.stringify(result), isError: true };
2332
4187
  }
4188
+ const contentBytes = Buffer.byteLength(content, "utf-8");
4189
+ const { limit: maxBytes, label: fileTypeLabel } = getMaxBytesForPath(filePath);
4190
+ if (contentBytes > maxBytes) {
4191
+ const result = {
4192
+ success: false,
4193
+ error: `Content size ${contentBytes} bytes exceeds ${fileTypeLabel} limit of ${maxBytes} bytes (${maxBytes / 1024} KB)`,
4194
+ callerOtter,
4195
+ attemptedPath: filePath,
4196
+ allowedPaths: []
4197
+ };
4198
+ return { text: JSON.stringify(result), isError: true };
4199
+ }
2333
4200
  const normalized = normalize(filePath);
2334
- const fullPath = join4(cwd, normalized);
2335
- if (existsSync4(fullPath)) {
4201
+ const fullPath = join5(cwd, normalized);
4202
+ if (existsSync6(fullPath)) {
2336
4203
  try {
2337
- const stat = lstatSync4(fullPath);
4204
+ const stat = lstatSync6(fullPath);
2338
4205
  if (stat.isSymbolicLink()) {
2339
4206
  const result = {
2340
4207
  success: false,
@@ -2359,11 +4226,38 @@ function handleSafeWrite(input) {
2359
4226
  };
2360
4227
  return { text: JSON.stringify(result), isError: true };
2361
4228
  }
4229
+ const pageSlug = extractPageSlug(normalized);
4230
+ if (pageSlug) {
4231
+ const ownership = checkPageOwnership(cwd, pageSlug, callerOtter);
4232
+ if (!ownership.allowed) {
4233
+ const result = {
4234
+ success: false,
4235
+ 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.`,
4236
+ callerOtter,
4237
+ attemptedPath: filePath,
4238
+ allowedPaths: []
4239
+ };
4240
+ return { text: JSON.stringify(result), isError: true };
4241
+ }
4242
+ }
2362
4243
  try {
2363
4244
  if (createDirectories) {
2364
- mkdirSync3(dirname(fullPath), { recursive: true });
4245
+ mkdirSync5(dirname(fullPath), { recursive: true });
4246
+ }
4247
+ writeFileSync5(fullPath, content, { encoding: "utf-8" });
4248
+ if (pageSlug) {
4249
+ try {
4250
+ const registry = readPageRegistry(cwd);
4251
+ registry[pageSlug] = {
4252
+ slug: pageSlug,
4253
+ claimedBy: callerOtter,
4254
+ contentTypes: extractContentTypes(content),
4255
+ writtenAt: (/* @__PURE__ */ new Date()).toISOString()
4256
+ };
4257
+ writePageRegistry(cwd, registry);
4258
+ } catch {
4259
+ }
2365
4260
  }
2366
- writeFileSync4(fullPath, content, { encoding: "utf-8" });
2367
4261
  const result = {
2368
4262
  success: true,
2369
4263
  path: normalized,
@@ -2389,10 +4283,12 @@ function registerSafeWriteTools(server2) {
2389
4283
  "stackwright_pro_safe_write",
2390
4284
  DESC,
2391
4285
  {
2392
- callerOtter: z10.string().describe('The otter agent name requesting the write, e.g. "stackwright-pro-page-otter"'),
2393
- filePath: z10.string().describe('Relative path from project root, e.g. "pages/dashboard/content.yml"'),
2394
- content: z10.string().describe("File content to write"),
2395
- createDirectories: z10.boolean().optional().describe("Create parent directories if they don't exist. Default: true")
4286
+ callerOtter: z14.string().describe('The otter agent name requesting the write, e.g. "stackwright-pro-page-otter"'),
4287
+ filePath: z14.string().describe('Relative path from project root, e.g. "pages/dashboard/content.yml"'),
4288
+ content: z14.string().describe("File content to write"),
4289
+ createDirectories: boolCoerce(z14.boolean().optional().default(true)).describe(
4290
+ "Create parent directories if they don't exist. Default: true"
4291
+ )
2396
4292
  },
2397
4293
  async ({ callerOtter, filePath, content, createDirectories }) => {
2398
4294
  const result = handleSafeWrite({
@@ -2407,9 +4303,9 @@ function registerSafeWriteTools(server2) {
2407
4303
  }
2408
4304
 
2409
4305
  // src/tools/auth.ts
2410
- import { z as z11 } from "zod";
2411
- import { readFileSync as readFileSync4, writeFileSync as writeFileSync5, existsSync as existsSync5 } from "fs";
2412
- import { join as join5 } from "path";
4306
+ import { z as z15 } from "zod";
4307
+ import { readFileSync as readFileSync6, writeFileSync as writeFileSync6, existsSync as existsSync7, mkdirSync as mkdirSync6 } from "fs";
4308
+ import { join as join6 } from "path";
2413
4309
  function buildHierarchy(roles) {
2414
4310
  const h = {};
2415
4311
  for (let i = 0; i < roles.length - 1; i++) {
@@ -2429,6 +4325,19 @@ function routesToYaml(routes, defaultRole, indent) {
2429
4325
  return routes.map((r) => `${indent}- pattern: ${r}
2430
4326
  ${indent} requiredRole: ${defaultRole}`).join("\n");
2431
4327
  }
4328
+ function detectNextMajorVersion(cwd) {
4329
+ try {
4330
+ const pkgPath = join6(cwd, "package.json");
4331
+ if (!existsSync7(pkgPath)) return null;
4332
+ const pkg = JSON.parse(readFileSync6(pkgPath, "utf8"));
4333
+ const nextVersion = pkg.dependencies?.next ?? pkg.devDependencies?.next;
4334
+ if (!nextVersion) return null;
4335
+ const match = nextVersion.match(/(\d+)/);
4336
+ return match ? parseInt(match[1], 10) : null;
4337
+ } catch {
4338
+ return null;
4339
+ }
4340
+ }
2432
4341
  function upsertAuthBlock(existing, authYaml) {
2433
4342
  const lines = existing.split("\n");
2434
4343
  let authStart = -1;
@@ -2441,14 +4350,99 @@ function upsertAuthBlock(existing, authYaml) {
2441
4350
  break;
2442
4351
  }
2443
4352
  }
2444
- if (authStart < 0) {
2445
- return existing.trimEnd() + "\n" + authYaml + "\n";
4353
+ if (authStart < 0) {
4354
+ return existing.trimEnd() + "\n" + authYaml + "\n";
4355
+ }
4356
+ const before = lines.slice(0, authStart);
4357
+ const after = lines.slice(authEnd);
4358
+ return [...before, ...authYaml.trimEnd().split("\n"), ...after.length ? after : []].join("\n");
4359
+ }
4360
+ function generateMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4361
+ const rbacBlock = ` rbac: {
4362
+ roles: ${JSON.stringify(roles)},
4363
+ defaultRole: '${defaultRole}',
4364
+ hierarchy: ${JSON.stringify(hierarchy, null, 4)},
4365
+ },`;
4366
+ const auditBlock = ` audit: {
4367
+ enabled: ${auditEnabled},
4368
+ retentionDays: ${auditRetentionDays},
4369
+ },`;
4370
+ const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
4371
+ const configBlock = `export const config = {
4372
+ matcher: ${JSON.stringify(protectedRoutes)},
4373
+ };`;
4374
+ if (method === "cac") {
4375
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
4376
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
4377
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
4378
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
4379
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth
4380
+ // \u26A0\uFE0F SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
4381
+ // DoD security officer review required before production deployment.
4382
+ // Verify: CA bundle completeness, EDIPI lookup endpoint, OCSP accessibility.
4383
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs/edge';
4384
+
4385
+ export const middleware = createProMiddleware({
4386
+ method: 'cac',
4387
+ cac: {
4388
+ caBundle: process.env.CAC_CA_BUNDLE ?? '${caBundle}',
4389
+ edipiLookup: '${edipiLookup}',
4390
+ ocspEndpoint: process.env.CAC_OCSP_ENDPOINT ?? '${ocspEndpoint}',
4391
+ certHeader: '${certHeader}',
4392
+ },
4393
+ ${rbacBlock}
4394
+ ${auditBlock}
4395
+ ${routesBlock}
4396
+ });
4397
+
4398
+ ${configBlock}
4399
+ `;
4400
+ }
4401
+ if (method === "oidc") {
4402
+ const scopes2 = params.oidcScopes ?? "openid profile email";
4403
+ const roleClaim = params.oidcRoleClaim ?? "roles";
4404
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
4405
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs/edge';
4406
+
4407
+ export const middleware = createProMiddleware({
4408
+ method: 'oidc',
4409
+ oidc: {
4410
+ discoveryUrl: process.env.OIDC_DISCOVERY_URL!,
4411
+ clientId: process.env.OIDC_CLIENT_ID!,
4412
+ clientSecret: process.env.OIDC_CLIENT_SECRET!,
4413
+ scopes: '${scopes2}',
4414
+ roleClaim: '${roleClaim}',
4415
+ },
4416
+ ${rbacBlock}
4417
+ ${auditBlock}
4418
+ ${routesBlock}
4419
+ });
4420
+
4421
+ ${configBlock}
4422
+ `;
2446
4423
  }
2447
- const before = lines.slice(0, authStart);
2448
- const after = lines.slice(authEnd);
2449
- return [...before, ...authYaml.trimEnd().split("\n"), ...after.length ? after : []].join("\n");
4424
+ const scopes = params.oauth2Scopes ?? "read write";
4425
+ return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
4426
+ import { createProMiddleware } from '@stackwright-pro/auth-nextjs/edge';
4427
+
4428
+ export const middleware = createProMiddleware({
4429
+ method: 'oauth2',
4430
+ oauth2: {
4431
+ authorizationUrl: process.env.OAUTH2_AUTH_URL!,
4432
+ tokenUrl: process.env.OAUTH2_TOKEN_URL!,
4433
+ clientId: process.env.OAUTH2_CLIENT_ID!,
4434
+ clientSecret: process.env.OAUTH2_CLIENT_SECRET!,
4435
+ scopes: '${scopes}',
4436
+ },
4437
+ ${rbacBlock}
4438
+ ${auditBlock}
4439
+ ${routesBlock}
4440
+ });
4441
+
4442
+ ${configBlock}
4443
+ `;
2450
4444
  }
2451
- function generateMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4445
+ function generateProxyContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
2452
4446
  const rbacBlock = ` rbac: {
2453
4447
  roles: ${JSON.stringify(roles)},
2454
4448
  defaultRole: '${defaultRole}',
@@ -2467,13 +4461,13 @@ function generateMiddlewareContent(method, params, roles, defaultRole, hierarchy
2467
4461
  const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
2468
4462
  const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
2469
4463
  const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
2470
- return `// middleware.ts \u2014 generated by @stackwright-pro/auth
2471
- // \u26A0\uFE0F SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
4464
+ return `// proxy.ts \u2014 generated by @stackwright-pro/auth (Next.js >=16)
4465
+ // SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
2472
4466
  // DoD security officer review required before production deployment.
2473
4467
  // Verify: CA bundle completeness, EDIPI lookup endpoint, OCSP accessibility.
2474
- import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
4468
+ import { createProProxy } from '@stackwright-pro/auth-nextjs/edge';
2475
4469
 
2476
- export const middleware = createProMiddleware({
4470
+ export const proxy = createProProxy({
2477
4471
  method: 'cac',
2478
4472
  cac: {
2479
4473
  caBundle: process.env.CAC_CA_BUNDLE ?? '${caBundle}',
@@ -2492,10 +4486,10 @@ ${configBlock}
2492
4486
  if (method === "oidc") {
2493
4487
  const scopes2 = params.oidcScopes ?? "openid profile email";
2494
4488
  const roleClaim = params.oidcRoleClaim ?? "roles";
2495
- return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
2496
- import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
4489
+ return `// proxy.ts \u2014 generated by @stackwright-pro/auth (Next.js >=16)
4490
+ import { createProProxy } from '@stackwright-pro/auth-nextjs/edge';
2497
4491
 
2498
- export const middleware = createProMiddleware({
4492
+ export const proxy = createProProxy({
2499
4493
  method: 'oidc',
2500
4494
  oidc: {
2501
4495
  discoveryUrl: process.env.OIDC_DISCOVERY_URL!,
@@ -2513,10 +4507,10 @@ ${configBlock}
2513
4507
  `;
2514
4508
  }
2515
4509
  const scopes = params.oauth2Scopes ?? "read write";
2516
- return `// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs
2517
- import { createProMiddleware } from '@stackwright-pro/auth-nextjs';
4510
+ return `// proxy.ts \u2014 generated by @stackwright-pro/auth (Next.js >=16)
4511
+ import { createProProxy } from '@stackwright-pro/auth-nextjs/edge';
2518
4512
 
2519
- export const middleware = createProMiddleware({
4513
+ export const proxy = createProProxy({
2520
4514
  method: 'oauth2',
2521
4515
  oauth2: {
2522
4516
  authorizationUrl: process.env.OAUTH2_AUTH_URL!,
@@ -2559,7 +4553,7 @@ OAUTH2_CLIENT_ID=your-client-id
2559
4553
  OAUTH2_CLIENT_SECRET=your-client-secret
2560
4554
  `;
2561
4555
  }
2562
- function generateYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4556
+ function generateYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes, useProxy) {
2563
4557
  const rbacSection = ` rbac:
2564
4558
  roles:
2565
4559
  ${rolesToYaml(roles, " ")}
@@ -2582,7 +4576,7 @@ ${routesToYaml(protectedRoutes, " ", defaultRole)}`.replace(/\n\s+,/g, "");
2582
4576
  const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
2583
4577
  return `auth:
2584
4578
  method: cac
2585
- ${providerLine} middleware: ./middleware.ts
4579
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
2586
4580
  cac:
2587
4581
  caBundle: \${CAC_CA_BUNDLE}
2588
4582
  edipiLookup: ${edipiLookup}
@@ -2599,7 +4593,7 @@ ${auditSection}
2599
4593
  const roleClaim = params.oidcRoleClaim ?? "roles";
2600
4594
  return `auth:
2601
4595
  method: oidc
2602
- ${providerLine} middleware: ./middleware.ts
4596
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
2603
4597
  oidc:
2604
4598
  discoveryUrl: \${OIDC_DISCOVERY_URL}
2605
4599
  clientId: \${OIDC_CLIENT_ID}
@@ -2615,7 +4609,7 @@ ${auditSection}
2615
4609
  const scopes = params.oauth2Scopes ?? "read write";
2616
4610
  return `auth:
2617
4611
  method: oauth2
2618
- ${providerLine} middleware: ./middleware.ts
4612
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
2619
4613
  oauth2:
2620
4614
  authorizationUrl: \${OAUTH2_AUTH_URL}
2621
4615
  tokenUrl: \${OAUTH2_TOKEN_URL}
@@ -2628,10 +4622,321 @@ ${routeLines}
2628
4622
  ${auditSection}
2629
4623
  `;
2630
4624
  }
4625
+ function generateDevOnlyMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4626
+ const rbacBlock = ` rbac: {
4627
+ roles: ${JSON.stringify(roles)},
4628
+ defaultRole: '${defaultRole}',
4629
+ hierarchy: ${JSON.stringify(hierarchy, null, 4)},
4630
+ },`;
4631
+ const auditBlock = ` audit: {
4632
+ enabled: ${auditEnabled},
4633
+ retentionDays: ${auditRetentionDays},
4634
+ },`;
4635
+ const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
4636
+ const configBlock = `export const config = {
4637
+ matcher: ${JSON.stringify(protectedRoutes)},
4638
+ };`;
4639
+ const devHeader = [
4640
+ "// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs (dev-only mock)",
4641
+ "// DEV ONLY \u2014 uses mock authentication from lib/mock-auth.ts",
4642
+ "// Do NOT deploy to production.",
4643
+ "import { createProMiddleware } from '@stackwright-pro/auth-nextjs/edge';",
4644
+ "import { mockAuthProvider } from './lib/mock-auth';"
4645
+ ].join("\n");
4646
+ if (method === "cac") {
4647
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
4648
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
4649
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
4650
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
4651
+ return `${devHeader}
4652
+
4653
+ export const middleware = createProMiddleware({
4654
+ method: 'cac',
4655
+ cac: {
4656
+ caBundle: '${caBundle}',
4657
+ edipiLookup: '${edipiLookup}',
4658
+ ocspEndpoint: '${ocspEndpoint}',
4659
+ certHeader: '${certHeader}',
4660
+ provider: mockAuthProvider,
4661
+ },
4662
+ ${rbacBlock}
4663
+ ${auditBlock}
4664
+ ${routesBlock}
4665
+ });
4666
+
4667
+ ${configBlock}
4668
+ `;
4669
+ }
4670
+ if (method === "oidc") {
4671
+ const scopes2 = params.oidcScopes ?? "openid profile email";
4672
+ const roleClaim = params.oidcRoleClaim ?? "roles";
4673
+ return `${devHeader}
4674
+
4675
+ export const middleware = createProMiddleware({
4676
+ method: 'oidc',
4677
+ oidc: {
4678
+ discoveryUrl: 'https://dev-mock-oidc/.well-known/openid-configuration',
4679
+ clientId: 'dev-mock-client',
4680
+ clientSecret: 'dev-mock-secret',
4681
+ scopes: '${scopes2}',
4682
+ roleClaim: '${roleClaim}',
4683
+ provider: mockAuthProvider,
4684
+ },
4685
+ ${rbacBlock}
4686
+ ${auditBlock}
4687
+ ${routesBlock}
4688
+ });
4689
+
4690
+ ${configBlock}
4691
+ `;
4692
+ }
4693
+ const scopes = params.oauth2Scopes ?? "read write";
4694
+ return `${devHeader}
4695
+
4696
+ export const middleware = createProMiddleware({
4697
+ method: 'oauth2',
4698
+ oauth2: {
4699
+ authorizationUrl: 'https://dev-mock-oauth2/authorize',
4700
+ tokenUrl: 'https://dev-mock-oauth2/token',
4701
+ clientId: 'dev-mock-client',
4702
+ clientSecret: 'dev-mock-secret',
4703
+ scopes: '${scopes}',
4704
+ provider: mockAuthProvider,
4705
+ },
4706
+ ${rbacBlock}
4707
+ ${auditBlock}
4708
+ ${routesBlock}
4709
+ });
4710
+
4711
+ ${configBlock}
4712
+ `;
4713
+ }
4714
+ function generateDevOnlyProxyContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
4715
+ const rbacBlock = ` rbac: {
4716
+ roles: ${JSON.stringify(roles)},
4717
+ defaultRole: '${defaultRole}',
4718
+ hierarchy: ${JSON.stringify(hierarchy, null, 4)},
4719
+ },`;
4720
+ const auditBlock = ` audit: {
4721
+ enabled: ${auditEnabled},
4722
+ retentionDays: ${auditRetentionDays},
4723
+ },`;
4724
+ const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
4725
+ const configBlock = `export const config = {
4726
+ matcher: ${JSON.stringify(protectedRoutes)},
4727
+ };`;
4728
+ const devHeader = [
4729
+ "// proxy.ts -- generated by @stackwright-pro/auth (Next.js >=16, dev-only mock)",
4730
+ "// DEV ONLY -- uses mock authentication from lib/mock-auth.ts",
4731
+ "// Do NOT deploy to production.",
4732
+ "import { createProProxy } from '@stackwright-pro/auth-nextjs/edge';",
4733
+ "import { mockAuthProvider } from './lib/mock-auth';"
4734
+ ].join("\n");
4735
+ if (method === "cac") {
4736
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
4737
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
4738
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
4739
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
4740
+ return `${devHeader}
4741
+
4742
+ export const proxy = createProProxy({
4743
+ method: 'cac',
4744
+ cac: {
4745
+ caBundle: '${caBundle}',
4746
+ edipiLookup: '${edipiLookup}',
4747
+ ocspEndpoint: '${ocspEndpoint}',
4748
+ certHeader: '${certHeader}',
4749
+ provider: mockAuthProvider,
4750
+ },
4751
+ ${rbacBlock}
4752
+ ${auditBlock}
4753
+ ${routesBlock}
4754
+ });
4755
+
4756
+ ${configBlock}
4757
+ `;
4758
+ }
4759
+ if (method === "oidc") {
4760
+ const scopes2 = params.oidcScopes ?? "openid profile email";
4761
+ const roleClaim = params.oidcRoleClaim ?? "roles";
4762
+ return `${devHeader}
4763
+
4764
+ export const proxy = createProProxy({
4765
+ method: 'oidc',
4766
+ oidc: {
4767
+ discoveryUrl: 'https://dev-mock-oidc/.well-known/openid-configuration',
4768
+ clientId: 'dev-mock-client',
4769
+ clientSecret: 'dev-mock-secret',
4770
+ scopes: '${scopes2}',
4771
+ roleClaim: '${roleClaim}',
4772
+ provider: mockAuthProvider,
4773
+ },
4774
+ ${rbacBlock}
4775
+ ${auditBlock}
4776
+ ${routesBlock}
4777
+ });
4778
+
4779
+ ${configBlock}
4780
+ `;
4781
+ }
4782
+ const scopes = params.oauth2Scopes ?? "read write";
4783
+ return `${devHeader}
4784
+
4785
+ export const proxy = createProProxy({
4786
+ method: 'oauth2',
4787
+ oauth2: {
4788
+ authorizationUrl: 'https://dev-mock-oauth2/authorize',
4789
+ tokenUrl: 'https://dev-mock-oauth2/token',
4790
+ clientId: 'dev-mock-client',
4791
+ clientSecret: 'dev-mock-secret',
4792
+ scopes: '${scopes}',
4793
+ provider: mockAuthProvider,
4794
+ },
4795
+ ${rbacBlock}
4796
+ ${auditBlock}
4797
+ ${routesBlock}
4798
+ });
4799
+
4800
+ ${configBlock}
4801
+ `;
4802
+ }
4803
+ function generateDevOnlyYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes, useProxy) {
4804
+ const rbacSection = ` rbac:
4805
+ roles:
4806
+ ${rolesToYaml(roles, " ")}
4807
+ defaultRole: ${defaultRole}
4808
+ hierarchy:
4809
+ ${hierarchyToYaml(hierarchy, " ")}`;
4810
+ const auditSection = ` audit:
4811
+ enabled: ${auditEnabled}
4812
+ retentionDays: ${auditRetentionDays}`;
4813
+ const routeLines = protectedRoutes.map((r) => ` - pattern: ${r}
4814
+ requiredRole: ${defaultRole}`).join("\n");
4815
+ const providerLine = params.provider ? ` provider: ${params.provider}
4816
+ ` : "";
4817
+ if (method === "cac") {
4818
+ const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
4819
+ const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
4820
+ const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
4821
+ const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
4822
+ return `auth:
4823
+ method: cac
4824
+ devOnly: true
4825
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
4826
+ cac:
4827
+ caBundle: ${caBundle}
4828
+ edipiLookup: ${edipiLookup}
4829
+ ocspEndpoint: ${ocspEndpoint}
4830
+ certHeader: ${certHeader}
4831
+ ${rbacSection}
4832
+ protectedRoutes:
4833
+ ${routeLines}
4834
+ ${auditSection}
4835
+ `;
4836
+ }
4837
+ if (method === "oidc") {
4838
+ const scopes2 = params.oidcScopes ?? "openid profile email";
4839
+ const roleClaim = params.oidcRoleClaim ?? "roles";
4840
+ return `auth:
4841
+ method: oidc
4842
+ devOnly: true
4843
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
4844
+ oidc:
4845
+ discoveryUrl: https://dev-mock-oidc/.well-known/openid-configuration
4846
+ clientId: dev-mock-client
4847
+ clientSecret: dev-mock-secret
4848
+ scopes: ${scopes2}
4849
+ roleClaim: ${roleClaim}
4850
+ ${rbacSection}
4851
+ protectedRoutes:
4852
+ ${routeLines}
4853
+ ${auditSection}
4854
+ `;
4855
+ }
4856
+ const scopes = params.oauth2Scopes ?? "read write";
4857
+ return `auth:
4858
+ method: oauth2
4859
+ devOnly: true
4860
+ ${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
4861
+ oauth2:
4862
+ authorizationUrl: https://dev-mock-oauth2/authorize
4863
+ tokenUrl: https://dev-mock-oauth2/token
4864
+ clientId: dev-mock-client
4865
+ clientSecret: dev-mock-secret
4866
+ scopes: ${scopes}
4867
+ ${rbacSection}
4868
+ protectedRoutes:
4869
+ ${routeLines}
4870
+ ${auditSection}
4871
+ `;
4872
+ }
4873
+ function deriveDevKey(roleName) {
4874
+ const segment = roleName.split("_")[0];
4875
+ return (segment ?? roleName).toLowerCase();
4876
+ }
4877
+ function generateMockAuthContent(roles, mockUsers) {
4878
+ const entries = [];
4879
+ const scriptLines = [];
4880
+ for (let i = 0; i < roles.length; i++) {
4881
+ const role = roles[i];
4882
+ const devKey = deriveDevKey(role);
4883
+ const persona = mockUsers?.[i];
4884
+ const name = persona?.name ?? `Dev ${role}`;
4885
+ const email = persona?.email ?? `dev-${devKey}@example.mil`;
4886
+ const edipi = String(i + 1).padStart(10, "0");
4887
+ entries.push(` ${devKey}: {
4888
+ id: 'mock-${devKey}-${String(i + 1).padStart(3, "0")}',
4889
+ name: '${name}',
4890
+ email: '${email}',
4891
+ roles: ['${role}'],
4892
+ edipi: '${edipi}',
4893
+ }`);
4894
+ scriptLines.push(` * pnpm dev:${devKey} \u2014 ${name}`);
4895
+ }
4896
+ return `/**
4897
+ * Mock authentication for development mode.
4898
+ *
4899
+ * DEV_ONLY_MODE \u2014 no real auth provider. Select a persona via MOCK_USER env var
4900
+ * or use the convenience scripts in package.json:
4901
+ ${scriptLines.join("\n")}
4902
+ */
4903
+
4904
+ export const MOCK_USERS = {
4905
+ ${entries.join(",\n")}
4906
+ } as const;
4907
+
4908
+ export type MockRole = keyof typeof MOCK_USERS;
4909
+
4910
+ export function getMockUser(role?: string) {
4911
+ const key = (role ?? process.env.MOCK_USER) as MockRole | undefined;
4912
+ if (!key) return null;
4913
+ return MOCK_USERS[key] ?? null;
4914
+ }
4915
+
4916
+ export function mockAuthProvider() {
4917
+ return getMockUser();
4918
+ }
4919
+ `;
4920
+ }
4921
+ function updatePackageJsonScripts(existingJson, roles, mockUsers) {
4922
+ const pkg = JSON.parse(existingJson);
4923
+ const scripts = pkg.scripts ?? {};
4924
+ delete scripts["dev:admin"];
4925
+ delete scripts["dev:analyst"];
4926
+ delete scripts["dev:viewer"];
4927
+ for (let i = 0; i < roles.length; i++) {
4928
+ const devKey = deriveDevKey(roles[i]);
4929
+ scripts[`dev:${devKey}`] = `MOCK_USER=${devKey} next dev`;
4930
+ }
4931
+ pkg.scripts = scripts;
4932
+ return JSON.stringify(pkg, null, 2) + "\n";
4933
+ }
2631
4934
  async function configureAuthHandler(params, cwd) {
2632
4935
  const {
2633
4936
  method,
2634
4937
  provider,
4938
+ devOnly = false,
4939
+ mockUsers,
2635
4940
  rbacRoles = ["SUPER_ADMIN", "ADMIN", "ANALYST"],
2636
4941
  auditEnabled = true,
2637
4942
  auditRetentionDays = 90,
@@ -2640,7 +4945,10 @@ async function configureAuthHandler(params, cwd) {
2640
4945
  const roles = rbacRoles;
2641
4946
  const defaultRole = params.rbacDefaultRole ?? roles[roles.length - 1];
2642
4947
  const hierarchy = buildHierarchy(roles);
2643
- if (method === "none") {
4948
+ const detectedVersion = params.nextMajorVersion ?? detectNextMajorVersion(cwd);
4949
+ const useProxy = (detectedVersion ?? 0) >= 16;
4950
+ const conventionFile = useProxy ? "proxy.ts" : "middleware.ts";
4951
+ if (method === "none" && !devOnly) {
2644
4952
  return {
2645
4953
  content: [
2646
4954
  {
@@ -2653,16 +4961,46 @@ async function configureAuthHandler(params, cwd) {
2653
4961
  rbacDefaultRole: defaultRole,
2654
4962
  protectedRoutesCount: protectedRoutes.length,
2655
4963
  filesWritten: [],
2656
- securityWarning: null
4964
+ securityWarning: null,
4965
+ autoUpgradeWarning: null
2657
4966
  })
2658
4967
  }
2659
4968
  ]
2660
4969
  };
2661
4970
  }
4971
+ const effectiveMethod = method === "none" ? "oidc" : method;
4972
+ const autoUpgradeWarning = method === "none" ? "method: 'none' + devOnly: true was automatically upgraded to method: 'oidc' + devOnly: true. In DEV_ONLY_MODE, pass method: 'oidc' + devOnly: true directly (swp-5tmy)." : null;
2662
4973
  const filesWritten = [];
2663
4974
  try {
2664
- const middlewareContent = generateMiddlewareContent(
2665
- method,
4975
+ const authFileContent = devOnly ? useProxy ? generateDevOnlyProxyContent(
4976
+ effectiveMethod,
4977
+ params,
4978
+ roles,
4979
+ defaultRole,
4980
+ hierarchy,
4981
+ auditEnabled,
4982
+ auditRetentionDays,
4983
+ protectedRoutes
4984
+ ) : generateDevOnlyMiddlewareContent(
4985
+ effectiveMethod,
4986
+ params,
4987
+ roles,
4988
+ defaultRole,
4989
+ hierarchy,
4990
+ auditEnabled,
4991
+ auditRetentionDays,
4992
+ protectedRoutes
4993
+ ) : useProxy ? generateProxyContent(
4994
+ effectiveMethod,
4995
+ params,
4996
+ roles,
4997
+ defaultRole,
4998
+ hierarchy,
4999
+ auditEnabled,
5000
+ auditRetentionDays,
5001
+ protectedRoutes
5002
+ ) : generateMiddlewareContent(
5003
+ effectiveMethod,
2666
5004
  params,
2667
5005
  roles,
2668
5006
  defaultRole,
@@ -2671,59 +5009,121 @@ async function configureAuthHandler(params, cwd) {
2671
5009
  auditRetentionDays,
2672
5010
  protectedRoutes
2673
5011
  );
2674
- writeFileSync5(join5(cwd, "middleware.ts"), middlewareContent, "utf8");
2675
- filesWritten.push("middleware.ts");
5012
+ writeFileSync6(join6(cwd, conventionFile), authFileContent, "utf8");
5013
+ filesWritten.push(conventionFile);
2676
5014
  } catch (err) {
2677
5015
  const msg = err instanceof Error ? err.message : String(err);
2678
5016
  return {
2679
5017
  content: [
2680
5018
  {
2681
5019
  type: "text",
2682
- text: JSON.stringify({ success: false, error: `Failed writing middleware.ts: ${msg}` })
5020
+ text: JSON.stringify({
5021
+ success: false,
5022
+ error: `Failed writing ${conventionFile}: ${msg}`
5023
+ })
2683
5024
  }
2684
5025
  ],
2685
5026
  isError: true
2686
5027
  };
2687
5028
  }
2688
- try {
2689
- const envBlock = generateEnvBlock(method, params);
2690
- const envPath = join5(cwd, ".env.example");
2691
- if (existsSync5(envPath)) {
2692
- const existing = readFileSync4(envPath, "utf8");
2693
- writeFileSync5(envPath, existing.trimEnd() + "\n\n" + envBlock, "utf8");
2694
- } else {
2695
- writeFileSync5(envPath, envBlock, "utf8");
5029
+ if (!devOnly) {
5030
+ try {
5031
+ const envBlock = generateEnvBlock(effectiveMethod, params);
5032
+ const envPath = join6(cwd, ".env.example");
5033
+ if (existsSync7(envPath)) {
5034
+ const existing = readFileSync6(envPath, "utf8");
5035
+ writeFileSync6(envPath, existing.trimEnd() + "\n\n" + envBlock, "utf8");
5036
+ } else {
5037
+ writeFileSync6(envPath, envBlock, "utf8");
5038
+ }
5039
+ filesWritten.push(".env.example");
5040
+ } catch (err) {
5041
+ const msg = err instanceof Error ? err.message : String(err);
5042
+ return {
5043
+ content: [
5044
+ {
5045
+ type: "text",
5046
+ text: JSON.stringify({ success: false, error: `Failed writing .env.example: ${msg}` })
5047
+ }
5048
+ ],
5049
+ isError: true
5050
+ };
5051
+ }
5052
+ }
5053
+ if (devOnly) {
5054
+ try {
5055
+ const mockAuthDir = join6(cwd, "lib");
5056
+ mkdirSync6(mockAuthDir, { recursive: true });
5057
+ const mockAuthContent = generateMockAuthContent(roles, mockUsers);
5058
+ writeFileSync6(join6(mockAuthDir, "mock-auth.ts"), mockAuthContent, "utf8");
5059
+ filesWritten.push("lib/mock-auth.ts");
5060
+ } catch (err) {
5061
+ const msg = err instanceof Error ? err.message : String(err);
5062
+ return {
5063
+ content: [
5064
+ {
5065
+ type: "text",
5066
+ text: JSON.stringify({
5067
+ success: false,
5068
+ error: `Failed writing lib/mock-auth.ts: ${msg}`
5069
+ })
5070
+ }
5071
+ ],
5072
+ isError: true
5073
+ };
5074
+ }
5075
+ try {
5076
+ const pkgPath = join6(cwd, "package.json");
5077
+ if (existsSync7(pkgPath)) {
5078
+ const existingPkg = readFileSync6(pkgPath, "utf8");
5079
+ const updatedPkg = updatePackageJsonScripts(existingPkg, roles, mockUsers);
5080
+ writeFileSync6(pkgPath, updatedPkg, "utf8");
5081
+ filesWritten.push("package.json");
5082
+ }
5083
+ } catch (err) {
5084
+ const msg = err instanceof Error ? err.message : String(err);
5085
+ return {
5086
+ content: [
5087
+ {
5088
+ type: "text",
5089
+ text: JSON.stringify({
5090
+ success: false,
5091
+ error: `Failed updating package.json: ${msg}`
5092
+ })
5093
+ }
5094
+ ],
5095
+ isError: true
5096
+ };
2696
5097
  }
2697
- filesWritten.push(".env.example");
2698
- } catch (err) {
2699
- const msg = err instanceof Error ? err.message : String(err);
2700
- return {
2701
- content: [
2702
- {
2703
- type: "text",
2704
- text: JSON.stringify({ success: false, error: `Failed writing .env.example: ${msg}` })
2705
- }
2706
- ],
2707
- isError: true
2708
- };
2709
5098
  }
2710
5099
  try {
2711
- const authYaml = generateYamlBlock(
2712
- method,
5100
+ const authYaml = devOnly ? generateDevOnlyYamlBlock(
5101
+ effectiveMethod,
2713
5102
  params,
2714
5103
  roles,
2715
5104
  defaultRole,
2716
5105
  hierarchy,
2717
5106
  auditEnabled,
2718
5107
  auditRetentionDays,
2719
- protectedRoutes
5108
+ protectedRoutes,
5109
+ useProxy
5110
+ ) : generateYamlBlock(
5111
+ effectiveMethod,
5112
+ params,
5113
+ roles,
5114
+ defaultRole,
5115
+ hierarchy,
5116
+ auditEnabled,
5117
+ auditRetentionDays,
5118
+ protectedRoutes,
5119
+ useProxy
2720
5120
  );
2721
- const ymlPath = join5(cwd, "stackwright.yml");
2722
- if (!existsSync5(ymlPath)) {
2723
- writeFileSync5(ymlPath, authYaml, "utf8");
5121
+ const ymlPath = join6(cwd, "stackwright.yml");
5122
+ if (!existsSync7(ymlPath)) {
5123
+ writeFileSync6(ymlPath, authYaml, "utf8");
2724
5124
  } else {
2725
- const existing = readFileSync4(ymlPath, "utf8");
2726
- writeFileSync5(ymlPath, upsertAuthBlock(existing, authYaml), "utf8");
5125
+ const existing = readFileSync6(ymlPath, "utf8");
5126
+ writeFileSync6(ymlPath, upsertAuthBlock(existing, authYaml), "utf8");
2727
5127
  }
2728
5128
  filesWritten.push("stackwright.yml");
2729
5129
  } catch (err) {
@@ -2738,20 +5138,37 @@ async function configureAuthHandler(params, cwd) {
2738
5138
  isError: true
2739
5139
  };
2740
5140
  }
2741
- const securityWarning = method === "cac" ? "SECURITY REVIEW REQUIRED \u2014 CAC certificate chain must be verified before production deployment" : null;
5141
+ const securityWarning = effectiveMethod === "cac" ? "SECURITY REVIEW REQUIRED \u2014 CAC certificate chain must be verified before production deployment" : null;
2742
5142
  return {
2743
5143
  content: [
2744
5144
  {
2745
5145
  type: "text",
2746
5146
  text: JSON.stringify({
2747
5147
  success: true,
2748
- method,
5148
+ method: effectiveMethod,
2749
5149
  provider: provider ?? null,
2750
5150
  rbacRoles: roles,
2751
5151
  rbacDefaultRole: defaultRole,
2752
5152
  protectedRoutesCount: protectedRoutes.length,
2753
5153
  filesWritten,
2754
- securityWarning
5154
+ convention: useProxy ? "proxy" : "middleware",
5155
+ nextMajorVersion: params.nextMajorVersion ?? null,
5156
+ securityWarning,
5157
+ autoUpgradeWarning,
5158
+ ...devOnly ? {
5159
+ devScripts: {
5160
+ written: filesWritten.includes("package.json"),
5161
+ scripts: filesWritten.includes("package.json") ? Object.fromEntries(
5162
+ roles.map((r) => {
5163
+ const k = deriveDevKey(r);
5164
+ return [`dev:${k}`, `MOCK_USER=${k} next dev`];
5165
+ })
5166
+ ) : {},
5167
+ ...filesWritten.includes("package.json") ? {} : {
5168
+ warning: "package.json not found \u2014 dev scripts were not written. Run the auth phase again after scaffolding creates package.json."
5169
+ }
5170
+ }
5171
+ } : {}
2755
5172
  })
2756
5173
  }
2757
5174
  ]
@@ -2762,35 +5179,38 @@ function registerAuthTools(server2) {
2762
5179
  "stackwright_pro_configure_auth",
2763
5180
  "Generate authentication middleware and configuration for a Next.js Stackwright application. Writes `middleware.ts` from a secure template, appends/updates the `auth:` section in `stackwright.yml`, and generates `.env.example` with required environment variables. \u26A0\uFE0F For CAC/PKI: generated `middleware.ts` carries a SECURITY REVIEW REQUIRED comment \u2014 certificate chain validation must be verified by a DoD security officer before production deployment. This is the ONLY approved path to generating `middleware.ts`. Never write TypeScript auth files directly.",
2764
5181
  {
2765
- method: z11.enum(["cac", "oidc", "oauth2", "none"]),
2766
- provider: z11.enum(["azure-ad", "okta", "ping", "cognito", "custom"]).optional(),
5182
+ method: z15.enum(["cac", "oidc", "oauth2", "none"]),
5183
+ provider: z15.enum(["azure-ad", "okta", "ping", "cognito", "custom"]).optional(),
2767
5184
  // CAC
2768
- cacCaBundle: z11.string().optional(),
2769
- cacEdipiLookup: z11.string().optional(),
2770
- cacOcspEndpoint: z11.string().optional(),
2771
- cacCertHeader: z11.string().optional(),
5185
+ cacCaBundle: z15.string().optional(),
5186
+ cacEdipiLookup: z15.string().optional(),
5187
+ cacOcspEndpoint: z15.string().optional(),
5188
+ cacCertHeader: z15.string().optional(),
2772
5189
  // OIDC
2773
- oidcDiscoveryUrl: z11.string().optional(),
2774
- oidcClientId: z11.string().optional(),
2775
- oidcClientSecret: z11.string().optional(),
2776
- oidcScopes: z11.string().optional(),
2777
- oidcRoleClaim: z11.string().optional(),
5190
+ oidcDiscoveryUrl: z15.string().optional(),
5191
+ oidcClientId: z15.string().optional(),
5192
+ oidcClientSecret: z15.string().optional(),
5193
+ oidcScopes: z15.string().optional(),
5194
+ oidcRoleClaim: z15.string().optional(),
2778
5195
  // OAuth2
2779
- oauth2AuthUrl: z11.string().optional(),
2780
- oauth2TokenUrl: z11.string().optional(),
2781
- oauth2ClientId: z11.string().optional(),
2782
- oauth2ClientSecret: z11.string().optional(),
2783
- oauth2Scopes: z11.string().optional(),
5196
+ oauth2AuthUrl: z15.string().optional(),
5197
+ oauth2TokenUrl: z15.string().optional(),
5198
+ oauth2ClientId: z15.string().optional(),
5199
+ oauth2ClientSecret: z15.string().optional(),
5200
+ oauth2Scopes: z15.string().optional(),
2784
5201
  // RBAC
2785
- rbacRoles: z11.array(z11.string()).optional(),
2786
- rbacDefaultRole: z11.string().optional(),
5202
+ rbacRoles: jsonCoerce(z15.array(z15.string()).optional()),
5203
+ rbacDefaultRole: z15.string().optional(),
2787
5204
  // Audit
2788
- auditEnabled: z11.boolean().optional(),
2789
- auditRetentionDays: z11.number().int().positive().optional(),
5205
+ auditEnabled: boolCoerce(z15.boolean().optional()),
5206
+ auditRetentionDays: numCoerce(z15.number().int().positive().optional()),
2790
5207
  // Routes
2791
- protectedRoutes: z11.array(z11.string()).optional(),
5208
+ protectedRoutes: jsonCoerce(z15.array(z15.string()).optional()),
2792
5209
  // Injection for tests
2793
- _cwd: z11.string().optional()
5210
+ _cwd: z15.string().optional(),
5211
+ devOnly: boolCoerce(z15.boolean().optional()),
5212
+ mockUsers: jsonCoerce(z15.array(z15.object({ name: z15.string(), email: z15.string() })).optional()),
5213
+ nextMajorVersion: numCoerce(z15.number().int().positive().optional())
2794
5214
  },
2795
5215
  async (params) => {
2796
5216
  const cwd = params._cwd ?? process.cwd();
@@ -2800,45 +5220,65 @@ function registerAuthTools(server2) {
2800
5220
  }
2801
5221
 
2802
5222
  // src/integrity.ts
2803
- import { createHash as createHash2, timingSafeEqual } from "crypto";
2804
- import { readFileSync as readFileSync5, readdirSync, lstatSync as lstatSync5 } from "fs";
2805
- import { join as join6, basename } from "path";
5223
+ import { createHash as createHash4, timingSafeEqual as timingSafeEqual2 } from "crypto";
5224
+ import { readFileSync as readFileSync7, readdirSync as readdirSync2, lstatSync as lstatSync7 } from "fs";
5225
+ import { join as join7, basename } from "path";
2806
5226
  var _checksums = /* @__PURE__ */ new Map([
2807
5227
  [
2808
5228
  "stackwright-pro-api-otter.json",
2809
- "f1cc9edf2dd1df3ebcea1d0ab33d17a358faaf8aa97ee232cd7994042f2eac0d"
5229
+ "df79f4389a576c2885efa07b04f613c60eb8ebf4a8b1d4c7da5e4bb6ee4248dd"
2810
5230
  ],
2811
5231
  [
2812
5232
  "stackwright-pro-auth-otter.json",
2813
- "a19e06c503209a8a35fe321d30448623545b36b48c47a6ec064d13406ad1f725"
5233
+ "07134125ab4f8c82ee015f27587e4d84bdeefca5ec211d1563bcb25b8aa61eb3"
2814
5234
  ],
2815
5235
  [
2816
5236
  "stackwright-pro-dashboard-otter.json",
2817
- "b3cb3d7554f2e9eed3b57d5e0e3bf85d6ba5b4db5d3af5514391cf0575fcc001"
5237
+ "160af221e04200f53709f8c3e249ca6dafb38a325b232fabd478b28f5492ab01"
2818
5238
  ],
2819
5239
  [
2820
5240
  "stackwright-pro-data-otter.json",
2821
- "bfacb87ae82867472a75982215554336a105a658d6cd3dd2c8b819fa1e11d7ac"
5241
+ "709c8e49328908549fe87de181a5991e09c918ef24bbfe6948f9888f0c758c25"
2822
5242
  ],
2823
5243
  [
2824
5244
  "stackwright-pro-designer-otter.json",
2825
- "c58fa7c7ead9e6398074e1c7ce3f31a8ef4eb3679f5fa18cc03cae3a87878c88"
5245
+ "1364b2c235c07b0b798e9aab90a68604f60019a5508d41ba576977f173e20cd9"
5246
+ ],
5247
+ [
5248
+ "stackwright-pro-domain-expert-otter.json",
5249
+ "1f21b8ff3450bdae29a4d31b31462ba22583995a448af3c11ab0a5071f46bd72"
2826
5250
  ],
2827
5251
  [
2828
5252
  "stackwright-pro-foreman-otter.json",
2829
- "27f4dfd4676246c9fea14fd1de4f148928eeaf06e58b08240761fd3e663dd540"
5253
+ "438b03d2c35f64536055c68b3a9044fe3b5e4f2889acde4500dd801fad724be1"
5254
+ ],
5255
+ [
5256
+ "stackwright-pro-geo-otter.json",
5257
+ "2ec83c26a08c413d9553ff8b8f0f0f643c1a8da043741b356e27106cad78f05f"
2830
5258
  ],
2831
5259
  [
2832
5260
  "stackwright-pro-page-otter.json",
2833
- "65bec3a3a0dda6b7591bba2de9399f1e3a4fb99cfe1075342f4f4be98d917b67"
5261
+ "0057ea97f7c2e33a8673140f59a0237eb627d82c676af3fae4faa31033598e03"
5262
+ ],
5263
+ [
5264
+ "stackwright-pro-polish-otter.json",
5265
+ "bd87327b9a9a62fabaee8837492ce943feae8bfc15e5d43b45ba0e84619daec3"
5266
+ ],
5267
+ [
5268
+ "stackwright-pro-scaffold-otter.json",
5269
+ "91de5861f1406043d1d387388302fb1492211b81e2eea9777dec60e48f317f2a"
2834
5270
  ],
2835
5271
  [
2836
5272
  "stackwright-pro-theme-otter.json",
2837
- "64ffaeeceacd739922788a1d074f6feaffc3f91d09706c2c104f0c0281677732"
5273
+ "fe10108e3ba67106751ea662f512bb5f4eb58f7abda26880ef4cf6b0f9feb944"
2838
5274
  ],
2839
5275
  [
2840
5276
  "stackwright-pro-workflow-otter.json",
2841
- "0eec9d6a731678cf547c2a7b0b6fc338ca143c35501365a1e4e5dd2779dd5510"
5277
+ "5f6209fadc1355580e2455a16386f06bd7d5814f047b2dd5b33800abf6a48ff8"
5278
+ ],
5279
+ [
5280
+ "stackwright-services-otter.json",
5281
+ "c013d7fc2475e62d0af54d57bc988182feee7766bac0edf841cbfad5c73e9261"
2842
5282
  ]
2843
5283
  ]);
2844
5284
  Object.freeze(_checksums);
@@ -2853,11 +5293,11 @@ for (const [name, digest] of CANONICAL_CHECKSUMS) {
2853
5293
  }
2854
5294
  var MAX_OTTER_BYTES = 1 * 1024 * 1024;
2855
5295
  function computeSha256(data) {
2856
- return createHash2("sha256").update(data).digest("hex");
5296
+ return createHash4("sha256").update(data).digest("hex");
2857
5297
  }
2858
5298
  function safeEqual(a, b) {
2859
5299
  if (a.length !== b.length) return false;
2860
- return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
5300
+ return timingSafeEqual2(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
2861
5301
  }
2862
5302
  function verifyOtterFile(filePath) {
2863
5303
  const filename = basename(filePath);
@@ -2867,7 +5307,7 @@ function verifyOtterFile(filePath) {
2867
5307
  }
2868
5308
  let stat;
2869
5309
  try {
2870
- stat = lstatSync5(filePath);
5310
+ stat = lstatSync7(filePath);
2871
5311
  } catch (err) {
2872
5312
  const msg = err instanceof Error ? err.message : String(err);
2873
5313
  return { verified: false, filename, error: `Cannot stat file: ${msg}` };
@@ -2885,7 +5325,7 @@ function verifyOtterFile(filePath) {
2885
5325
  }
2886
5326
  let raw;
2887
5327
  try {
2888
- raw = readFileSync5(filePath);
5328
+ raw = readFileSync7(filePath);
2889
5329
  } catch (err) {
2890
5330
  const msg = err instanceof Error ? err.message : String(err);
2891
5331
  return { verified: false, filename, error: `Cannot read file: ${msg}` };
@@ -2918,12 +5358,24 @@ function verifyOtterFile(filePath) {
2918
5358
  return { verified: true, filename };
2919
5359
  }
2920
5360
  function verifyAllOtters(otterDir) {
5361
+ if (/(?:^|[/\\])\.\.(?:[/\\]|$)/.test(otterDir) || otterDir.includes("..")) {
5362
+ return {
5363
+ verified: [],
5364
+ failed: [
5365
+ {
5366
+ filename: "<directory>",
5367
+ error: `Security: path traversal sequence detected in otter directory parameter`
5368
+ }
5369
+ ],
5370
+ unknown: []
5371
+ };
5372
+ }
2921
5373
  const verified = [];
2922
5374
  const failed = [];
2923
5375
  const unknown = [];
2924
5376
  let entries;
2925
5377
  try {
2926
- entries = readdirSync(otterDir);
5378
+ entries = readdirSync2(otterDir);
2927
5379
  } catch (err) {
2928
5380
  const msg = err instanceof Error ? err.message : String(err);
2929
5381
  return {
@@ -2934,9 +5386,9 @@ function verifyAllOtters(otterDir) {
2934
5386
  }
2935
5387
  const otterFiles = entries.filter((f) => f.endsWith("-otter.json"));
2936
5388
  for (const filename of otterFiles) {
2937
- const filePath = join6(otterDir, filename);
5389
+ const filePath = join7(otterDir, filename);
2938
5390
  try {
2939
- if (lstatSync5(filePath).isSymbolicLink()) {
5391
+ if (lstatSync7(filePath).isSymbolicLink()) {
2940
5392
  failed.push({ filename, error: "Skipped: symlink" });
2941
5393
  continue;
2942
5394
  }
@@ -2962,15 +5414,30 @@ var DEFAULT_SEARCH_PATHS = ["node_modules/@stackwright-pro/otters/src/", "packag
2962
5414
  function resolveOtterDir() {
2963
5415
  const cwd = process.cwd();
2964
5416
  for (const relative of DEFAULT_SEARCH_PATHS) {
2965
- const candidate = join6(cwd, relative);
5417
+ const candidate = join7(cwd, relative);
2966
5418
  try {
2967
- lstatSync5(candidate);
5419
+ lstatSync7(candidate);
2968
5420
  return candidate;
2969
5421
  } catch {
2970
5422
  }
2971
5423
  }
2972
5424
  return null;
2973
5425
  }
5426
+ function emitIntegrityAuditEvent(params) {
5427
+ const record = JSON.stringify({
5428
+ level: "AUDIT",
5429
+ event: "INTEGRITY_FAIL",
5430
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5431
+ source: "stackwright_pro_verify_otter_integrity",
5432
+ otterDir: params.otterDir,
5433
+ failedCount: params.failed.length,
5434
+ unknownCount: params.unknown.length,
5435
+ failures: params.failed,
5436
+ unknown: params.unknown
5437
+ });
5438
+ process.stderr.write(`INTEGRITY_FAIL ${record}
5439
+ `);
5440
+ }
2974
5441
  function registerIntegrityTools(server2) {
2975
5442
  server2.tool(
2976
5443
  "stackwright_pro_verify_otter_integrity",
@@ -2994,6 +5461,13 @@ function registerIntegrityTools(server2) {
2994
5461
  }
2995
5462
  const result = verifyAllOtters(resolved);
2996
5463
  const allGood = result.failed.length === 0 && result.unknown.length === 0;
5464
+ if (!allGood) {
5465
+ emitIntegrityAuditEvent({
5466
+ otterDir: resolved,
5467
+ failed: result.failed,
5468
+ unknown: result.unknown
5469
+ });
5470
+ }
2997
5471
  return {
2998
5472
  content: [
2999
5473
  {
@@ -3007,25 +5481,27 @@ function registerIntegrityTools(server2) {
3007
5481
  verified: result.verified,
3008
5482
  failed: result.failed,
3009
5483
  unknown: result.unknown,
3010
- warning: result.failed.length > 0 ? "SHA-256 mismatches detected (non-blocking). PKI-signed manifest support coming soon." : void 0
5484
+ ...allGood ? {} : {
5485
+ error: "INTEGRITY CHECK FAILED: SHA-256 mismatch detected in otter agent definitions. Do not proceed \u2014 otter files may have been tampered with."
5486
+ }
3011
5487
  })
3012
5488
  }
3013
5489
  ],
3014
- isError: false
5490
+ isError: !allGood
3015
5491
  };
3016
5492
  }
3017
5493
  );
3018
5494
  }
3019
5495
 
3020
5496
  // src/tools/domain.ts
3021
- import { z as z12 } from "zod";
3022
- import { readFileSync as readFileSync6, existsSync as existsSync6 } from "fs";
3023
- import { join as join7 } from "path";
5497
+ import { z as z16 } from "zod";
5498
+ import { readFileSync as readFileSync8, existsSync as existsSync8 } from "fs";
5499
+ import { join as join8 } from "path";
3024
5500
  function handleListCollections(input) {
3025
5501
  const cwd = input._cwd ?? process.cwd();
3026
5502
  const sources = [
3027
5503
  {
3028
- path: join7(cwd, ".stackwright", "artifacts", "data-config.json"),
5504
+ path: join8(cwd, ".stackwright", "artifacts", "data-config.json"),
3029
5505
  source: "data-config.json",
3030
5506
  parse: (raw) => {
3031
5507
  const parsed = JSON.parse(raw);
@@ -3036,15 +5512,15 @@ function handleListCollections(input) {
3036
5512
  }
3037
5513
  },
3038
5514
  {
3039
- path: join7(cwd, "stackwright.yml"),
5515
+ path: join8(cwd, "stackwright.yml"),
3040
5516
  source: "stackwright.yml",
3041
5517
  parse: extractCollectionsFromYaml
3042
5518
  }
3043
5519
  ];
3044
5520
  for (const { path: path3, source, parse } of sources) {
3045
- if (!existsSync6(path3)) continue;
5521
+ if (!existsSync8(path3)) continue;
3046
5522
  try {
3047
- const collections = parse(readFileSync6(path3, "utf8"));
5523
+ const collections = parse(readFileSync8(path3, "utf8"));
3048
5524
  return {
3049
5525
  text: JSON.stringify({ collections, source, collectionCount: collections.length }),
3050
5526
  isError: false
@@ -3195,8 +5671,8 @@ function handleValidateWorkflow(input) {
3195
5671
  if (input.workflow && Object.keys(input.workflow).length > 0) {
3196
5672
  raw = input.workflow;
3197
5673
  } else {
3198
- const artifactPath = join7(cwd, ".stackwright", "artifacts", "workflow-config.json");
3199
- if (!existsSync6(artifactPath)) {
5674
+ const artifactPath = join8(cwd, ".stackwright", "artifacts", "workflow-config.json");
5675
+ if (!existsSync8(artifactPath)) {
3200
5676
  return fail([
3201
5677
  {
3202
5678
  code: "NO_WORKFLOW",
@@ -3205,7 +5681,7 @@ function handleValidateWorkflow(input) {
3205
5681
  ]);
3206
5682
  }
3207
5683
  try {
3208
- raw = JSON.parse(readFileSync6(artifactPath, "utf8"));
5684
+ raw = JSON.parse(readFileSync8(artifactPath, "utf8"));
3209
5685
  } catch (err) {
3210
5686
  return fail([{ code: "INVALID_JSON", message: `Failed to parse workflow artifact: ${err}` }]);
3211
5687
  }
@@ -3404,7 +5880,7 @@ function registerDomainTools(server2) {
3404
5880
  "stackwright_pro_resolve_data_strategy",
3405
5881
  "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.",
3406
5882
  {
3407
- strategy: z12.string().describe(
5883
+ strategy: z16.string().describe(
3408
5884
  'The data-1 answer value: "pulse-fast", "isr-fast", "isr-standard", or "isr-slow"'
3409
5885
  )
3410
5886
  },
@@ -3414,7 +5890,7 @@ function registerDomainTools(server2) {
3414
5890
  "stackwright_pro_validate_workflow",
3415
5891
  "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.",
3416
5892
  {
3417
- workflow: z12.record(z12.string(), z12.unknown()).optional().describe(
5893
+ workflow: jsonCoerce(z16.record(z16.string(), z16.unknown()).optional()).describe(
3418
5894
  "Parsed workflow object. If omitted, reads from .stackwright/artifacts/workflow-config.json"
3419
5895
  )
3420
5896
  },
@@ -3422,18 +5898,598 @@ function registerDomainTools(server2) {
3422
5898
  );
3423
5899
  }
3424
5900
 
5901
+ // src/tools/type-schemas.ts
5902
+ import { z as z17 } from "zod";
5903
+ function buildTypeSchemaSummary() {
5904
+ return {
5905
+ version: "1.0",
5906
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
5907
+ domains: {
5908
+ workflow: {
5909
+ description: "Workflow DSL \u2014 step definitions, auth blocks, field types, conditions",
5910
+ schemas: [
5911
+ "WorkflowFileSchema",
5912
+ "WorkflowDefinitionSchema",
5913
+ "WorkflowStepSchema",
5914
+ "WorkflowStepTypeSchema",
5915
+ "WorkflowFieldSchema",
5916
+ "WorkflowActionSchema",
5917
+ "WorkflowAuthSchema",
5918
+ "WorkflowThemeSchema",
5919
+ "TransitionConditionSchema",
5920
+ "PersistenceSchema"
5921
+ ],
5922
+ otter: "stackwright-pro-workflow-otter",
5923
+ artifactKey: "workflowConfig"
5924
+ },
5925
+ auth: {
5926
+ description: "Authentication providers \u2014 PKI/CAC, OIDC, RBAC configuration",
5927
+ schemas: [
5928
+ "authConfigSchema",
5929
+ "pkiConfigSchema",
5930
+ "oidcConfigSchema",
5931
+ "rbacConfigSchema",
5932
+ "componentAuthSchema",
5933
+ "authUserSchema",
5934
+ "authSessionSchema"
5935
+ ],
5936
+ otter: "stackwright-pro-auth-otter",
5937
+ artifactKey: "authConfig"
5938
+ },
5939
+ openapi: {
5940
+ description: "OpenAPI spec integration \u2014 collection config, endpoint filters, actions",
5941
+ interfaces: [
5942
+ "OpenAPIConfig",
5943
+ "ActionConfig",
5944
+ "EndpointFilter",
5945
+ "ApprovedSpec",
5946
+ "PrebuildSecurityConfig",
5947
+ "SiteConfig",
5948
+ "ValidationResult"
5949
+ ],
5950
+ otter: "stackwright-pro-api-otter",
5951
+ artifactKey: "apiConfig"
5952
+ },
5953
+ pulse: {
5954
+ description: "Real-time data polling \u2014 source-agnostic polling options and states",
5955
+ interfaces: ["PulseOptions", "PulseMeta", "PulseState"],
5956
+ note: "React-bound types (PulseProps, PulseIndicatorProps) remain in @stackwright-pro/pulse"
5957
+ },
5958
+ enterprise: {
5959
+ description: "Enterprise collection access \u2014 multi-tenant provider extension",
5960
+ interfaces: [
5961
+ "EnterpriseCollectionProvider",
5962
+ "CollectionProvider",
5963
+ "CollectionEntry",
5964
+ "CollectionListOptions",
5965
+ "CollectionListResult",
5966
+ "TenantFilter",
5967
+ "Collection"
5968
+ ],
5969
+ note: "CollectionProvider, CollectionEntry, CollectionListOptions, and CollectionListResult are re-exported from @stackwright/types (^1.5.0). EnterpriseCollectionProvider, TenantFilter, and Collection are Pro-only extensions."
5970
+ }
5971
+ }
5972
+ };
5973
+ }
5974
+ function registerTypeSchemasTool(server2) {
5975
+ server2.tool(
5976
+ "stackwright_pro_get_type_schemas",
5977
+ "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.",
5978
+ {
5979
+ format: z17.enum(["full", "domains-only"]).optional().default("full").describe("full = complete summary with all fields; domains-only = just domain names")
5980
+ },
5981
+ async ({ format }) => {
5982
+ const summary = buildTypeSchemaSummary();
5983
+ const output = format === "domains-only" ? Object.keys(summary.domains) : summary;
5984
+ return {
5985
+ content: [{ type: "text", text: JSON.stringify(output, null, 2) }]
5986
+ };
5987
+ }
5988
+ );
5989
+ }
5990
+
5991
+ // src/tools/scaffold-cleanup.ts
5992
+ import {
5993
+ existsSync as existsSync9,
5994
+ lstatSync as lstatSync8,
5995
+ unlinkSync as unlinkSync2,
5996
+ readFileSync as readFileSync9,
5997
+ writeFileSync as writeFileSync7,
5998
+ readdirSync as readdirSync3,
5999
+ rmdirSync,
6000
+ mkdirSync as mkdirSync7
6001
+ } from "fs";
6002
+ import { join as join9, dirname as dirname2 } from "path";
6003
+ var SCAFFOLD_FILES_TO_DELETE = [
6004
+ "content/posts/getting-started.yaml",
6005
+ "content/posts/hello-world.yaml"
6006
+ ];
6007
+ var GETTING_STARTED_SCAFFOLD_FINGERPRINTS = [
6008
+ "Welcome to your new Stackwright",
6009
+ "Petstore API",
6010
+ "Petstore"
6011
+ ];
6012
+ var POST_FILE_EXTENSIONS = [".yaml", ".yml", ".md", ".mdx"];
6013
+ var POSTS_COLLECTION_FILE = "_collection.yaml";
6014
+ var SCAFFOLD_DIRS_TO_PRUNE = [
6015
+ "pages/getting-started",
6016
+ "content/posts"
6017
+ // Don't prune 'content' — user may have other content directories
6018
+ ];
6019
+ var NOT_FOUND_PATH = "app/not-found.tsx";
6020
+ var FALLBACK_COLORS = {
6021
+ background: "#ffffff",
6022
+ foreground: "#171717",
6023
+ primary: "#525252",
6024
+ mutedForeground: "#737373"
6025
+ };
6026
+ function readThemeColors(cwd) {
6027
+ const tokenPath = join9(cwd, ".stackwright", "artifacts", "theme-tokens.json");
6028
+ if (!existsSync9(tokenPath)) return { ...FALLBACK_COLORS };
6029
+ const stat = lstatSync8(tokenPath);
6030
+ if (stat.isSymbolicLink()) return { ...FALLBACK_COLORS };
6031
+ try {
6032
+ const raw = JSON.parse(readFileSync9(tokenPath, "utf-8"));
6033
+ const css = raw?.cssVariables ?? {};
6034
+ const toHsl = (hslValue) => {
6035
+ if (!hslValue || typeof hslValue !== "string") return null;
6036
+ return `hsl(${hslValue})`;
6037
+ };
6038
+ return {
6039
+ background: toHsl(css["--background"]) ?? FALLBACK_COLORS.background,
6040
+ foreground: toHsl(css["--foreground"]) ?? FALLBACK_COLORS.foreground,
6041
+ primary: toHsl(css["--primary"]) ?? FALLBACK_COLORS.primary,
6042
+ mutedForeground: toHsl(css["--muted-foreground"]) ?? FALLBACK_COLORS.mutedForeground
6043
+ };
6044
+ } catch {
6045
+ return { ...FALLBACK_COLORS };
6046
+ }
6047
+ }
6048
+ function generateNotFoundPage(colors) {
6049
+ return `export default function NotFound() {
6050
+ return (
6051
+ <div
6052
+ style={{
6053
+ display: 'flex',
6054
+ flexDirection: 'column',
6055
+ alignItems: 'center',
6056
+ justifyContent: 'center',
6057
+ minHeight: '100vh',
6058
+ backgroundColor: '${colors.background}',
6059
+ color: '${colors.foreground}',
6060
+ fontFamily: 'system-ui, -apple-system, sans-serif',
6061
+ padding: '2rem',
6062
+ textAlign: 'center',
6063
+ }}
6064
+ >
6065
+ <h1 style={{ fontSize: '4rem', fontWeight: 700, margin: 0, color: '${colors.primary}' }}>
6066
+ 404
6067
+ </h1>
6068
+ <p style={{ fontSize: '1.25rem', color: '${colors.mutedForeground}', marginTop: '0.5rem' }}>
6069
+ Page not found
6070
+ </p>
6071
+ <a
6072
+ href="/"
6073
+ style={{
6074
+ marginTop: '2rem',
6075
+ padding: '0.75rem 1.5rem',
6076
+ backgroundColor: '${colors.primary}',
6077
+ color: '${colors.background}',
6078
+ borderRadius: '0.5rem',
6079
+ textDecoration: 'none',
6080
+ fontSize: '0.875rem',
6081
+ fontWeight: 500,
6082
+ }}
6083
+ >
6084
+ Go Home
6085
+ </a>
6086
+ </div>
6087
+ );
6088
+ }
6089
+ `;
6090
+ }
6091
+ function isSafePath(fullPath) {
6092
+ if (!existsSync9(fullPath)) return true;
6093
+ const stat = lstatSync8(fullPath);
6094
+ return !stat.isSymbolicLink();
6095
+ }
6096
+ function isDirEmpty(dirPath) {
6097
+ if (!existsSync9(dirPath)) return false;
6098
+ const stat = lstatSync8(dirPath);
6099
+ if (!stat.isDirectory()) return false;
6100
+ return readdirSync3(dirPath).length === 0;
6101
+ }
6102
+ function handleCleanupScaffold(_cwd) {
6103
+ const cwd = _cwd ?? process.cwd();
6104
+ const result = {
6105
+ deleted: [],
6106
+ rewritten: [],
6107
+ skipped: [],
6108
+ errors: [],
6109
+ prunedDirs: [],
6110
+ cleanupWarnings: []
6111
+ };
6112
+ for (const relPath of SCAFFOLD_FILES_TO_DELETE) {
6113
+ const fullPath = join9(cwd, relPath);
6114
+ if (!existsSync9(fullPath)) {
6115
+ result.skipped.push(relPath);
6116
+ continue;
6117
+ }
6118
+ if (!isSafePath(fullPath)) {
6119
+ result.errors.push(`Refusing to delete symlink: ${relPath}`);
6120
+ continue;
6121
+ }
6122
+ try {
6123
+ unlinkSync2(fullPath);
6124
+ result.deleted.push(relPath);
6125
+ } catch (err) {
6126
+ result.errors.push(`Failed to delete ${relPath}: ${String(err)}`);
6127
+ }
6128
+ }
6129
+ {
6130
+ const relPath = "pages/getting-started/content.yml";
6131
+ const fullPath = join9(cwd, relPath);
6132
+ if (!existsSync9(fullPath)) {
6133
+ result.skipped.push(relPath);
6134
+ } else if (!isSafePath(fullPath)) {
6135
+ result.errors.push(`Refusing to delete symlink: ${relPath}`);
6136
+ } else {
6137
+ const content = readFileSync9(fullPath, "utf-8");
6138
+ const isScaffoldDefault = GETTING_STARTED_SCAFFOLD_FINGERPRINTS.some(
6139
+ (marker) => content.includes(marker)
6140
+ );
6141
+ if (isScaffoldDefault) {
6142
+ try {
6143
+ unlinkSync2(fullPath);
6144
+ result.deleted.push(relPath);
6145
+ } catch (err) {
6146
+ result.errors.push(`Failed to delete ${relPath}: ${String(err)}`);
6147
+ }
6148
+ } else {
6149
+ result.cleanupWarnings.push(
6150
+ `pages/getting-started/content.yml preserved \u2014 no scaffold fingerprint found (user-modified content)`
6151
+ );
6152
+ }
6153
+ }
6154
+ }
6155
+ {
6156
+ const relPath = `content/posts/${POSTS_COLLECTION_FILE}`;
6157
+ const fullPath = join9(cwd, relPath);
6158
+ const postsDir = join9(cwd, "content/posts");
6159
+ if (!existsSync9(fullPath)) {
6160
+ result.skipped.push(relPath);
6161
+ } else if (!isSafePath(fullPath)) {
6162
+ result.errors.push(`Refusing to delete symlink: ${relPath}`);
6163
+ } else if (!existsSync9(postsDir)) {
6164
+ result.skipped.push(relPath);
6165
+ } else {
6166
+ const userPostFiles = readdirSync3(postsDir).filter(
6167
+ (f) => f !== POSTS_COLLECTION_FILE && POST_FILE_EXTENSIONS.some((ext) => f.endsWith(ext))
6168
+ );
6169
+ if (userPostFiles.length === 0) {
6170
+ try {
6171
+ unlinkSync2(fullPath);
6172
+ result.deleted.push(relPath);
6173
+ } catch (err) {
6174
+ result.errors.push(`Failed to delete ${relPath}: ${String(err)}`);
6175
+ }
6176
+ } else {
6177
+ result.cleanupWarnings.push(
6178
+ `content/posts/_collection.yaml preserved \u2014 ${userPostFiles.length} user post file(s) exist: ${userPostFiles.slice(0, 3).join(", ")}`
6179
+ );
6180
+ }
6181
+ }
6182
+ }
6183
+ for (const relDir of SCAFFOLD_DIRS_TO_PRUNE) {
6184
+ const fullDir = join9(cwd, relDir);
6185
+ if (!existsSync9(fullDir)) continue;
6186
+ if (!isSafePath(fullDir)) {
6187
+ result.errors.push(`Refusing to prune symlink directory: ${relDir}`);
6188
+ continue;
6189
+ }
6190
+ if (isDirEmpty(fullDir)) {
6191
+ try {
6192
+ rmdirSync(fullDir);
6193
+ result.prunedDirs.push(relDir);
6194
+ } catch (err) {
6195
+ result.errors.push(`Failed to prune directory ${relDir}: ${String(err)}`);
6196
+ }
6197
+ }
6198
+ }
6199
+ {
6200
+ const fullPath = join9(cwd, NOT_FOUND_PATH);
6201
+ if (!existsSync9(fullPath)) {
6202
+ result.skipped.push(NOT_FOUND_PATH);
6203
+ } else if (!isSafePath(fullPath)) {
6204
+ result.errors.push(`Refusing to rewrite symlink: ${NOT_FOUND_PATH}`);
6205
+ } else {
6206
+ try {
6207
+ const colors = readThemeColors(cwd);
6208
+ const content = generateNotFoundPage(colors);
6209
+ const dir = dirname2(fullPath);
6210
+ mkdirSync7(dir, { recursive: true });
6211
+ writeFileSync7(fullPath, content, "utf-8");
6212
+ result.rewritten.push(NOT_FOUND_PATH);
6213
+ } catch (err) {
6214
+ result.errors.push(`Failed to rewrite ${NOT_FOUND_PATH}: ${String(err)}`);
6215
+ }
6216
+ }
6217
+ }
6218
+ return {
6219
+ text: JSON.stringify(result),
6220
+ isError: false
6221
+ };
6222
+ }
6223
+ function registerScaffoldCleanupTools(server2) {
6224
+ const DESC = "Deterministic scaffold remnant cleanup \u2014 removes stale OSS scaffold files after raft run.";
6225
+ server2.tool(
6226
+ "stackwright_pro_cleanup_scaffold",
6227
+ `Remove/rewrite stale scaffold files (blog posts, hardcoded not-found page) after the raft pipeline completes. ${DESC}`,
6228
+ {},
6229
+ async () => {
6230
+ const r = handleCleanupScaffold();
6231
+ return {
6232
+ content: [{ type: "text", text: r.text }],
6233
+ isError: r.isError
6234
+ };
6235
+ }
6236
+ );
6237
+ }
6238
+
6239
+ // src/tools/contrast.ts
6240
+ import { z as z18 } from "zod";
6241
+ function linearizeChannel(c255) {
6242
+ const c = c255 / 255;
6243
+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
6244
+ }
6245
+ function relativeLuminance(r, g, b) {
6246
+ return 0.2126 * linearizeChannel(r) + 0.7152 * linearizeChannel(g) + 0.0722 * linearizeChannel(b);
6247
+ }
6248
+ function contrastRatioFromLuminance(l1, l2) {
6249
+ const lighter = Math.max(l1, l2);
6250
+ const darker = Math.min(l1, l2);
6251
+ return (lighter + 0.05) / (darker + 0.05);
6252
+ }
6253
+ function parseHex(hex) {
6254
+ const clean = hex.replace("#", "").trim().toLowerCase();
6255
+ if (clean.length === 3) {
6256
+ const r = parseInt(clean.charAt(0) + clean.charAt(0), 16);
6257
+ const g = parseInt(clean.charAt(1) + clean.charAt(1), 16);
6258
+ const b = parseInt(clean.charAt(2) + clean.charAt(2), 16);
6259
+ if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
6260
+ return [r, g, b];
6261
+ }
6262
+ if (clean.length === 6) {
6263
+ const r = parseInt(clean.slice(0, 2), 16);
6264
+ const g = parseInt(clean.slice(2, 4), 16);
6265
+ const b = parseInt(clean.slice(4, 6), 16);
6266
+ if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
6267
+ return [r, g, b];
6268
+ }
6269
+ return null;
6270
+ }
6271
+ function hslToRgb(h, s, l) {
6272
+ const hn = h / 360;
6273
+ const sn = s / 100;
6274
+ const ln = l / 100;
6275
+ const hue2rgb = (p, q, t) => {
6276
+ let tt = t;
6277
+ if (tt < 0) tt += 1;
6278
+ if (tt > 1) tt -= 1;
6279
+ if (tt < 1 / 6) return p + (q - p) * 6 * tt;
6280
+ if (tt < 1 / 2) return q;
6281
+ if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6;
6282
+ return p;
6283
+ };
6284
+ let r, g, b;
6285
+ if (sn === 0) {
6286
+ r = g = b = ln;
6287
+ } else {
6288
+ const q = ln < 0.5 ? ln * (1 + sn) : ln + sn - ln * sn;
6289
+ const p = 2 * ln - q;
6290
+ r = hue2rgb(p, q, hn + 1 / 3);
6291
+ g = hue2rgb(p, q, hn);
6292
+ b = hue2rgb(p, q, hn - 1 / 3);
6293
+ }
6294
+ return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
6295
+ }
6296
+ function parseHsl(hsl) {
6297
+ let str = hsl.replace(/^hsl\s*\(\s*/i, "").replace(/\s*\)$/, "").trim();
6298
+ str = str.replace(/%/g, "");
6299
+ const parts = str.split(/[\s,]+/).filter(Boolean);
6300
+ if (parts.length !== 3) return null;
6301
+ const h = parseFloat(parts[0]);
6302
+ const s = parseFloat(parts[1]);
6303
+ const l = parseFloat(parts[2]);
6304
+ if (isNaN(h) || isNaN(s) || isNaN(l)) return null;
6305
+ return hslToRgb(h, s, l);
6306
+ }
6307
+ function parseColor(color) {
6308
+ const trimmed = color.trim();
6309
+ if (trimmed.startsWith("#")) return parseHex(trimmed);
6310
+ if (/^hsl\s*\(/i.test(trimmed)) return parseHsl(trimmed);
6311
+ if (/^\d[\d.]*[\s,]+\d[\d.]*%?[\s,]+\d[\d.]*%?$/.test(trimmed)) return parseHsl(trimmed);
6312
+ return null;
6313
+ }
6314
+ function rgbToHex(r, g, b) {
6315
+ return "#" + [r, g, b].map(
6316
+ (c) => Math.max(0, Math.min(255, Math.round(c))).toString(16).padStart(2, "0")
6317
+ ).join("");
6318
+ }
6319
+ function handleCheckContrast(fg, bg) {
6320
+ const fgRgb = parseColor(fg);
6321
+ const bgRgb = parseColor(bg);
6322
+ if (!fgRgb) throw new Error(`Cannot parse foreground color: "${fg}"`);
6323
+ if (!bgRgb) throw new Error(`Cannot parse background color: "${bg}"`);
6324
+ const fgL = relativeLuminance(...fgRgb);
6325
+ const bgL = relativeLuminance(...bgRgb);
6326
+ const ratio = parseFloat(contrastRatioFromLuminance(fgL, bgL).toFixed(2));
6327
+ return {
6328
+ fgHex: rgbToHex(...fgRgb),
6329
+ bgHex: rgbToHex(...bgRgb),
6330
+ ratio,
6331
+ aa: ratio >= 4.5,
6332
+ aaLarge: ratio >= 3,
6333
+ aaa: ratio >= 7,
6334
+ aaaLarge: ratio >= 4.5
6335
+ };
6336
+ }
6337
+ function handleDeriveAccessiblePalette(seed, targetRatio) {
6338
+ const seedRgb = parseColor(seed);
6339
+ if (!seedRgb) throw new Error(`Cannot parse seed color: "${seed}"`);
6340
+ const seedHex = rgbToHex(...seedRgb);
6341
+ const seedL = relativeLuminance(...seedRgb);
6342
+ const whiteRatio = parseFloat(contrastRatioFromLuminance(1, seedL).toFixed(2));
6343
+ const blackRatio = parseFloat(contrastRatioFromLuminance(0, seedL).toFixed(2));
6344
+ const whiteWorks = whiteRatio >= targetRatio;
6345
+ const blackWorks = blackRatio >= targetRatio;
6346
+ let strategy;
6347
+ let foreground;
6348
+ let ratio;
6349
+ let alternativeForeground;
6350
+ let alternativeRatio;
6351
+ if (blackWorks && whiteWorks) {
6352
+ if (blackRatio >= whiteRatio) {
6353
+ strategy = "black";
6354
+ foreground = "#000000";
6355
+ ratio = blackRatio;
6356
+ alternativeForeground = "#ffffff";
6357
+ alternativeRatio = whiteRatio;
6358
+ } else {
6359
+ strategy = "white";
6360
+ foreground = "#ffffff";
6361
+ ratio = whiteRatio;
6362
+ alternativeForeground = "#000000";
6363
+ alternativeRatio = blackRatio;
6364
+ }
6365
+ } else if (blackWorks) {
6366
+ strategy = "black";
6367
+ foreground = "#000000";
6368
+ ratio = blackRatio;
6369
+ alternativeForeground = "#ffffff";
6370
+ alternativeRatio = whiteRatio;
6371
+ } else if (whiteWorks) {
6372
+ strategy = "white";
6373
+ foreground = "#ffffff";
6374
+ ratio = whiteRatio;
6375
+ alternativeForeground = "#000000";
6376
+ alternativeRatio = blackRatio;
6377
+ } else {
6378
+ strategy = "unachievable";
6379
+ if (blackRatio >= whiteRatio) {
6380
+ foreground = "#000000";
6381
+ ratio = blackRatio;
6382
+ alternativeForeground = "#ffffff";
6383
+ alternativeRatio = whiteRatio;
6384
+ } else {
6385
+ foreground = "#ffffff";
6386
+ ratio = whiteRatio;
6387
+ alternativeForeground = "#000000";
6388
+ alternativeRatio = blackRatio;
6389
+ }
6390
+ }
6391
+ return {
6392
+ seedHex,
6393
+ foreground,
6394
+ ratio,
6395
+ aa: ratio >= 4.5,
6396
+ aaLarge: ratio >= 3,
6397
+ aaa: ratio >= 7,
6398
+ meetsTarget: ratio >= targetRatio,
6399
+ strategy,
6400
+ alternativeForeground,
6401
+ alternativeRatio
6402
+ };
6403
+ }
6404
+ var PASS = "[PASS]";
6405
+ var FAIL = "[FAIL]";
6406
+ var mark = (ok) => ok ? PASS : FAIL;
6407
+ function registerContrastTools(server2) {
6408
+ server2.tool(
6409
+ "stackwright_pro_check_contrast",
6410
+ '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%").',
6411
+ {
6412
+ fg: z18.string().describe("Foreground (text) color \u2014 hex or HSL"),
6413
+ bg: z18.string().describe("Background color \u2014 hex or HSL")
6414
+ },
6415
+ async ({ fg, bg }) => {
6416
+ let result;
6417
+ try {
6418
+ result = handleCheckContrast(fg, bg);
6419
+ } catch (err) {
6420
+ return {
6421
+ content: [{ type: "text", text: `Error: ${err.message}` }]
6422
+ };
6423
+ }
6424
+ const text = [
6425
+ `WCAG 2.1 Contrast Check`,
6426
+ ``,
6427
+ ` Foreground : ${result.fgHex}`,
6428
+ ` Background : ${result.bgHex}`,
6429
+ ` Ratio : ${result.ratio}:1`,
6430
+ ``,
6431
+ ` ${mark(result.aa)} AA \u2014 normal text (\u22654.5:1)`,
6432
+ ` ${mark(result.aaLarge)} AA \u2014 large text (\u22653.0:1)`,
6433
+ ` ${mark(result.aaa)} AAA \u2014 normal text (\u22657.0:1)`,
6434
+ ` ${mark(result.aaaLarge)} AAA \u2014 large text (\u22654.5:1)`
6435
+ ].join("\n");
6436
+ return { content: [{ type: "text", text }] };
6437
+ }
6438
+ );
6439
+ server2.tool(
6440
+ "stackwright_pro_derive_accessible_palette",
6441
+ '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%").',
6442
+ {
6443
+ seed: z18.string().describe("Background (seed) color \u2014 hex or HSL"),
6444
+ targetRatio: numCoerce(z18.number().default(4.5)).describe(
6445
+ "Minimum required contrast ratio (default 4.5 for WCAG AA)"
6446
+ )
6447
+ },
6448
+ async ({ seed, targetRatio }) => {
6449
+ let result;
6450
+ try {
6451
+ result = handleDeriveAccessiblePalette(seed, targetRatio ?? 4.5);
6452
+ } catch (err) {
6453
+ return {
6454
+ content: [{ type: "text", text: `Error: ${err.message}` }]
6455
+ };
6456
+ }
6457
+ const metLine = result.meetsTarget ? `${PASS} Meets target (${targetRatio}:1)` : `${FAIL} Target (${targetRatio}:1) UNACHIEVABLE with white or black \u2014 best available used`;
6458
+ const altNote = result.alternativeRatio >= (targetRatio ?? 4.5) ? `also passes (${result.alternativeRatio}:1)` : `fails at ${result.alternativeRatio}:1`;
6459
+ const text = [
6460
+ `Accessible Palette Derivation`,
6461
+ ``,
6462
+ ` Background (seed) : ${result.seedHex}`,
6463
+ ` Foreground : ${result.foreground} (${result.strategy})`,
6464
+ ` Contrast ratio : ${result.ratio}:1`,
6465
+ ` ${metLine}`,
6466
+ ``,
6467
+ ` ${mark(result.aa)} AA \u2014 normal text (\u22654.5:1)`,
6468
+ ` ${mark(result.aaLarge)} AA \u2014 large text (\u22653.0:1)`,
6469
+ ` ${mark(result.aaa)} AAA \u2014 normal text (\u22657.0:1)`,
6470
+ ``,
6471
+ ` Alternative (${result.alternativeForeground}): ${altNote}`
6472
+ ].join("\n");
6473
+ return { content: [{ type: "text", text }] };
6474
+ }
6475
+ );
6476
+ }
6477
+
3425
6478
  // package.json
3426
6479
  var package_default = {
3427
6480
  dependencies: {
3428
6481
  "@modelcontextprotocol/sdk": "^1.10.0",
3429
6482
  "@stackwright-pro/cli-data-explorer": "workspace:*",
3430
- zod: "^4.3.6"
6483
+ "@stackwright-pro/types": "workspace:*",
6484
+ "@types/js-yaml": "^4.0.9",
6485
+ "js-yaml": "^4.2.0",
6486
+ zod: "^4.4.3"
3431
6487
  },
3432
6488
  devDependencies: {
3433
- "@types/node": "^24.1.0",
3434
- tsup: "^8.5.0",
3435
- typescript: "^5.8.3",
3436
- vitest: "^4.0.18"
6489
+ "@types/node": "catalog:",
6490
+ tsup: "catalog:",
6491
+ typescript: "catalog:",
6492
+ vitest: "catalog:"
3437
6493
  },
3438
6494
  scripts: {
3439
6495
  prepublishOnly: "node scripts/verify-integrity-sync.js",
@@ -3444,10 +6500,13 @@ var package_default = {
3444
6500
  "test:coverage": "vitest run --coverage"
3445
6501
  },
3446
6502
  name: "@stackwright-pro/mcp",
3447
- version: "0.2.0-alpha.9",
6503
+ version: "0.2.0-alpha.90",
3448
6504
  description: "MCP tools for Stackwright Pro - Data Explorer, Security, ISR, and Dashboard generation",
3449
- license: "PROPRIETARY",
6505
+ license: "SEE LICENSE IN LICENSE",
3450
6506
  main: "./dist/server.js",
6507
+ bin: {
6508
+ "stackwright-pro-mcp": "./dist/server.js"
6509
+ },
3451
6510
  module: "./dist/server.mjs",
3452
6511
  types: "./dist/server.d.ts",
3453
6512
  exports: {
@@ -3460,6 +6519,11 @@ var package_default = {
3460
6519
  types: "./dist/integrity.d.ts",
3461
6520
  import: "./dist/integrity.mjs",
3462
6521
  require: "./dist/integrity.js"
6522
+ },
6523
+ "./type-schemas": {
6524
+ types: "./dist/tools/type-schemas.d.ts",
6525
+ import: "./dist/tools/type-schemas.mjs",
6526
+ require: "./dist/tools/type-schemas.js"
3463
6527
  }
3464
6528
  },
3465
6529
  files: [
@@ -3487,9 +6551,24 @@ registerPipelineTools(server);
3487
6551
  registerSafeWriteTools(server);
3488
6552
  registerAuthTools(server);
3489
6553
  registerIntegrityTools(server);
6554
+ registerArtifactSigningTools(server);
3490
6555
  registerDomainTools(server);
6556
+ registerTypeSchemasTool(server);
6557
+ registerValidateYamlFragmentTool(server);
6558
+ registerGetSchemaTool(server);
6559
+ registerScaffoldCleanupTools(server);
6560
+ registerContrastTools(server);
3491
6561
  async function main() {
3492
6562
  const transport = new StdioServerTransport();
6563
+ try {
6564
+ const servicesRegisterPkg = "@stackwright-services/mcp/register";
6565
+ const mod = await import(servicesRegisterPkg);
6566
+ if (typeof mod.registerServicesTools === "function") {
6567
+ mod.registerServicesTools(server);
6568
+ console.error("Stackwright Services tools registered on pro MCP");
6569
+ }
6570
+ } catch {
6571
+ }
3493
6572
  await server.connect(transport);
3494
6573
  console.error("Stackwright Pro MCP server running on stdio");
3495
6574
  }