@stackwright-pro/mcp 0.2.0-alpha.7 → 0.2.0-alpha.72
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/LICENSE +21 -0
- package/dist/integrity.d.mts +29 -1
- package/dist/integrity.d.ts +29 -1
- package/dist/integrity.js +65 -10
- package/dist/integrity.js.map +1 -1
- package/dist/integrity.mjs +64 -10
- package/dist/integrity.mjs.map +1 -1
- package/dist/server.js +2942 -394
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +2974 -401
- package/dist/server.mjs.map +1 -1
- package/dist/tools/type-schemas.d.mts +51 -0
- package/dist/tools/type-schemas.d.ts +51 -0
- package/dist/tools/type-schemas.js +120 -0
- package/dist/tools/type-schemas.js.map +1 -0
- package/dist/tools/type-schemas.mjs +94 -0
- package/dist/tools/type-schemas.mjs.map +1 -0
- package/package.json +17 -8
package/dist/server.js
CHANGED
|
@@ -27,15 +27,44 @@ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
|
27
27
|
var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
|
|
28
28
|
|
|
29
29
|
// src/tools/data-explorer.ts
|
|
30
|
-
var
|
|
30
|
+
var import_zod2 = require("zod");
|
|
31
31
|
var import_cli_data_explorer = require("@stackwright-pro/cli-data-explorer");
|
|
32
|
+
|
|
33
|
+
// src/coerce.ts
|
|
34
|
+
var import_zod = require("zod");
|
|
35
|
+
function jsonCoerce(schema) {
|
|
36
|
+
return import_zod.z.preprocess((v) => {
|
|
37
|
+
if (typeof v === "string") {
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(v);
|
|
40
|
+
} catch {
|
|
41
|
+
return v;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return v;
|
|
45
|
+
}, schema);
|
|
46
|
+
}
|
|
47
|
+
function boolCoerce(schema) {
|
|
48
|
+
return import_zod.z.preprocess((v) => v === "true" ? true : v === "false" ? false : v, schema);
|
|
49
|
+
}
|
|
50
|
+
function numCoerce(schema) {
|
|
51
|
+
return import_zod.z.preprocess((v) => {
|
|
52
|
+
if (typeof v === "string" && v.trim() !== "") {
|
|
53
|
+
const n = Number(v);
|
|
54
|
+
if (!Number.isNaN(n)) return n;
|
|
55
|
+
}
|
|
56
|
+
return v;
|
|
57
|
+
}, schema);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/tools/data-explorer.ts
|
|
32
61
|
function registerDataExplorerTools(server2) {
|
|
33
62
|
server2.tool(
|
|
34
63
|
"stackwright_pro_list_entities",
|
|
35
64
|
"List all available API entities from OpenAPI specs or generated Zod schemas. Use this to discover what entities are available before generating endpoint filters. Returns entity names, endpoints, and field counts. Part of the Pro Otter Raft for building API-integrated Stackwright applications.",
|
|
36
65
|
{
|
|
37
|
-
specPath:
|
|
38
|
-
projectRoot:
|
|
66
|
+
specPath: import_zod2.z.string().optional().describe("Path to OpenAPI spec file (YAML or JSON)"),
|
|
67
|
+
projectRoot: import_zod2.z.string().optional().describe("Project root directory (auto-detected if omitted)")
|
|
39
68
|
},
|
|
40
69
|
async ({ specPath, projectRoot }) => {
|
|
41
70
|
const result = (0, import_cli_data_explorer.listEntities)({
|
|
@@ -83,9 +112,13 @@ function registerDataExplorerTools(server2) {
|
|
|
83
112
|
"stackwright_pro_generate_filter",
|
|
84
113
|
"Generate endpoint filter configuration from selected entities. Creates include/exclude patterns for stackwright.yml OpenAPI integration. Use this after stackwright_pro_list_entities to select which API endpoints the application needs. Only selected endpoints will generate client code, reducing bundle size and improving security.",
|
|
85
114
|
{
|
|
86
|
-
selectedEntities:
|
|
87
|
-
|
|
88
|
-
|
|
115
|
+
selectedEntities: jsonCoerce(import_zod2.z.array(import_zod2.z.string())).describe(
|
|
116
|
+
'Entity slugs to include (e.g., ["equipment", "supplies"])'
|
|
117
|
+
),
|
|
118
|
+
excludePatterns: jsonCoerce(import_zod2.z.array(import_zod2.z.string()).optional()).describe(
|
|
119
|
+
'Glob patterns to exclude (e.g., ["/admin/**", "/reports/**"])'
|
|
120
|
+
),
|
|
121
|
+
projectRoot: import_zod2.z.string().optional().describe("Project root directory")
|
|
89
122
|
},
|
|
90
123
|
async ({ selectedEntities, excludePatterns, projectRoot }) => {
|
|
91
124
|
const result = (0, import_cli_data_explorer.generateFilter)({
|
|
@@ -141,7 +174,7 @@ function registerDataExplorerTools(server2) {
|
|
|
141
174
|
}
|
|
142
175
|
|
|
143
176
|
// src/tools/security.ts
|
|
144
|
-
var
|
|
177
|
+
var import_zod3 = require("zod");
|
|
145
178
|
var import_crypto = require("crypto");
|
|
146
179
|
var import_fs = __toESM(require("fs"));
|
|
147
180
|
var import_path = __toESM(require("path"));
|
|
@@ -150,8 +183,8 @@ function registerSecurityTools(server2) {
|
|
|
150
183
|
"stackwright_pro_validate_spec",
|
|
151
184
|
"Validate an OpenAPI spec against the enterprise approved-specs configuration. Checks if the spec URL is on the allowlist and verifies SHA-256 hash integrity. Use this in enterprise environments where only pre-approved API specs are allowed. Fails build if spec is not approved or has been modified.",
|
|
152
185
|
{
|
|
153
|
-
specPath:
|
|
154
|
-
configPath:
|
|
186
|
+
specPath: import_zod3.z.string().describe("URL or file path to the OpenAPI spec to validate"),
|
|
187
|
+
configPath: import_zod3.z.string().optional().describe("Path to stackwright.yml with prebuild.security config")
|
|
155
188
|
},
|
|
156
189
|
async ({ specPath, configPath }) => {
|
|
157
190
|
let securityEnabled = false;
|
|
@@ -259,16 +292,15 @@ Status: Valid (${allowlist.length} specs on allowlist)`
|
|
|
259
292
|
"stackwright_pro_add_approved_spec",
|
|
260
293
|
"Add an OpenAPI spec to the approved-specs allowlist in stackwright.yml. Computes the SHA-256 hash of the spec and adds it to the security configuration. Use this when onboarding a new API in enterprise environments.",
|
|
261
294
|
{
|
|
262
|
-
name:
|
|
263
|
-
url:
|
|
264
|
-
configPath:
|
|
295
|
+
name: import_zod3.z.string().describe("Human-readable name for the spec"),
|
|
296
|
+
url: import_zod3.z.string().describe("URL or file path to the OpenAPI spec"),
|
|
297
|
+
configPath: import_zod3.z.string().optional().describe("Path to stackwright.yml")
|
|
265
298
|
},
|
|
266
299
|
async ({ name, url, configPath }) => {
|
|
267
300
|
const configFile = configPath || import_path.default.join(process.cwd(), "stackwright.yml");
|
|
268
301
|
let sha256 = "<computed-at-build>";
|
|
269
302
|
try {
|
|
270
303
|
if (url.startsWith("http://") || url.startsWith("https://")) {
|
|
271
|
-
sha256 = "<computed-at-build>";
|
|
272
304
|
} else if (import_fs.default.existsSync(url)) {
|
|
273
305
|
const specContent = import_fs.default.readFileSync(url, "utf8");
|
|
274
306
|
sha256 = (0, import_crypto.createHash)("sha256").update(specContent).digest("hex");
|
|
@@ -315,7 +347,7 @@ SHA-256 computed: ${sha256}`
|
|
|
315
347
|
"stackwright_pro_list_approved_specs",
|
|
316
348
|
"List all specs currently on the approved-specs allowlist. Shows spec names, URLs, and hash prefixes. Use this to audit what APIs are approved in the project.",
|
|
317
349
|
{
|
|
318
|
-
configPath:
|
|
350
|
+
configPath: import_zod3.z.string().optional().describe("Path to stackwright.yml")
|
|
319
351
|
},
|
|
320
352
|
async ({ configPath }) => {
|
|
321
353
|
const configFile = configPath || import_path.default.join(process.cwd(), "stackwright.yml");
|
|
@@ -384,16 +416,18 @@ SHA-256 computed: ${sha256}`
|
|
|
384
416
|
}
|
|
385
417
|
|
|
386
418
|
// src/tools/isr.ts
|
|
387
|
-
var
|
|
419
|
+
var import_zod4 = require("zod");
|
|
388
420
|
function registerIsrTools(server2) {
|
|
389
421
|
server2.tool(
|
|
390
422
|
"stackwright_pro_configure_isr",
|
|
391
423
|
"Configure Incremental Static Regeneration (ISR) for an API-backed collection. ISR allows API data to be cached and refreshed on a schedule, providing real-time data with the performance of static generation. Use this after stackwright_pro_generate_filter to set revalidation intervals.",
|
|
392
424
|
{
|
|
393
|
-
collection:
|
|
394
|
-
revalidateSeconds:
|
|
395
|
-
|
|
396
|
-
|
|
425
|
+
collection: import_zod4.z.string().describe('Collection name (e.g., "equipment", "supplies")'),
|
|
426
|
+
revalidateSeconds: numCoerce(import_zod4.z.number().optional()).describe(
|
|
427
|
+
"Revalidation interval in seconds (default: 60)"
|
|
428
|
+
),
|
|
429
|
+
fallback: import_zod4.z.enum(["blocking", "true", "false"]).optional().describe("Fallback behavior for new pages"),
|
|
430
|
+
configPath: import_zod4.z.string().optional().describe("Path to stackwright.yml")
|
|
397
431
|
},
|
|
398
432
|
async ({ collection, revalidateSeconds = 60, fallback = "blocking", configPath }) => {
|
|
399
433
|
const revalidate = revalidateSeconds;
|
|
@@ -404,7 +438,7 @@ function registerIsrTools(server2) {
|
|
|
404
438
|
isr:
|
|
405
439
|
revalidate: ${revalidate}
|
|
406
440
|
fallback: ${fallback}`;
|
|
407
|
-
let description
|
|
441
|
+
let description;
|
|
408
442
|
if (revalidate < 60) {
|
|
409
443
|
description = "\u26A1 Very fresh data (revalidate every " + revalidate + "s)";
|
|
410
444
|
} else if (revalidate < 300) {
|
|
@@ -436,14 +470,16 @@ ${yamlSnippet}
|
|
|
436
470
|
"stackwright_pro_configure_isr_batch",
|
|
437
471
|
"Configure ISR for multiple collections at once. More efficient than calling stackwright_pro_configure_isr multiple times. Provide different revalidation intervals based on data freshness requirements.",
|
|
438
472
|
{
|
|
439
|
-
collections:
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
473
|
+
collections: jsonCoerce(
|
|
474
|
+
import_zod4.z.array(
|
|
475
|
+
import_zod4.z.object({
|
|
476
|
+
name: import_zod4.z.string().describe("Collection name"),
|
|
477
|
+
revalidateSeconds: numCoerce(import_zod4.z.number().optional()).describe("Revalidation interval")
|
|
478
|
+
})
|
|
479
|
+
)
|
|
444
480
|
).describe("Array of collection configurations"),
|
|
445
|
-
defaultFallback:
|
|
446
|
-
configPath:
|
|
481
|
+
defaultFallback: import_zod4.z.enum(["blocking", "true", "false"]).optional().describe("Default fallback behavior"),
|
|
482
|
+
configPath: import_zod4.z.string().optional().describe("Path to stackwright.yml")
|
|
447
483
|
},
|
|
448
484
|
async ({ collections, defaultFallback = "blocking", configPath }) => {
|
|
449
485
|
const lines = [`\u2699\uFE0F Batch ISR Configuration:
|
|
@@ -471,17 +507,17 @@ Fallback: ${defaultFallback}`);
|
|
|
471
507
|
}
|
|
472
508
|
|
|
473
509
|
// src/tools/dashboard.ts
|
|
474
|
-
var
|
|
510
|
+
var import_zod5 = require("zod");
|
|
475
511
|
var import_cli_data_explorer2 = require("@stackwright-pro/cli-data-explorer");
|
|
476
512
|
function registerDashboardTools(server2) {
|
|
477
513
|
server2.tool(
|
|
478
514
|
"stackwright_pro_generate_dashboard",
|
|
479
515
|
"Generate a dashboard page configuration for displaying API data. Creates YAML content for a Stackwright page with grid, metric_card, data_table, and collection_list content types. Use this after stackwright_pro_generate_filter to create pages for your API collections.",
|
|
480
516
|
{
|
|
481
|
-
entities:
|
|
482
|
-
layout:
|
|
483
|
-
pageTitle:
|
|
484
|
-
specPath:
|
|
517
|
+
entities: jsonCoerce(import_zod5.z.array(import_zod5.z.string())).describe("Entity slugs to include in dashboard"),
|
|
518
|
+
layout: import_zod5.z.enum(["grid", "table", "mixed"]).optional().describe("Dashboard layout style"),
|
|
519
|
+
pageTitle: import_zod5.z.string().optional().describe("Page title"),
|
|
520
|
+
specPath: import_zod5.z.string().optional().describe("Path to OpenAPI spec for entity details")
|
|
485
521
|
},
|
|
486
522
|
async ({ entities, layout = "mixed", pageTitle, specPath }) => {
|
|
487
523
|
let entityDetails = [];
|
|
@@ -567,9 +603,9 @@ ${yaml}
|
|
|
567
603
|
"stackwright_pro_generate_detail_page",
|
|
568
604
|
"Generate a detail view page for a single API entity. Creates YAML content for displaying all fields of an individual record. Use this to create detail pages that complement collection listing pages.",
|
|
569
605
|
{
|
|
570
|
-
entity:
|
|
571
|
-
slugField:
|
|
572
|
-
specPath:
|
|
606
|
+
entity: import_zod5.z.string().describe('Entity slug (e.g., "equipment")'),
|
|
607
|
+
slugField: import_zod5.z.string().optional().describe('Field to use as URL slug (default: "id")'),
|
|
608
|
+
specPath: import_zod5.z.string().optional().describe("Path to OpenAPI spec for field details")
|
|
573
609
|
},
|
|
574
610
|
async ({ entity, slugField = "id", specPath }) => {
|
|
575
611
|
let fields = [];
|
|
@@ -592,39 +628,49 @@ ${yaml}
|
|
|
592
628
|
` title: "${entityName} Details | {{ ${entity}.${slugField} }}"`,
|
|
593
629
|
"",
|
|
594
630
|
" content_items:",
|
|
595
|
-
" -
|
|
596
|
-
'
|
|
597
|
-
"
|
|
598
|
-
`
|
|
599
|
-
'
|
|
600
|
-
"
|
|
601
|
-
`
|
|
602
|
-
'
|
|
603
|
-
' background: "primary"',
|
|
604
|
-
' color: "text"',
|
|
631
|
+
" - type: text_block",
|
|
632
|
+
' label: "detail-header"',
|
|
633
|
+
" heading:",
|
|
634
|
+
` text: "{{ ${entity}.${slugField} }}"`,
|
|
635
|
+
' textSize: "h1"',
|
|
636
|
+
" textBlocks:",
|
|
637
|
+
` - text: "Details for this ${entity}"`,
|
|
638
|
+
' textSize: "body1"',
|
|
605
639
|
"",
|
|
606
|
-
" - grid
|
|
607
|
-
'
|
|
608
|
-
"
|
|
609
|
-
" items:"
|
|
640
|
+
" - type: grid",
|
|
641
|
+
' label: "detail-fields"',
|
|
642
|
+
" columns:"
|
|
610
643
|
];
|
|
611
644
|
const displayFields = fields.length > 0 ? fields.slice(0, 8) : [
|
|
612
645
|
{ name: slugField, type: "string" },
|
|
613
646
|
{ name: "created_at", type: "datetime" },
|
|
614
647
|
{ name: "updated_at", type: "datetime" }
|
|
615
648
|
];
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
yamlLines.push(
|
|
621
|
-
yamlLines.push(
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
649
|
+
const mid = Math.ceil(displayFields.length / 2);
|
|
650
|
+
const col1 = displayFields.slice(0, mid);
|
|
651
|
+
const col2 = displayFields.slice(mid);
|
|
652
|
+
for (const [colIndex, colFields] of [col1, col2].entries()) {
|
|
653
|
+
yamlLines.push(" - width: 1");
|
|
654
|
+
yamlLines.push(" content_items:");
|
|
655
|
+
for (const field of colFields) {
|
|
656
|
+
const label = field.name.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
|
|
657
|
+
yamlLines.push(" - type: text_block");
|
|
658
|
+
yamlLines.push(` label: "${field.name}-field"`);
|
|
659
|
+
yamlLines.push(" heading:");
|
|
660
|
+
yamlLines.push(` text: "${label}"`);
|
|
661
|
+
yamlLines.push(' textSize: "h4"');
|
|
662
|
+
yamlLines.push(" textBlocks:");
|
|
663
|
+
yamlLines.push(` - text: "{{ ${entity}.${field.name} }}"`);
|
|
664
|
+
yamlLines.push(' textSize: "body1"');
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
yamlLines.push("");
|
|
668
|
+
yamlLines.push(" - type: action_bar");
|
|
669
|
+
yamlLines.push(" actions:");
|
|
670
|
+
yamlLines.push(` - label: "<- Back to ${entityName}"`);
|
|
671
|
+
yamlLines.push(" action: navigate");
|
|
672
|
+
yamlLines.push(` href: "/${entity}"`);
|
|
673
|
+
yamlLines.push(" style: secondary");
|
|
628
674
|
const yaml = yamlLines.join("\n");
|
|
629
675
|
return {
|
|
630
676
|
content: [
|
|
@@ -645,7 +691,7 @@ ${yaml}
|
|
|
645
691
|
}
|
|
646
692
|
|
|
647
693
|
// src/tools/clarification.ts
|
|
648
|
-
var
|
|
694
|
+
var import_zod6 = require("zod");
|
|
649
695
|
var CONTRADICTION_PATTERNS = [
|
|
650
696
|
{
|
|
651
697
|
keywords: ["minimal", "clean", "simple"],
|
|
@@ -733,12 +779,14 @@ function registerClarificationTools(server2) {
|
|
|
733
779
|
"stackwright_pro_clarify",
|
|
734
780
|
"Ask the user for clarification when a specialist otter encounters ambiguity. This is for MID-EXECUTION questions, NOT upfront question collection (use the Question Manifest Protocol for that). Returns a structured response for the foreman to present to the user via ask_user_question (closed_choice) or directly (open_text).",
|
|
735
781
|
{
|
|
736
|
-
context:
|
|
737
|
-
question_type:
|
|
738
|
-
question:
|
|
739
|
-
choices:
|
|
740
|
-
|
|
741
|
-
|
|
782
|
+
context: import_zod6.z.string().optional().describe("Context about what the otter is trying to do"),
|
|
783
|
+
question_type: import_zod6.z.enum(["closed_choice", "open_text"]).describe("Type of question being asked"),
|
|
784
|
+
question: import_zod6.z.string().describe("The clarification question to ask the user"),
|
|
785
|
+
choices: jsonCoerce(import_zod6.z.array(import_zod6.z.string()).optional()).describe(
|
|
786
|
+
"Options for closed_choice questions"
|
|
787
|
+
),
|
|
788
|
+
priority: import_zod6.z.enum(["blocking", "preferred", "optional"]).optional().default("preferred").describe("How critical is this clarification? Default: preferred"),
|
|
789
|
+
target_field: import_zod6.z.string().optional().describe("What field/config does this clarify?")
|
|
742
790
|
},
|
|
743
791
|
async ({ context, question_type, question, choices, priority, target_field }) => {
|
|
744
792
|
const result = handleClarify({
|
|
@@ -767,8 +815,10 @@ function registerClarificationTools(server2) {
|
|
|
767
815
|
"stackwright_pro_detect_conflict",
|
|
768
816
|
"Detect when a user's stated preference conflicts with their selected choices. Uses keyword heuristics against known contradiction patterns (minimal vs vibrant, dark vs light, etc). Returns conflict details and resolution options.",
|
|
769
817
|
{
|
|
770
|
-
stated_preference:
|
|
771
|
-
selected_values:
|
|
818
|
+
stated_preference: import_zod6.z.string().describe("What the user said they wanted"),
|
|
819
|
+
selected_values: jsonCoerce(import_zod6.z.record(import_zod6.z.string(), import_zod6.z.string())).describe(
|
|
820
|
+
"What the user actually selected (field \u2192 value)"
|
|
821
|
+
)
|
|
772
822
|
},
|
|
773
823
|
async ({ stated_preference, selected_values }) => {
|
|
774
824
|
const result = handleDetectConflict({ stated_preference, selected_values });
|
|
@@ -813,7 +863,7 @@ ${result.resolution_options?.map((o) => ` \u2022 ${o}`).join("\n")}
|
|
|
813
863
|
}
|
|
814
864
|
|
|
815
865
|
// src/tools/packages.ts
|
|
816
|
-
var
|
|
866
|
+
var import_zod7 = require("zod");
|
|
817
867
|
var import_fs2 = require("fs");
|
|
818
868
|
var import_child_process = require("child_process");
|
|
819
869
|
var import_path2 = __toESM(require("path"));
|
|
@@ -834,17 +884,23 @@ function registerPackageTools(server2) {
|
|
|
834
884
|
"Ensures pro packages are present in a project's package.json. Safe to call multiple times \u2014 never overwrites existing version pins. Use this to bootstrap dependencies before specialist otters run. Pass includeBaseline: true to automatically include all required @stackwright-pro/* baseline dependencies. Safe to call on existing projects \u2014 never overwrites pinned versions.",
|
|
835
885
|
{
|
|
836
886
|
// FIX 3 (B-new-1): Zod v4 requires two-arg z.record(keySchema, valueSchema)
|
|
837
|
-
packages:
|
|
838
|
-
'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }'
|
|
887
|
+
packages: jsonCoerce(import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional().default({})).describe(
|
|
888
|
+
'Dependencies to add. Record<packageName, version>. e.g. { "@stackwright-pro/auth": "latest" }. Omit or pass {} when using includeBaseline: true.'
|
|
889
|
+
),
|
|
890
|
+
devPackages: jsonCoerce(import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional()).describe(
|
|
891
|
+
"devDependencies to add. Same format as packages."
|
|
839
892
|
),
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
893
|
+
scripts: jsonCoerce(import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional()).describe(
|
|
894
|
+
"npm scripts to add. Only adds if key does not already exist."
|
|
895
|
+
),
|
|
896
|
+
targetDir: import_zod7.z.string().optional().describe(
|
|
843
897
|
"Project directory containing package.json. Defaults to process.cwd(). Must be an absolute path within the current working directory."
|
|
844
898
|
),
|
|
845
|
-
runInstall:
|
|
846
|
-
|
|
847
|
-
|
|
899
|
+
runInstall: boolCoerce(import_zod7.z.boolean().optional().default(true)).describe(
|
|
900
|
+
"Run pnpm install after writing package.json. Defaults to true. Pass boolean true/false."
|
|
901
|
+
),
|
|
902
|
+
includeBaseline: boolCoerce(import_zod7.z.boolean().optional().default(false)).describe(
|
|
903
|
+
"When true, automatically merges BASELINE_DEPS and BASELINE_DEV_DEPS before applying packages/devPackages args. Safe to call on existing projects \u2014 never overwrites pinned versions. Pass boolean true/false."
|
|
848
904
|
)
|
|
849
905
|
},
|
|
850
906
|
async ({ packages, devPackages, scripts, targetDir, runInstall, includeBaseline }) => {
|
|
@@ -1002,11 +1058,11 @@ function setupPackages(opts) {
|
|
|
1002
1058
|
}
|
|
1003
1059
|
}
|
|
1004
1060
|
const raw = (0, import_fs2.readFileSync)(realPackageJsonPath, "utf8");
|
|
1005
|
-
const PackageJsonSchema =
|
|
1061
|
+
const PackageJsonSchema = import_zod7.z.object({
|
|
1006
1062
|
// Zod v4: z.record(keySchema, valueSchema) — two-arg form required
|
|
1007
|
-
dependencies:
|
|
1008
|
-
devDependencies:
|
|
1009
|
-
scripts:
|
|
1063
|
+
dependencies: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional(),
|
|
1064
|
+
devDependencies: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional(),
|
|
1065
|
+
scripts: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.string()).optional()
|
|
1010
1066
|
}).passthrough();
|
|
1011
1067
|
const schemaResult = PackageJsonSchema.safeParse(JSON.parse(raw));
|
|
1012
1068
|
if (!schemaResult.success) {
|
|
@@ -1088,8 +1144,9 @@ function setupPackages(opts) {
|
|
|
1088
1144
|
|
|
1089
1145
|
// src/tools/questions.ts
|
|
1090
1146
|
var import_promises = require("fs/promises");
|
|
1147
|
+
var import_node_fs = require("fs");
|
|
1091
1148
|
var import_node_path = require("path");
|
|
1092
|
-
var
|
|
1149
|
+
var import_zod8 = require("zod");
|
|
1093
1150
|
|
|
1094
1151
|
// src/question-adapter.ts
|
|
1095
1152
|
function truncate(str, maxLength) {
|
|
@@ -1274,23 +1331,30 @@ function answersToManifestFormat(answers, questions) {
|
|
|
1274
1331
|
return result;
|
|
1275
1332
|
}
|
|
1276
1333
|
|
|
1334
|
+
// src/validation.ts
|
|
1335
|
+
var SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
|
|
1336
|
+
var SAFE_QUESTION_ID = /^[a-z0-9][a-z0-9-]{0,63}$/i;
|
|
1337
|
+
function isValidPhase(phase) {
|
|
1338
|
+
return SAFE_PHASE.test(phase);
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1277
1341
|
// src/tools/questions.ts
|
|
1278
|
-
var ManifestQuestionSchema =
|
|
1279
|
-
id:
|
|
1280
|
-
question:
|
|
1281
|
-
type:
|
|
1282
|
-
required:
|
|
1283
|
-
options:
|
|
1284
|
-
|
|
1285
|
-
label:
|
|
1286
|
-
value:
|
|
1342
|
+
var ManifestQuestionSchema = import_zod8.z.object({
|
|
1343
|
+
id: import_zod8.z.string(),
|
|
1344
|
+
question: import_zod8.z.string(),
|
|
1345
|
+
type: import_zod8.z.enum(["text", "select", "multi-select", "confirm"]),
|
|
1346
|
+
required: import_zod8.z.boolean().optional(),
|
|
1347
|
+
options: import_zod8.z.array(
|
|
1348
|
+
import_zod8.z.object({
|
|
1349
|
+
label: import_zod8.z.string(),
|
|
1350
|
+
value: import_zod8.z.string()
|
|
1287
1351
|
})
|
|
1288
1352
|
).optional(),
|
|
1289
|
-
default:
|
|
1290
|
-
help:
|
|
1291
|
-
dependsOn:
|
|
1292
|
-
questionId:
|
|
1293
|
-
value:
|
|
1353
|
+
default: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.boolean(), import_zod8.z.array(import_zod8.z.string())]).optional(),
|
|
1354
|
+
help: import_zod8.z.string().optional(),
|
|
1355
|
+
dependsOn: import_zod8.z.object({
|
|
1356
|
+
questionId: import_zod8.z.string(),
|
|
1357
|
+
value: import_zod8.z.union([import_zod8.z.string(), import_zod8.z.array(import_zod8.z.string())])
|
|
1294
1358
|
}).optional()
|
|
1295
1359
|
});
|
|
1296
1360
|
function registerQuestionTools(server2) {
|
|
@@ -1298,15 +1362,16 @@ function registerQuestionTools(server2) {
|
|
|
1298
1362
|
"stackwright_pro_present_phase_questions",
|
|
1299
1363
|
"Adapt manifest-format questions from a specialist otter and present them to the user via ask_user_question. Pass only the phase name \u2014 this tool reads questions from .stackwright/question-manifest.json automatically. The questions parameter is optional and only needed if the manifest has not been written yet. Use this instead of calling ask_user_question directly \u2014 it handles label truncation (50-char limit), header generation, confirm/text defaults, and correct array formatting automatically. IMPORTANT: This is the ONLY approved way to prepare questions before calling ask_user_question. Never call ask_user_question with raw manifest questions. Never retry ask_user_question validation errors by calling it directly \u2014 always re-call this tool.",
|
|
1300
1364
|
{
|
|
1301
|
-
phase:
|
|
1302
|
-
questions:
|
|
1365
|
+
phase: import_zod8.z.string().describe('Phase name for display context, e.g. "designer", "api", "auth"'),
|
|
1366
|
+
questions: jsonCoerce(import_zod8.z.array(ManifestQuestionSchema).optional()).describe(
|
|
1303
1367
|
"Questions in Question Manifest format. If omitted, questions are read from .stackwright/question-manifest.json using the phase name."
|
|
1304
1368
|
),
|
|
1305
|
-
answers:
|
|
1369
|
+
answers: jsonCoerce(
|
|
1370
|
+
import_zod8.z.record(import_zod8.z.string(), import_zod8.z.union([import_zod8.z.string(), import_zod8.z.array(import_zod8.z.string()), import_zod8.z.boolean()])).optional()
|
|
1371
|
+
).describe("Previously collected answers used to resolve dependsOn conditions")
|
|
1306
1372
|
},
|
|
1307
1373
|
async ({ phase, questions, answers }) => {
|
|
1308
1374
|
let resolvedQuestions;
|
|
1309
|
-
const SAFE_PHASE = /^[a-z][a-z0-9-]{0,30}$/;
|
|
1310
1375
|
if (!SAFE_PHASE.test(phase)) {
|
|
1311
1376
|
return {
|
|
1312
1377
|
content: [
|
|
@@ -1353,17 +1418,36 @@ function registerQuestionTools(server2) {
|
|
|
1353
1418
|
}
|
|
1354
1419
|
}
|
|
1355
1420
|
const adapted = adaptQuestions(resolvedQuestions, answers ?? {});
|
|
1421
|
+
const labelSchema = import_zod8.z.string().max(50, "Value should have at most 50 characters");
|
|
1422
|
+
for (const q of adapted) {
|
|
1423
|
+
for (const opt of q.options) {
|
|
1424
|
+
const check = labelSchema.safeParse(opt.label);
|
|
1425
|
+
if (!check.success) {
|
|
1426
|
+
return {
|
|
1427
|
+
content: [
|
|
1428
|
+
{
|
|
1429
|
+
type: "text",
|
|
1430
|
+
text: JSON.stringify({
|
|
1431
|
+
error: `Option label for phase "${phase}" exceeds 50 characters: ${check.error.issues[0]?.message ?? "label too long"}. Truncate option labels to \u226450 characters before calling this tool.`
|
|
1432
|
+
})
|
|
1433
|
+
}
|
|
1434
|
+
],
|
|
1435
|
+
isError: true
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1356
1440
|
if (adapted.length === 0) {
|
|
1357
1441
|
return {
|
|
1358
1442
|
content: [
|
|
1359
1443
|
{
|
|
1360
1444
|
type: "text",
|
|
1361
|
-
text:
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1445
|
+
text: `Phase "${phase}" has no questions to present. Do NOT call ask_user_question. Call stackwright_pro_save_phase_answers({ phase: "${phase}", rawAnswers: [] }) directly, then proceed to the execution step for this phase.`
|
|
1446
|
+
},
|
|
1447
|
+
{
|
|
1448
|
+
type: "text",
|
|
1449
|
+
// Empty array — second block always present so the foreman's two-block contract holds
|
|
1450
|
+
text: JSON.stringify([])
|
|
1367
1451
|
}
|
|
1368
1452
|
],
|
|
1369
1453
|
isError: false
|
|
@@ -1384,10 +1468,146 @@ function registerQuestionTools(server2) {
|
|
|
1384
1468
|
};
|
|
1385
1469
|
}
|
|
1386
1470
|
);
|
|
1471
|
+
server2.tool(
|
|
1472
|
+
"stackwright_pro_get_next_question",
|
|
1473
|
+
"Returns the next unanswered question for a phase as a plain JSON object \u2014 one question at a time. Returns { done: true } when all questions are answered or the phase has no questions. Call this in a loop: present the question in plain chat, get user reply, call record_answer, repeat.",
|
|
1474
|
+
{ phase: import_zod8.z.string().describe('Phase name e.g. "designer", "api", "auth"') },
|
|
1475
|
+
async ({ phase }) => {
|
|
1476
|
+
if (!SAFE_PHASE.test(phase)) {
|
|
1477
|
+
return {
|
|
1478
|
+
content: [
|
|
1479
|
+
{
|
|
1480
|
+
type: "text",
|
|
1481
|
+
text: JSON.stringify({ error: `Invalid phase name: "${phase.slice(0, 50)}"` })
|
|
1482
|
+
}
|
|
1483
|
+
],
|
|
1484
|
+
isError: true
|
|
1485
|
+
};
|
|
1486
|
+
}
|
|
1487
|
+
const cwd = process.cwd();
|
|
1488
|
+
const questionsPath = (0, import_node_path.join)(cwd, ".stackwright", "questions", `${phase}.json`);
|
|
1489
|
+
let questions = [];
|
|
1490
|
+
try {
|
|
1491
|
+
const raw = await (0, import_promises.readFile)(questionsPath, "utf-8");
|
|
1492
|
+
const parsed = JSON.parse(raw);
|
|
1493
|
+
questions = parsed.questions ?? [];
|
|
1494
|
+
} catch {
|
|
1495
|
+
return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
|
|
1496
|
+
}
|
|
1497
|
+
if (questions.length === 0) {
|
|
1498
|
+
return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
|
|
1499
|
+
}
|
|
1500
|
+
const answersPath = (0, import_node_path.join)(cwd, ".stackwright", "answers", `${phase}.json`);
|
|
1501
|
+
let answeredIds = /* @__PURE__ */ new Set();
|
|
1502
|
+
try {
|
|
1503
|
+
const raw = await (0, import_promises.readFile)(answersPath, "utf-8");
|
|
1504
|
+
const parsed = JSON.parse(raw);
|
|
1505
|
+
answeredIds = new Set(Object.keys(parsed.answers ?? {}));
|
|
1506
|
+
} catch {
|
|
1507
|
+
}
|
|
1508
|
+
const next = questions.find((q) => !answeredIds.has(q.id));
|
|
1509
|
+
if (!next) {
|
|
1510
|
+
return { content: [{ type: "text", text: JSON.stringify({ done: true }) }] };
|
|
1511
|
+
}
|
|
1512
|
+
return {
|
|
1513
|
+
content: [
|
|
1514
|
+
{
|
|
1515
|
+
type: "text",
|
|
1516
|
+
text: JSON.stringify({
|
|
1517
|
+
done: false,
|
|
1518
|
+
questionId: next.id,
|
|
1519
|
+
question: next.question,
|
|
1520
|
+
type: next.type,
|
|
1521
|
+
options: next.options ?? null,
|
|
1522
|
+
help: next.help ?? null,
|
|
1523
|
+
index: questions.indexOf(next) + 1,
|
|
1524
|
+
total: questions.length
|
|
1525
|
+
})
|
|
1526
|
+
}
|
|
1527
|
+
]
|
|
1528
|
+
};
|
|
1529
|
+
}
|
|
1530
|
+
);
|
|
1531
|
+
server2.tool(
|
|
1532
|
+
"stackwright_pro_record_answer",
|
|
1533
|
+
"Records a single answer to a phase question. Appends to .stackwright/answers/{phase}.json incrementally. Idempotent \u2014 calling twice for the same questionId overwrites. Call after receiving each user reply in the conversational question loop.",
|
|
1534
|
+
{
|
|
1535
|
+
phase: import_zod8.z.string().describe('Phase name e.g. "designer"'),
|
|
1536
|
+
questionId: import_zod8.z.string().describe('The question ID from get_next_question, e.g. "designer-1"'),
|
|
1537
|
+
answer: import_zod8.z.string().describe("The user's free-text answer")
|
|
1538
|
+
},
|
|
1539
|
+
async ({ phase, questionId, answer }) => {
|
|
1540
|
+
if (!SAFE_PHASE.test(phase)) {
|
|
1541
|
+
return {
|
|
1542
|
+
content: [
|
|
1543
|
+
{ type: "text", text: JSON.stringify({ error: "Invalid phase name" }) }
|
|
1544
|
+
],
|
|
1545
|
+
isError: true
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
if (!SAFE_QUESTION_ID.test(questionId)) {
|
|
1549
|
+
return {
|
|
1550
|
+
content: [
|
|
1551
|
+
{ type: "text", text: JSON.stringify({ error: "Invalid questionId" }) }
|
|
1552
|
+
],
|
|
1553
|
+
isError: true
|
|
1554
|
+
};
|
|
1555
|
+
}
|
|
1556
|
+
const safeAnswer = answer.slice(0, 2e3);
|
|
1557
|
+
const cwd = process.cwd();
|
|
1558
|
+
const answersDir = (0, import_node_path.join)(cwd, ".stackwright", "answers");
|
|
1559
|
+
const answersPath = (0, import_node_path.join)(answersDir, `${phase}.json`);
|
|
1560
|
+
if ((0, import_node_fs.existsSync)(answersDir) && (0, import_node_fs.lstatSync)(answersDir).isSymbolicLink()) {
|
|
1561
|
+
return {
|
|
1562
|
+
content: [
|
|
1563
|
+
{
|
|
1564
|
+
type: "text",
|
|
1565
|
+
text: JSON.stringify({ error: "answers dir is a symlink \u2014 refusing to write" })
|
|
1566
|
+
}
|
|
1567
|
+
],
|
|
1568
|
+
isError: true
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
(0, import_node_fs.mkdirSync)(answersDir, { recursive: true });
|
|
1572
|
+
let existing = {
|
|
1573
|
+
version: "1.0",
|
|
1574
|
+
phase,
|
|
1575
|
+
answers: {}
|
|
1576
|
+
};
|
|
1577
|
+
try {
|
|
1578
|
+
if ((0, import_node_fs.existsSync)(answersPath)) {
|
|
1579
|
+
if ((0, import_node_fs.lstatSync)(answersPath).isSymbolicLink()) {
|
|
1580
|
+
return {
|
|
1581
|
+
content: [
|
|
1582
|
+
{
|
|
1583
|
+
type: "text",
|
|
1584
|
+
text: JSON.stringify({ error: "answers file is a symlink \u2014 refusing to write" })
|
|
1585
|
+
}
|
|
1586
|
+
],
|
|
1587
|
+
isError: true
|
|
1588
|
+
};
|
|
1589
|
+
}
|
|
1590
|
+
const raw = await (0, import_promises.readFile)(answersPath, "utf-8");
|
|
1591
|
+
existing = JSON.parse(raw);
|
|
1592
|
+
}
|
|
1593
|
+
} catch {
|
|
1594
|
+
}
|
|
1595
|
+
existing.answers[questionId] = safeAnswer;
|
|
1596
|
+
existing.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1597
|
+
const tmp = `${answersPath}.tmp`;
|
|
1598
|
+
await (0, import_promises.writeFile)(tmp, JSON.stringify(existing, null, 2), "utf-8");
|
|
1599
|
+
(0, import_node_fs.renameSync)(tmp, answersPath);
|
|
1600
|
+
return {
|
|
1601
|
+
content: [
|
|
1602
|
+
{ type: "text", text: JSON.stringify({ recorded: true, phase, questionId }) }
|
|
1603
|
+
]
|
|
1604
|
+
};
|
|
1605
|
+
}
|
|
1606
|
+
);
|
|
1387
1607
|
}
|
|
1388
1608
|
|
|
1389
1609
|
// src/tools/orchestration.ts
|
|
1390
|
-
var
|
|
1610
|
+
var import_zod9 = require("zod");
|
|
1391
1611
|
var import_fs3 = require("fs");
|
|
1392
1612
|
var import_path3 = require("path");
|
|
1393
1613
|
var OTTER_NAME_TO_PHASE = [
|
|
@@ -1398,7 +1618,9 @@ var OTTER_NAME_TO_PHASE = [
|
|
|
1398
1618
|
["dashboard", "dashboard"],
|
|
1399
1619
|
["data", "data"],
|
|
1400
1620
|
["page", "pages"],
|
|
1401
|
-
["workflow", "workflow"]
|
|
1621
|
+
["workflow", "workflow"],
|
|
1622
|
+
["polish", "polish"],
|
|
1623
|
+
["geo", "geo"]
|
|
1402
1624
|
];
|
|
1403
1625
|
var PHASE_TO_OTTER = {
|
|
1404
1626
|
designer: "stackwright-pro-designer-otter",
|
|
@@ -1408,7 +1630,9 @@ var PHASE_TO_OTTER = {
|
|
|
1408
1630
|
pages: "stackwright-pro-page-otter",
|
|
1409
1631
|
dashboard: "stackwright-pro-dashboard-otter",
|
|
1410
1632
|
data: "stackwright-pro-data-otter",
|
|
1411
|
-
workflow: "stackwright-pro-workflow-otter"
|
|
1633
|
+
workflow: "stackwright-pro-workflow-otter",
|
|
1634
|
+
polish: "stackwright-pro-polish-otter",
|
|
1635
|
+
geo: "stackwright-pro-geo-otter"
|
|
1412
1636
|
};
|
|
1413
1637
|
function detectPhase(otterName) {
|
|
1414
1638
|
const lower = otterName.toLowerCase();
|
|
@@ -1474,14 +1698,78 @@ function handleSaveManifest(input) {
|
|
|
1474
1698
|
}
|
|
1475
1699
|
}
|
|
1476
1700
|
function handleSavePhaseAnswers(input) {
|
|
1701
|
+
if (!isValidPhase(input.phase)) {
|
|
1702
|
+
return {
|
|
1703
|
+
text: JSON.stringify({
|
|
1704
|
+
success: false,
|
|
1705
|
+
error: `Invalid phase name: "${input.phase.slice(0, 50)}". Must be lowercase alphanumeric with hyphens, max 31 chars.`
|
|
1706
|
+
}),
|
|
1707
|
+
isError: true
|
|
1708
|
+
};
|
|
1709
|
+
}
|
|
1710
|
+
for (let i = 0; i < input.rawAnswers.length; i++) {
|
|
1711
|
+
const a = input.rawAnswers[i];
|
|
1712
|
+
if (!a.question_header || a.question_header.trim().length === 0) {
|
|
1713
|
+
return {
|
|
1714
|
+
text: JSON.stringify({
|
|
1715
|
+
success: false,
|
|
1716
|
+
error: `rawAnswers[${i}].question_header is empty \u2014 every answer must have a non-empty question_header.`
|
|
1717
|
+
}),
|
|
1718
|
+
isError: true
|
|
1719
|
+
};
|
|
1720
|
+
}
|
|
1721
|
+
if (!a.selected_options || a.selected_options.length === 0) {
|
|
1722
|
+
return {
|
|
1723
|
+
text: JSON.stringify({
|
|
1724
|
+
success: false,
|
|
1725
|
+
error: `rawAnswers[${i}].selected_options is empty for question_header "${a.question_header}" \u2014 every answer must have at least one selected option.`
|
|
1726
|
+
}),
|
|
1727
|
+
isError: true
|
|
1728
|
+
};
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
if (input.questions && input.questions.length > 0 && input.rawAnswers.length === 0) {
|
|
1732
|
+
return {
|
|
1733
|
+
text: JSON.stringify({
|
|
1734
|
+
success: false,
|
|
1735
|
+
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.`
|
|
1736
|
+
}),
|
|
1737
|
+
isError: true
|
|
1738
|
+
};
|
|
1739
|
+
}
|
|
1477
1740
|
const cwd = input._cwd ?? process.cwd();
|
|
1478
1741
|
const dir = (0, import_path3.join)(cwd, ".stackwright", "answers");
|
|
1479
1742
|
const filePath = (0, import_path3.join)(dir, `${input.phase}.json`);
|
|
1480
1743
|
try {
|
|
1481
1744
|
(0, import_fs3.mkdirSync)(dir, { recursive: true });
|
|
1745
|
+
const warnings = [];
|
|
1482
1746
|
let answers;
|
|
1483
1747
|
if (input.questions && input.questions.length > 0) {
|
|
1484
|
-
|
|
1748
|
+
try {
|
|
1749
|
+
answers = answersToManifestFormat(input.rawAnswers, input.questions);
|
|
1750
|
+
} catch (mapErr) {
|
|
1751
|
+
answers = {};
|
|
1752
|
+
warnings.push(
|
|
1753
|
+
`Reverse-mapping threw (${mapErr instanceof Error ? mapErr.message : String(mapErr)}) \u2014 falling back to direct key mapping.`
|
|
1754
|
+
);
|
|
1755
|
+
}
|
|
1756
|
+
if (Object.keys(answers).length === 0 && input.rawAnswers.length > 0) {
|
|
1757
|
+
answers = Object.fromEntries(
|
|
1758
|
+
input.rawAnswers.map((a) => [
|
|
1759
|
+
a.question_header,
|
|
1760
|
+
a.selected_options.length > 1 ? a.selected_options : a.selected_options[0] ?? ""
|
|
1761
|
+
])
|
|
1762
|
+
);
|
|
1763
|
+
warnings.push(
|
|
1764
|
+
`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).`
|
|
1765
|
+
);
|
|
1766
|
+
}
|
|
1767
|
+
const requiredCount = input.questions.filter((q) => q.required !== false).length;
|
|
1768
|
+
if (input.rawAnswers.length < requiredCount) {
|
|
1769
|
+
warnings.push(
|
|
1770
|
+
`Only ${input.rawAnswers.length} answers provided for ${requiredCount} required questions (${input.questions.length} total) \u2014 answers may be incomplete.`
|
|
1771
|
+
);
|
|
1772
|
+
}
|
|
1485
1773
|
} else {
|
|
1486
1774
|
answers = Object.fromEntries(
|
|
1487
1775
|
input.rawAnswers.map((a) => [a.question_header, a.selected_options[0] ?? ""])
|
|
@@ -1508,7 +1796,8 @@ function handleSavePhaseAnswers(input) {
|
|
|
1508
1796
|
text: JSON.stringify({
|
|
1509
1797
|
success: true,
|
|
1510
1798
|
path: filePath,
|
|
1511
|
-
answersCount: Object.keys(answers).length
|
|
1799
|
+
answersCount: Object.keys(answers).length,
|
|
1800
|
+
...warnings.length > 0 ? { warnings } : {}
|
|
1512
1801
|
}),
|
|
1513
1802
|
isError: false
|
|
1514
1803
|
};
|
|
@@ -1555,13 +1844,63 @@ function handleGetOtterName(input) {
|
|
|
1555
1844
|
isError: false
|
|
1556
1845
|
};
|
|
1557
1846
|
}
|
|
1847
|
+
function handleSaveBuildContext(input) {
|
|
1848
|
+
const cwd = input._cwd ?? process.cwd();
|
|
1849
|
+
const dir = (0, import_path3.join)(cwd, ".stackwright");
|
|
1850
|
+
const filePath = (0, import_path3.join)(dir, "build-context.json");
|
|
1851
|
+
try {
|
|
1852
|
+
(0, import_fs3.mkdirSync)(dir, { recursive: true });
|
|
1853
|
+
if ((0, import_fs3.existsSync)(filePath)) {
|
|
1854
|
+
const stat = (0, import_fs3.lstatSync)(filePath);
|
|
1855
|
+
if (stat.isSymbolicLink()) {
|
|
1856
|
+
return {
|
|
1857
|
+
text: JSON.stringify({
|
|
1858
|
+
success: false,
|
|
1859
|
+
error: `Refusing to write to symlink: ${filePath}`
|
|
1860
|
+
}),
|
|
1861
|
+
isError: true
|
|
1862
|
+
};
|
|
1863
|
+
}
|
|
1864
|
+
}
|
|
1865
|
+
const payload = {
|
|
1866
|
+
version: "1.0",
|
|
1867
|
+
savedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1868
|
+
buildContext: input.buildContext
|
|
1869
|
+
};
|
|
1870
|
+
(0, import_fs3.writeFileSync)(filePath, JSON.stringify(payload, null, 2) + "\n");
|
|
1871
|
+
return {
|
|
1872
|
+
text: JSON.stringify({ success: true, path: filePath }),
|
|
1873
|
+
isError: false
|
|
1874
|
+
};
|
|
1875
|
+
} catch (err) {
|
|
1876
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1877
|
+
return {
|
|
1878
|
+
text: JSON.stringify({ success: false, error: message }),
|
|
1879
|
+
isError: true
|
|
1880
|
+
};
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1558
1883
|
function registerOrchestrationTools(server2) {
|
|
1884
|
+
server2.tool(
|
|
1885
|
+
"stackwright_pro_save_build_context",
|
|
1886
|
+
`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.`,
|
|
1887
|
+
{
|
|
1888
|
+
buildContext: import_zod9.z.string().describe("Free-text description of what the user wants to build")
|
|
1889
|
+
},
|
|
1890
|
+
async ({ buildContext }) => {
|
|
1891
|
+
const { text, isError } = handleSaveBuildContext({ buildContext });
|
|
1892
|
+
return {
|
|
1893
|
+
content: [{ type: "text", text }],
|
|
1894
|
+
isError
|
|
1895
|
+
};
|
|
1896
|
+
}
|
|
1897
|
+
);
|
|
1559
1898
|
server2.tool(
|
|
1560
1899
|
"stackwright_pro_parse_otter_response",
|
|
1561
1900
|
"Parse and validate a specialist otter's QUESTION_COLLECTION_MODE JSON response. Handles JSON extraction from LLM responses (strips markdown, fixes single quotes, trailing commas). Detects the phase from the otter name. Use this immediately after invoke_agent() to get a validated manifest phase object.",
|
|
1562
1901
|
{
|
|
1563
|
-
otterName:
|
|
1564
|
-
responseText:
|
|
1902
|
+
otterName: import_zod9.z.string().describe('The agent name, e.g. "stackwright-pro-api-otter"'),
|
|
1903
|
+
responseText: import_zod9.z.string().describe("Raw text response from the otter's QUESTION_COLLECTION_MODE invocation")
|
|
1565
1904
|
},
|
|
1566
1905
|
async ({ otterName, responseText }) => {
|
|
1567
1906
|
const { result, isError } = handleParseOtterResponse({ otterName, responseText });
|
|
@@ -1575,16 +1914,18 @@ function registerOrchestrationTools(server2) {
|
|
|
1575
1914
|
"stackwright_pro_save_manifest",
|
|
1576
1915
|
"Write the question manifest to .stackwright/question-manifest.json. Call this after collecting and parsing questions from all otters via stackwright_pro_parse_otter_response.",
|
|
1577
1916
|
{
|
|
1578
|
-
phases:
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1917
|
+
phases: jsonCoerce(
|
|
1918
|
+
import_zod9.z.array(
|
|
1919
|
+
import_zod9.z.object({
|
|
1920
|
+
phase: import_zod9.z.string(),
|
|
1921
|
+
otter: import_zod9.z.string(),
|
|
1922
|
+
questions: import_zod9.z.array(import_zod9.z.any()),
|
|
1923
|
+
requiredPackages: import_zod9.z.object({
|
|
1924
|
+
dependencies: import_zod9.z.record(import_zod9.z.string(), import_zod9.z.string()).optional(),
|
|
1925
|
+
devPackages: import_zod9.z.record(import_zod9.z.string(), import_zod9.z.string()).optional()
|
|
1926
|
+
}).optional()
|
|
1927
|
+
})
|
|
1928
|
+
)
|
|
1588
1929
|
).describe("Array of parsed phase objects from stackwright_pro_parse_otter_response")
|
|
1589
1930
|
},
|
|
1590
1931
|
async ({ phases }) => {
|
|
@@ -1599,15 +1940,37 @@ function registerOrchestrationTools(server2) {
|
|
|
1599
1940
|
"stackwright_pro_save_phase_answers",
|
|
1600
1941
|
"Save user answers for a phase to .stackwright/answers/{phase}.json. Pass rawAnswers directly from ask_user_question and the original manifest questions for label-to-value reverse mapping.",
|
|
1601
1942
|
{
|
|
1602
|
-
phase:
|
|
1603
|
-
rawAnswers:
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1943
|
+
phase: import_zod9.z.string().describe('Phase name, e.g. "designer"'),
|
|
1944
|
+
rawAnswers: jsonCoerce(
|
|
1945
|
+
import_zod9.z.array(
|
|
1946
|
+
import_zod9.z.object({
|
|
1947
|
+
question_header: import_zod9.z.string().min(1, "question_header must not be empty"),
|
|
1948
|
+
selected_options: import_zod9.z.array(import_zod9.z.string()).min(1, "selected_options must have at least one entry"),
|
|
1949
|
+
other_text: import_zod9.z.string().nullable().optional()
|
|
1950
|
+
})
|
|
1951
|
+
)
|
|
1952
|
+
).describe(
|
|
1953
|
+
"Answers as returned by ask_user_question \u2014 pass the native array, not a JSON string"
|
|
1954
|
+
),
|
|
1955
|
+
questions: jsonCoerce(
|
|
1956
|
+
import_zod9.z.array(
|
|
1957
|
+
import_zod9.z.object({
|
|
1958
|
+
id: import_zod9.z.string(),
|
|
1959
|
+
question: import_zod9.z.string(),
|
|
1960
|
+
type: import_zod9.z.string(),
|
|
1961
|
+
options: import_zod9.z.array(import_zod9.z.object({ label: import_zod9.z.string(), value: import_zod9.z.string() })).optional(),
|
|
1962
|
+
required: import_zod9.z.boolean().optional(),
|
|
1963
|
+
default: import_zod9.z.union([import_zod9.z.string(), import_zod9.z.boolean(), import_zod9.z.array(import_zod9.z.string())]).optional(),
|
|
1964
|
+
help: import_zod9.z.string().optional(),
|
|
1965
|
+
dependsOn: import_zod9.z.object({
|
|
1966
|
+
questionId: import_zod9.z.string(),
|
|
1967
|
+
value: import_zod9.z.union([import_zod9.z.string(), import_zod9.z.array(import_zod9.z.string())])
|
|
1968
|
+
}).optional()
|
|
1969
|
+
}).passthrough()
|
|
1970
|
+
).optional()
|
|
1971
|
+
).describe(
|
|
1972
|
+
"Original manifest questions for label\u2192value reverse-mapping \u2014 pass the native array, not a JSON string"
|
|
1973
|
+
)
|
|
1611
1974
|
},
|
|
1612
1975
|
async ({ phase, rawAnswers, questions }) => {
|
|
1613
1976
|
const { text, isError } = handleSavePhaseAnswers({
|
|
@@ -1625,7 +1988,7 @@ function registerOrchestrationTools(server2) {
|
|
|
1625
1988
|
"stackwright_pro_read_phase_answers",
|
|
1626
1989
|
"Read saved answers for a phase from .stackwright/answers/{phase}.json. Returns { missing: true } when no answers exist yet \u2014 use this to skip phases safely in the execution loop.",
|
|
1627
1990
|
{
|
|
1628
|
-
phase:
|
|
1991
|
+
phase: import_zod9.z.string().describe('Phase name, e.g. "designer"')
|
|
1629
1992
|
},
|
|
1630
1993
|
async ({ phase }) => {
|
|
1631
1994
|
const { text, isError } = handleReadPhaseAnswers({ phase });
|
|
@@ -1639,7 +2002,7 @@ function registerOrchestrationTools(server2) {
|
|
|
1639
2002
|
"stackwright_pro_get_otter_name",
|
|
1640
2003
|
"Get the agent name for a phase (e.g. 'designer' \u2192 'stackwright-pro-designer-otter'). Use this in the execution loop to invoke the correct specialist otter without hardcoding names in the prompt.",
|
|
1641
2004
|
{
|
|
1642
|
-
phase:
|
|
2005
|
+
phase: import_zod9.z.string().describe('Phase name, e.g. "designer", "api", "pages"')
|
|
1643
2006
|
},
|
|
1644
2007
|
async ({ phase }) => {
|
|
1645
2008
|
const { text, isError } = handleGetOtterName({ phase });
|
|
@@ -1652,50 +2015,404 @@ function registerOrchestrationTools(server2) {
|
|
|
1652
2015
|
}
|
|
1653
2016
|
|
|
1654
2017
|
// src/tools/pipeline.ts
|
|
1655
|
-
var
|
|
2018
|
+
var import_zod11 = require("zod");
|
|
2019
|
+
var import_fs5 = require("fs");
|
|
2020
|
+
var import_path5 = require("path");
|
|
2021
|
+
var import_crypto3 = require("crypto");
|
|
2022
|
+
|
|
2023
|
+
// src/artifact-signing.ts
|
|
2024
|
+
var import_crypto2 = require("crypto");
|
|
1656
2025
|
var import_fs4 = require("fs");
|
|
1657
2026
|
var import_path4 = require("path");
|
|
1658
|
-
var
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
}
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
2027
|
+
var import_zod10 = require("zod");
|
|
2028
|
+
var ALGORITHM = "ECDSA-P384-SHA384";
|
|
2029
|
+
var KEY_FILE = "pipeline-keys.json";
|
|
2030
|
+
var KEY_DIR = ".stackwright";
|
|
2031
|
+
var SIGNATURE_MANIFEST = "signatures.json";
|
|
2032
|
+
var ARTIFACTS_DIR = ".stackwright/artifacts";
|
|
2033
|
+
function rejectSymlink(filePath, context) {
|
|
2034
|
+
if (!(0, import_fs4.existsSync)(filePath)) return;
|
|
2035
|
+
const stat = (0, import_fs4.lstatSync)(filePath);
|
|
2036
|
+
if (stat.isSymbolicLink()) {
|
|
2037
|
+
throw new Error(`Security: refusing to follow symlink at ${context}: ${filePath}`);
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
function computeSha384(data) {
|
|
2041
|
+
return (0, import_crypto2.createHash)("sha384").update(data).digest("hex");
|
|
2042
|
+
}
|
|
2043
|
+
function safeDigestEqual(a, b) {
|
|
2044
|
+
if (a.length !== b.length) return false;
|
|
2045
|
+
return (0, import_crypto2.timingSafeEqual)(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
|
|
2046
|
+
}
|
|
2047
|
+
function emptyManifest() {
|
|
2048
|
+
return {
|
|
2049
|
+
version: "1.0",
|
|
2050
|
+
algorithm: ALGORITHM,
|
|
2051
|
+
signatures: {}
|
|
2052
|
+
};
|
|
2053
|
+
}
|
|
2054
|
+
function initPipelineKeys(cwd) {
|
|
2055
|
+
const keyDir = (0, import_path4.join)(cwd, KEY_DIR);
|
|
2056
|
+
const keyPath = (0, import_path4.join)(keyDir, KEY_FILE);
|
|
2057
|
+
rejectSymlink(keyPath, "pipeline-keys.json");
|
|
2058
|
+
(0, import_fs4.mkdirSync)(keyDir, { recursive: true });
|
|
2059
|
+
const { publicKey, privateKey } = (0, import_crypto2.generateKeyPairSync)("ec", {
|
|
2060
|
+
namedCurve: "P-384"
|
|
2061
|
+
});
|
|
2062
|
+
const publicKeyPem = publicKey.export({ type: "spki", format: "pem" });
|
|
2063
|
+
const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" });
|
|
2064
|
+
const fingerprint = (0, import_crypto2.createHash)("sha256").update(publicKeyPem).digest("hex");
|
|
2065
|
+
const keyFile = {
|
|
2066
|
+
version: "1.0",
|
|
2067
|
+
algorithm: ALGORITHM,
|
|
2068
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2069
|
+
publicKeyPem,
|
|
2070
|
+
privateKeyPem
|
|
2071
|
+
};
|
|
2072
|
+
(0, import_fs4.writeFileSync)(keyPath, JSON.stringify(keyFile, null, 2), { encoding: "utf-8" });
|
|
2073
|
+
return { publicKeyPem, fingerprint };
|
|
2074
|
+
}
|
|
2075
|
+
function loadPipelineKeys(cwd) {
|
|
2076
|
+
const keyPath = (0, import_path4.join)(cwd, KEY_DIR, KEY_FILE);
|
|
2077
|
+
rejectSymlink(keyPath, "pipeline-keys.json");
|
|
2078
|
+
if (!(0, import_fs4.existsSync)(keyPath)) {
|
|
2079
|
+
throw new Error("Pipeline keys not found \u2014 call initPipelineKeys() first");
|
|
2080
|
+
}
|
|
2081
|
+
let raw;
|
|
2082
|
+
try {
|
|
2083
|
+
raw = (0, import_fs4.readFileSync)(keyPath, "utf-8");
|
|
2084
|
+
} catch (err) {
|
|
2085
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2086
|
+
throw new Error(`Cannot read pipeline keys: ${msg}`, { cause: err });
|
|
2087
|
+
}
|
|
2088
|
+
let parsed;
|
|
2089
|
+
try {
|
|
2090
|
+
parsed = JSON.parse(raw);
|
|
2091
|
+
} catch {
|
|
2092
|
+
throw new Error("Pipeline keys file is not valid JSON");
|
|
2093
|
+
}
|
|
2094
|
+
if (typeof parsed.publicKeyPem !== "string" || !parsed.publicKeyPem.includes("-----BEGIN PUBLIC KEY-----")) {
|
|
2095
|
+
throw new Error("Invalid public key PEM in pipeline keys file");
|
|
2096
|
+
}
|
|
2097
|
+
if (typeof parsed.privateKeyPem !== "string" || !parsed.privateKeyPem.includes("-----BEGIN")) {
|
|
2098
|
+
throw new Error("Invalid private key PEM in pipeline keys file");
|
|
2099
|
+
}
|
|
2100
|
+
const publicKey = (0, import_crypto2.createPublicKey)(parsed.publicKeyPem);
|
|
2101
|
+
const privateKey = (0, import_crypto2.createPrivateKey)(parsed.privateKeyPem);
|
|
2102
|
+
return { privateKey, publicKey };
|
|
2103
|
+
}
|
|
2104
|
+
function signArtifact(artifactBytes, privateKey) {
|
|
2105
|
+
const digest = computeSha384(artifactBytes);
|
|
2106
|
+
const sig = (0, import_crypto2.sign)("SHA384", artifactBytes, privateKey);
|
|
2107
|
+
return {
|
|
2108
|
+
digest,
|
|
2109
|
+
signature: sig.toString("base64"),
|
|
2110
|
+
algorithm: ALGORITHM,
|
|
2111
|
+
signedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2112
|
+
};
|
|
2113
|
+
}
|
|
2114
|
+
function verifyArtifact(artifactBytes, signature, publicKey) {
|
|
2115
|
+
const sigValid = (0, import_crypto2.verify)(
|
|
2116
|
+
"SHA384",
|
|
2117
|
+
artifactBytes,
|
|
2118
|
+
publicKey,
|
|
2119
|
+
Buffer.from(signature.signature, "base64")
|
|
2120
|
+
);
|
|
2121
|
+
if (!sigValid) return false;
|
|
2122
|
+
const actualDigest = computeSha384(artifactBytes);
|
|
2123
|
+
return safeDigestEqual(actualDigest, signature.digest);
|
|
2124
|
+
}
|
|
2125
|
+
function loadSignatureManifest(cwd) {
|
|
2126
|
+
const manifestPath = (0, import_path4.join)(cwd, ARTIFACTS_DIR, SIGNATURE_MANIFEST);
|
|
2127
|
+
rejectSymlink(manifestPath, "signatures.json");
|
|
2128
|
+
if (!(0, import_fs4.existsSync)(manifestPath)) return emptyManifest();
|
|
2129
|
+
let raw;
|
|
2130
|
+
try {
|
|
2131
|
+
raw = (0, import_fs4.readFileSync)(manifestPath, "utf-8");
|
|
2132
|
+
} catch (err) {
|
|
2133
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2134
|
+
throw new Error(`Cannot read signature manifest: ${msg}`, { cause: err });
|
|
2135
|
+
}
|
|
2136
|
+
try {
|
|
2137
|
+
const parsed = JSON.parse(raw);
|
|
2138
|
+
if (parsed.version !== "1.0" || typeof parsed.signatures !== "object") {
|
|
2139
|
+
throw new Error("Malformed signature manifest: invalid version or missing signatures object");
|
|
2140
|
+
}
|
|
2141
|
+
return parsed;
|
|
2142
|
+
} catch (err) {
|
|
2143
|
+
if (err instanceof Error && err.message.startsWith("Malformed")) throw err;
|
|
2144
|
+
throw new Error("Signature manifest is not valid JSON", { cause: err });
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
function saveArtifactSignature(cwd, artifactFilename, sig, signerOtter) {
|
|
2148
|
+
const artifactsDir = (0, import_path4.join)(cwd, ARTIFACTS_DIR);
|
|
2149
|
+
const manifestPath = (0, import_path4.join)(artifactsDir, SIGNATURE_MANIFEST);
|
|
2150
|
+
rejectSymlink(manifestPath, "signatures.json (save)");
|
|
2151
|
+
(0, import_fs4.mkdirSync)(artifactsDir, { recursive: true });
|
|
2152
|
+
const manifest = loadSignatureManifest(cwd);
|
|
2153
|
+
manifest.signatures[artifactFilename] = {
|
|
2154
|
+
...sig,
|
|
2155
|
+
signedBy: signerOtter
|
|
2156
|
+
};
|
|
2157
|
+
(0, import_fs4.writeFileSync)(manifestPath, JSON.stringify(manifest, null, 2), { encoding: "utf-8" });
|
|
2158
|
+
}
|
|
2159
|
+
function getArtifactSignature(cwd, artifactFilename) {
|
|
2160
|
+
const manifest = loadSignatureManifest(cwd);
|
|
2161
|
+
const entry = manifest.signatures[artifactFilename];
|
|
2162
|
+
if (!entry) return null;
|
|
2163
|
+
return {
|
|
2164
|
+
digest: entry.digest,
|
|
2165
|
+
signature: entry.signature,
|
|
2166
|
+
algorithm: entry.algorithm,
|
|
2167
|
+
signedAt: entry.signedAt
|
|
2168
|
+
};
|
|
2169
|
+
}
|
|
2170
|
+
function emitSignatureAuditEvent(params) {
|
|
2171
|
+
const record = JSON.stringify({
|
|
2172
|
+
level: "AUDIT",
|
|
2173
|
+
event: "ARTIFACT_SIGNATURE_FAIL",
|
|
2174
|
+
timestamp: params.timestamp,
|
|
2175
|
+
source: params.source,
|
|
2176
|
+
artifactFilename: params.artifactFilename,
|
|
2177
|
+
expectedDigest: params.expectedDigest,
|
|
2178
|
+
actualDigest: params.actualDigest,
|
|
2179
|
+
phase: params.phase
|
|
2180
|
+
});
|
|
2181
|
+
process.stderr.write(`ARTIFACT_SIGNATURE_FAIL ${record}
|
|
2182
|
+
`);
|
|
2183
|
+
}
|
|
2184
|
+
function registerArtifactSigningTools(server2) {
|
|
2185
|
+
server2.tool(
|
|
2186
|
+
"stackwright_pro_verify_artifact_signatures",
|
|
2187
|
+
"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.",
|
|
2188
|
+
{
|
|
2189
|
+
cwd: import_zod10.z.string().optional().describe("Project root directory. Defaults to process.cwd().")
|
|
2190
|
+
},
|
|
2191
|
+
async ({ cwd: cwdParam }) => {
|
|
2192
|
+
const cwd = cwdParam ?? process.cwd();
|
|
2193
|
+
let publicKey;
|
|
2194
|
+
try {
|
|
2195
|
+
const keys = loadPipelineKeys(cwd);
|
|
2196
|
+
publicKey = keys.publicKey;
|
|
2197
|
+
} catch (err) {
|
|
2198
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2199
|
+
return {
|
|
2200
|
+
content: [
|
|
2201
|
+
{
|
|
2202
|
+
type: "text",
|
|
2203
|
+
text: JSON.stringify({
|
|
2204
|
+
error: true,
|
|
2205
|
+
message: `Cannot load pipeline keys: ${msg}`
|
|
2206
|
+
})
|
|
2207
|
+
}
|
|
2208
|
+
],
|
|
2209
|
+
isError: true
|
|
2210
|
+
};
|
|
2211
|
+
}
|
|
2212
|
+
let manifest;
|
|
2213
|
+
try {
|
|
2214
|
+
manifest = loadSignatureManifest(cwd);
|
|
2215
|
+
} catch (err) {
|
|
2216
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2217
|
+
return {
|
|
2218
|
+
content: [
|
|
2219
|
+
{
|
|
2220
|
+
type: "text",
|
|
2221
|
+
text: JSON.stringify({
|
|
2222
|
+
error: true,
|
|
2223
|
+
message: `Cannot load signature manifest: ${msg}`
|
|
2224
|
+
})
|
|
2225
|
+
}
|
|
2226
|
+
],
|
|
2227
|
+
isError: true
|
|
2228
|
+
};
|
|
2229
|
+
}
|
|
2230
|
+
const artifactsPath = (0, import_path4.join)(cwd, ARTIFACTS_DIR);
|
|
2231
|
+
let artifactFiles = [];
|
|
2232
|
+
try {
|
|
2233
|
+
if ((0, import_fs4.existsSync)(artifactsPath)) {
|
|
2234
|
+
artifactFiles = (0, import_fs4.readdirSync)(artifactsPath).filter(
|
|
2235
|
+
(f) => f.endsWith(".json") && f !== SIGNATURE_MANIFEST
|
|
2236
|
+
);
|
|
2237
|
+
}
|
|
2238
|
+
} catch {
|
|
2239
|
+
}
|
|
2240
|
+
const results = [];
|
|
2241
|
+
let hasFailure = false;
|
|
2242
|
+
for (const filename of artifactFiles) {
|
|
2243
|
+
const filePath = (0, import_path4.join)(artifactsPath, filename);
|
|
2244
|
+
try {
|
|
2245
|
+
rejectSymlink(filePath, `artifact ${filename}`);
|
|
2246
|
+
} catch {
|
|
2247
|
+
results.push({
|
|
2248
|
+
filename,
|
|
2249
|
+
verified: false,
|
|
2250
|
+
error: "Refusing to verify symlink"
|
|
2251
|
+
});
|
|
2252
|
+
hasFailure = true;
|
|
2253
|
+
continue;
|
|
2254
|
+
}
|
|
2255
|
+
let artifactBytes;
|
|
2256
|
+
try {
|
|
2257
|
+
artifactBytes = (0, import_fs4.readFileSync)(filePath);
|
|
2258
|
+
} catch (err) {
|
|
2259
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2260
|
+
results.push({
|
|
2261
|
+
filename,
|
|
2262
|
+
verified: false,
|
|
2263
|
+
error: `Cannot read artifact: ${msg}`
|
|
2264
|
+
});
|
|
2265
|
+
hasFailure = true;
|
|
2266
|
+
continue;
|
|
2267
|
+
}
|
|
2268
|
+
const entry = manifest.signatures[filename];
|
|
2269
|
+
if (!entry) {
|
|
2270
|
+
results.push({
|
|
2271
|
+
filename,
|
|
2272
|
+
verified: false,
|
|
2273
|
+
error: "No signature found in manifest"
|
|
2274
|
+
});
|
|
2275
|
+
hasFailure = true;
|
|
2276
|
+
continue;
|
|
2277
|
+
}
|
|
2278
|
+
const sig = {
|
|
2279
|
+
digest: entry.digest,
|
|
2280
|
+
signature: entry.signature,
|
|
2281
|
+
algorithm: entry.algorithm,
|
|
2282
|
+
signedAt: entry.signedAt
|
|
2283
|
+
};
|
|
2284
|
+
const verified = verifyArtifact(artifactBytes, sig, publicKey);
|
|
2285
|
+
if (!verified) {
|
|
2286
|
+
const actualDigest = computeSha384(artifactBytes);
|
|
2287
|
+
emitSignatureAuditEvent({
|
|
2288
|
+
artifactFilename: filename,
|
|
2289
|
+
expectedDigest: sig.digest,
|
|
2290
|
+
actualDigest,
|
|
2291
|
+
phase: entry.signedBy ?? "unknown",
|
|
2292
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2293
|
+
source: "stackwright_pro_verify_artifact_signatures"
|
|
2294
|
+
});
|
|
2295
|
+
results.push({
|
|
2296
|
+
filename,
|
|
2297
|
+
verified: false,
|
|
2298
|
+
error: `Signature verification failed \u2014 artifact may have been tampered with`,
|
|
2299
|
+
signedBy: entry.signedBy,
|
|
2300
|
+
signedAt: entry.signedAt
|
|
2301
|
+
});
|
|
2302
|
+
hasFailure = true;
|
|
2303
|
+
} else {
|
|
2304
|
+
results.push({
|
|
2305
|
+
filename,
|
|
2306
|
+
verified: true,
|
|
2307
|
+
signedBy: entry.signedBy,
|
|
2308
|
+
signedAt: entry.signedAt
|
|
2309
|
+
});
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
for (const manifestFilename of Object.keys(manifest.signatures)) {
|
|
2313
|
+
if (!artifactFiles.includes(manifestFilename)) {
|
|
2314
|
+
results.push({
|
|
2315
|
+
filename: manifestFilename,
|
|
2316
|
+
verified: false,
|
|
2317
|
+
error: "Artifact referenced in manifest but missing from disk"
|
|
2318
|
+
});
|
|
2319
|
+
hasFailure = true;
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
const verifiedCount = results.filter((r) => r.verified).length;
|
|
2323
|
+
const failedCount = results.filter((r) => !r.verified).length;
|
|
2324
|
+
return {
|
|
2325
|
+
content: [
|
|
2326
|
+
{
|
|
2327
|
+
type: "text",
|
|
2328
|
+
text: JSON.stringify({
|
|
2329
|
+
totalArtifacts: artifactFiles.length,
|
|
2330
|
+
verifiedCount,
|
|
2331
|
+
failedCount,
|
|
2332
|
+
results,
|
|
2333
|
+
...hasFailure ? {
|
|
2334
|
+
error: "SIGNATURE VERIFICATION FAILED: One or more artifact signatures are invalid. Do not proceed \u2014 artifacts may have been tampered with."
|
|
2335
|
+
} : {}
|
|
2336
|
+
})
|
|
2337
|
+
}
|
|
2338
|
+
],
|
|
2339
|
+
isError: hasFailure
|
|
2340
|
+
};
|
|
2341
|
+
}
|
|
2342
|
+
);
|
|
2343
|
+
}
|
|
2344
|
+
|
|
2345
|
+
// src/tools/pipeline.ts
|
|
2346
|
+
var import_types = require("@stackwright-pro/types");
|
|
2347
|
+
var PHASE_ORDER = [
|
|
2348
|
+
"designer",
|
|
2349
|
+
"theme",
|
|
2350
|
+
"api",
|
|
2351
|
+
"data",
|
|
2352
|
+
"geo",
|
|
2353
|
+
"workflow",
|
|
2354
|
+
"services",
|
|
2355
|
+
"pages",
|
|
2356
|
+
"dashboard",
|
|
2357
|
+
"auth",
|
|
2358
|
+
"polish"
|
|
2359
|
+
];
|
|
2360
|
+
var PHASE_DEPENDENCIES = {
|
|
2361
|
+
designer: [],
|
|
2362
|
+
theme: ["designer"],
|
|
2363
|
+
api: [],
|
|
2364
|
+
data: ["api"],
|
|
2365
|
+
geo: ["data"],
|
|
2366
|
+
// workflow: no hard deps — uses service: references with Prism mock fallback
|
|
2367
|
+
// when API artifacts aren't available; roles come from user answers
|
|
2368
|
+
workflow: [],
|
|
2369
|
+
// services: needs API endpoints to know what to wire, and optionally
|
|
2370
|
+
// workflow states as trigger sources. Produces OpenAPI specs consumed
|
|
2371
|
+
// by pages and dashboard for typed data wiring.
|
|
2372
|
+
services: ["api", "workflow"],
|
|
2373
|
+
// pages/dashboard: depend on services for typed endpoint wiring (OpenAPI
|
|
2374
|
+
// specs) and on geo so the specialist prompt includes geo-manifest.json
|
|
2375
|
+
// — page/dashboard otters see which page slugs are already claimed and
|
|
2376
|
+
// won't attempt to overwrite them (swp-73c). 'api' is still transitive
|
|
2377
|
+
// through 'data'; auth removed — page-otter has graceful fallback.
|
|
2378
|
+
pages: ["designer", "theme", "data", "services", "geo"],
|
|
2379
|
+
dashboard: ["designer", "theme", "data", "services", "geo"],
|
|
2380
|
+
// auth is the penultimate phase — runs after all content-producing phases
|
|
2381
|
+
// so it can read pages, dashboard, workflow, and geo artifacts for route
|
|
2382
|
+
// protection and RBAC wiring. Skipped upstream phases still satisfy deps
|
|
2383
|
+
// (the foreman marks them executed=true), so auth always runs.
|
|
2384
|
+
auth: ["pages", "dashboard", "workflow", "geo"],
|
|
2385
|
+
// polish is the terminal phase — runs after auth so the landing page and
|
|
2386
|
+
// nav reflect the final set of protected routes and all generated pages.
|
|
2387
|
+
polish: ["auth"]
|
|
2388
|
+
};
|
|
2389
|
+
var PHASE_ARTIFACT = {
|
|
2390
|
+
designer: "design-language.json",
|
|
2391
|
+
theme: "theme-tokens.json",
|
|
2392
|
+
api: "api-config.json",
|
|
2393
|
+
auth: "auth-config.json",
|
|
2394
|
+
data: "data-config.json",
|
|
2395
|
+
pages: "pages-manifest.json",
|
|
2396
|
+
dashboard: "dashboard-manifest.json",
|
|
2397
|
+
workflow: "workflow-config.json",
|
|
2398
|
+
services: "services-config.json",
|
|
2399
|
+
polish: "polish-manifest.json",
|
|
2400
|
+
geo: "geo-manifest.json"
|
|
2401
|
+
};
|
|
2402
|
+
var PHASE_TO_OTTER2 = {
|
|
2403
|
+
designer: "stackwright-pro-designer-otter",
|
|
2404
|
+
theme: "stackwright-pro-theme-otter",
|
|
2405
|
+
api: "stackwright-pro-api-otter",
|
|
2406
|
+
auth: "stackwright-pro-auth-otter",
|
|
2407
|
+
data: "stackwright-pro-data-otter",
|
|
1694
2408
|
pages: "stackwright-pro-page-otter",
|
|
1695
2409
|
dashboard: "stackwright-pro-dashboard-otter",
|
|
1696
|
-
workflow: "stackwright-pro-workflow-otter"
|
|
2410
|
+
workflow: "stackwright-pro-workflow-otter",
|
|
2411
|
+
services: "stackwright-services-otter",
|
|
2412
|
+
polish: "stackwright-pro-polish-otter",
|
|
2413
|
+
geo: "stackwright-pro-geo-otter"
|
|
1697
2414
|
};
|
|
1698
|
-
function
|
|
2415
|
+
function isValidPhase2(phase) {
|
|
1699
2416
|
return PHASE_ORDER.includes(phase);
|
|
1700
2417
|
}
|
|
1701
2418
|
function defaultPhaseStatus() {
|
|
@@ -1723,11 +2440,11 @@ function createDefaultState() {
|
|
|
1723
2440
|
};
|
|
1724
2441
|
}
|
|
1725
2442
|
function statePath(cwd) {
|
|
1726
|
-
return (0,
|
|
2443
|
+
return (0, import_path5.join)(cwd, ".stackwright", "pipeline-state.json");
|
|
1727
2444
|
}
|
|
1728
2445
|
function readState(cwd) {
|
|
1729
2446
|
const p = statePath(cwd);
|
|
1730
|
-
if (!(0,
|
|
2447
|
+
if (!(0, import_fs5.existsSync)(p)) return createDefaultState();
|
|
1731
2448
|
const raw = JSON.parse(safeReadSync(p));
|
|
1732
2449
|
if (typeof raw !== "object" || raw === null || raw.version !== "1.0") {
|
|
1733
2450
|
return createDefaultState();
|
|
@@ -1735,26 +2452,26 @@ function readState(cwd) {
|
|
|
1735
2452
|
return raw;
|
|
1736
2453
|
}
|
|
1737
2454
|
function safeWriteSync(filePath, content) {
|
|
1738
|
-
if ((0,
|
|
1739
|
-
const stat = (0,
|
|
2455
|
+
if ((0, import_fs5.existsSync)(filePath)) {
|
|
2456
|
+
const stat = (0, import_fs5.lstatSync)(filePath);
|
|
1740
2457
|
if (stat.isSymbolicLink()) {
|
|
1741
2458
|
throw new Error(`Refusing to write to symlink: ${filePath}`);
|
|
1742
2459
|
}
|
|
1743
2460
|
}
|
|
1744
|
-
(0,
|
|
2461
|
+
(0, import_fs5.writeFileSync)(filePath, content);
|
|
1745
2462
|
}
|
|
1746
2463
|
function safeReadSync(filePath) {
|
|
1747
|
-
if ((0,
|
|
1748
|
-
const stat = (0,
|
|
2464
|
+
if ((0, import_fs5.existsSync)(filePath)) {
|
|
2465
|
+
const stat = (0, import_fs5.lstatSync)(filePath);
|
|
1749
2466
|
if (stat.isSymbolicLink()) {
|
|
1750
2467
|
throw new Error(`Refusing to read symlink: ${filePath}`);
|
|
1751
2468
|
}
|
|
1752
2469
|
}
|
|
1753
|
-
return (0,
|
|
2470
|
+
return (0, import_fs5.readFileSync)(filePath, "utf-8");
|
|
1754
2471
|
}
|
|
1755
2472
|
function writeState(cwd, state) {
|
|
1756
|
-
const dir = (0,
|
|
1757
|
-
(0,
|
|
2473
|
+
const dir = (0, import_path5.join)(cwd, ".stackwright");
|
|
2474
|
+
(0, import_fs5.mkdirSync)(dir, { recursive: true });
|
|
1758
2475
|
state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1759
2476
|
safeWriteSync(statePath(cwd), JSON.stringify(state, null, 2) + "\n");
|
|
1760
2477
|
}
|
|
@@ -1775,6 +2492,15 @@ function handleGetPipelineState(_cwd) {
|
|
|
1775
2492
|
const cwd = _cwd ?? process.cwd();
|
|
1776
2493
|
try {
|
|
1777
2494
|
const state = readState(cwd);
|
|
2495
|
+
const keyPath = (0, import_path5.join)(cwd, ".stackwright", "pipeline-keys.json");
|
|
2496
|
+
if (!(0, import_fs5.existsSync)(keyPath)) {
|
|
2497
|
+
try {
|
|
2498
|
+
const { fingerprint } = initPipelineKeys(cwd);
|
|
2499
|
+
state["signingKeyFingerprint"] = fingerprint;
|
|
2500
|
+
writeState(cwd, state);
|
|
2501
|
+
} catch {
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
1778
2504
|
return { text: JSON.stringify(state), isError: false };
|
|
1779
2505
|
} catch (err) {
|
|
1780
2506
|
return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
|
|
@@ -1782,7 +2508,7 @@ function handleGetPipelineState(_cwd) {
|
|
|
1782
2508
|
}
|
|
1783
2509
|
function handleSetPipelineState(input) {
|
|
1784
2510
|
const cwd = input._cwd ?? process.cwd();
|
|
1785
|
-
if (input.phase && !
|
|
2511
|
+
if (input.phase && !isValidPhase2(input.phase)) {
|
|
1786
2512
|
return {
|
|
1787
2513
|
text: JSON.stringify({
|
|
1788
2514
|
error: true,
|
|
@@ -1801,6 +2527,28 @@ function handleSetPipelineState(input) {
|
|
|
1801
2527
|
isError: true
|
|
1802
2528
|
};
|
|
1803
2529
|
}
|
|
2530
|
+
if (input.updates && input.updates.length > 0) {
|
|
2531
|
+
for (const update of input.updates) {
|
|
2532
|
+
if (!isValidPhase2(update.phase)) {
|
|
2533
|
+
return {
|
|
2534
|
+
text: JSON.stringify({
|
|
2535
|
+
error: true,
|
|
2536
|
+
message: `Invalid phase in batch update: ${update.phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
|
|
2537
|
+
}),
|
|
2538
|
+
isError: true
|
|
2539
|
+
};
|
|
2540
|
+
}
|
|
2541
|
+
if (!VALID_FIELDS.includes(update.field)) {
|
|
2542
|
+
return {
|
|
2543
|
+
text: JSON.stringify({
|
|
2544
|
+
error: true,
|
|
2545
|
+
message: `Invalid field in batch update: ${update.field}. Valid fields are: ${VALID_FIELDS.join(", ")}`
|
|
2546
|
+
}),
|
|
2547
|
+
isError: true
|
|
2548
|
+
};
|
|
2549
|
+
}
|
|
2550
|
+
}
|
|
2551
|
+
}
|
|
1804
2552
|
try {
|
|
1805
2553
|
const state = readState(cwd);
|
|
1806
2554
|
if (input.status) {
|
|
@@ -1820,34 +2568,78 @@ function handleSetPipelineState(input) {
|
|
|
1820
2568
|
}
|
|
1821
2569
|
state.currentPhase = phase;
|
|
1822
2570
|
}
|
|
2571
|
+
if (input.updates && input.updates.length > 0) {
|
|
2572
|
+
for (const update of input.updates) {
|
|
2573
|
+
if (!state.phases[update.phase]) {
|
|
2574
|
+
state.phases[update.phase] = defaultPhaseStatus();
|
|
2575
|
+
}
|
|
2576
|
+
const batchPhaseState = state.phases[update.phase];
|
|
2577
|
+
batchPhaseState[update.field] = update.value;
|
|
2578
|
+
state.currentPhase = update.phase;
|
|
2579
|
+
}
|
|
2580
|
+
}
|
|
1823
2581
|
writeState(cwd, state);
|
|
1824
2582
|
return { text: JSON.stringify(state), isError: false };
|
|
1825
2583
|
} catch (err) {
|
|
1826
2584
|
return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
|
|
1827
2585
|
}
|
|
1828
2586
|
}
|
|
1829
|
-
function handleCheckExecutionReady(_cwd) {
|
|
2587
|
+
function handleCheckExecutionReady(_cwd, phase) {
|
|
1830
2588
|
const cwd = _cwd ?? process.cwd();
|
|
2589
|
+
if (phase) {
|
|
2590
|
+
if (!isValidPhase2(phase)) {
|
|
2591
|
+
return {
|
|
2592
|
+
text: JSON.stringify({
|
|
2593
|
+
error: true,
|
|
2594
|
+
message: `Invalid phase: ${phase}. Valid phases are: ${PHASE_ORDER.join(", ")}`
|
|
2595
|
+
}),
|
|
2596
|
+
isError: true
|
|
2597
|
+
};
|
|
2598
|
+
}
|
|
2599
|
+
const answerFile = (0, import_path5.join)(cwd, ".stackwright", "answers", `${phase}.json`);
|
|
2600
|
+
if (!(0, import_fs5.existsSync)(answerFile)) {
|
|
2601
|
+
return {
|
|
2602
|
+
text: JSON.stringify({ ready: false, phase, reason: "Answer file not found" }),
|
|
2603
|
+
isError: false
|
|
2604
|
+
};
|
|
2605
|
+
}
|
|
2606
|
+
try {
|
|
2607
|
+
const raw = safeReadSync(answerFile);
|
|
2608
|
+
const parsed = JSON.parse(raw);
|
|
2609
|
+
if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
|
|
2610
|
+
return {
|
|
2611
|
+
text: JSON.stringify({ ready: false, phase, reason: "Answer file is malformed" }),
|
|
2612
|
+
isError: false
|
|
2613
|
+
};
|
|
2614
|
+
}
|
|
2615
|
+
return { text: JSON.stringify({ ready: true, phase }), isError: false };
|
|
2616
|
+
} catch {
|
|
2617
|
+
return {
|
|
2618
|
+
text: JSON.stringify({ ready: false, phase, reason: "Answer file could not be parsed" }),
|
|
2619
|
+
isError: false
|
|
2620
|
+
};
|
|
2621
|
+
}
|
|
2622
|
+
}
|
|
1831
2623
|
try {
|
|
1832
|
-
const answersDir = (0,
|
|
2624
|
+
const answersDir = (0, import_path5.join)(cwd, ".stackwright", "answers");
|
|
1833
2625
|
const answeredPhases = [];
|
|
1834
2626
|
const missingPhases = [];
|
|
1835
|
-
for (const
|
|
1836
|
-
const answerFile = (0,
|
|
1837
|
-
if ((0,
|
|
2627
|
+
for (const phase2 of PHASE_ORDER) {
|
|
2628
|
+
const answerFile = (0, import_path5.join)(answersDir, `${phase2}.json`);
|
|
2629
|
+
if ((0, import_fs5.existsSync)(answerFile)) {
|
|
1838
2630
|
try {
|
|
1839
2631
|
const raw = safeReadSync(answerFile);
|
|
1840
2632
|
const parsed = JSON.parse(raw);
|
|
1841
2633
|
if (typeof parsed["version"] !== "string" || typeof parsed["phase"] !== "string" || typeof parsed["answers"] !== "object" || parsed["answers"] === null) {
|
|
1842
|
-
missingPhases.push(
|
|
2634
|
+
missingPhases.push(phase2);
|
|
1843
2635
|
continue;
|
|
1844
2636
|
}
|
|
1845
|
-
answeredPhases.push(
|
|
2637
|
+
answeredPhases.push(phase2);
|
|
1846
2638
|
} catch {
|
|
1847
|
-
missingPhases.push(
|
|
2639
|
+
missingPhases.push(phase2);
|
|
1848
2640
|
}
|
|
1849
2641
|
} else {
|
|
1850
|
-
missingPhases.push(
|
|
2642
|
+
missingPhases.push(phase2);
|
|
1851
2643
|
}
|
|
1852
2644
|
}
|
|
1853
2645
|
return {
|
|
@@ -1863,18 +2655,74 @@ function handleCheckExecutionReady(_cwd) {
|
|
|
1863
2655
|
return { text: JSON.stringify({ error: true, message: String(err) }), isError: true };
|
|
1864
2656
|
}
|
|
1865
2657
|
}
|
|
2658
|
+
function handleGetReadyPhases(_cwd) {
|
|
2659
|
+
const cwd = _cwd ?? process.cwd();
|
|
2660
|
+
try {
|
|
2661
|
+
const state = readState(cwd);
|
|
2662
|
+
const completed = [];
|
|
2663
|
+
const ready = [];
|
|
2664
|
+
const blocked = [];
|
|
2665
|
+
for (const phase of PHASE_ORDER) {
|
|
2666
|
+
const ps = state.phases[phase];
|
|
2667
|
+
if (ps?.executed) {
|
|
2668
|
+
completed.push(phase);
|
|
2669
|
+
continue;
|
|
2670
|
+
}
|
|
2671
|
+
const deps = PHASE_DEPENDENCIES[phase];
|
|
2672
|
+
const unmetDeps = deps.filter((dep) => !state.phases[dep]?.executed);
|
|
2673
|
+
if (unmetDeps.length === 0) {
|
|
2674
|
+
ready.push(phase);
|
|
2675
|
+
} else {
|
|
2676
|
+
blocked.push(phase);
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
return {
|
|
2680
|
+
text: JSON.stringify({
|
|
2681
|
+
readyPhases: ready,
|
|
2682
|
+
completedPhases: completed,
|
|
2683
|
+
blockedPhases: blocked,
|
|
2684
|
+
waveSize: ready.length,
|
|
2685
|
+
allComplete: ready.length === 0 && blocked.length === 0
|
|
2686
|
+
}),
|
|
2687
|
+
isError: false
|
|
2688
|
+
};
|
|
2689
|
+
} catch (err) {
|
|
2690
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2691
|
+
return { text: JSON.stringify({ error: true, message }), isError: true };
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
1866
2694
|
function handleListArtifacts(_cwd) {
|
|
1867
2695
|
const cwd = _cwd ?? process.cwd();
|
|
1868
2696
|
try {
|
|
1869
|
-
const artifactsDir = (0,
|
|
2697
|
+
const artifactsDir = (0, import_path5.join)(cwd, ".stackwright", "artifacts");
|
|
2698
|
+
let manifest = null;
|
|
2699
|
+
try {
|
|
2700
|
+
manifest = loadSignatureManifest(cwd);
|
|
2701
|
+
} catch {
|
|
2702
|
+
}
|
|
1870
2703
|
const artifacts = [];
|
|
1871
2704
|
let completedCount = 0;
|
|
1872
2705
|
for (const phase of PHASE_ORDER) {
|
|
1873
2706
|
const expectedFile = PHASE_ARTIFACT[phase];
|
|
1874
|
-
const fullPath = (0,
|
|
1875
|
-
const exists = (0,
|
|
2707
|
+
const fullPath = (0, import_path5.join)(artifactsDir, expectedFile);
|
|
2708
|
+
const exists = (0, import_fs5.existsSync)(fullPath);
|
|
1876
2709
|
if (exists) completedCount++;
|
|
1877
|
-
|
|
2710
|
+
let signed = false;
|
|
2711
|
+
let signatureValid = null;
|
|
2712
|
+
if (exists && manifest) {
|
|
2713
|
+
const entry = manifest.signatures[expectedFile];
|
|
2714
|
+
if (entry) {
|
|
2715
|
+
signed = true;
|
|
2716
|
+
try {
|
|
2717
|
+
const rawBytes = Buffer.from(safeReadSync(fullPath), "utf-8");
|
|
2718
|
+
const { publicKey } = loadPipelineKeys(cwd);
|
|
2719
|
+
signatureValid = verifyArtifact(rawBytes, entry, publicKey);
|
|
2720
|
+
} catch {
|
|
2721
|
+
signatureValid = null;
|
|
2722
|
+
}
|
|
2723
|
+
}
|
|
2724
|
+
}
|
|
2725
|
+
artifacts.push({ phase, expectedFile, exists, path: fullPath, signed, signatureValid });
|
|
1878
2726
|
}
|
|
1879
2727
|
return {
|
|
1880
2728
|
text: JSON.stringify({ artifacts, completedCount, totalCount: PHASE_ORDER.length }),
|
|
@@ -1887,7 +2735,7 @@ function handleListArtifacts(_cwd) {
|
|
|
1887
2735
|
function handleWritePhaseQuestions(input) {
|
|
1888
2736
|
const cwd = input._cwd ?? process.cwd();
|
|
1889
2737
|
const { phase, responseText } = input;
|
|
1890
|
-
if (!
|
|
2738
|
+
if (!isValidPhase2(phase)) {
|
|
1891
2739
|
return {
|
|
1892
2740
|
text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
|
|
1893
2741
|
isError: true
|
|
@@ -1910,9 +2758,9 @@ function handleWritePhaseQuestions(input) {
|
|
|
1910
2758
|
}
|
|
1911
2759
|
} catch {
|
|
1912
2760
|
}
|
|
1913
|
-
const questionsDir = (0,
|
|
1914
|
-
(0,
|
|
1915
|
-
const filePath = (0,
|
|
2761
|
+
const questionsDir = (0, import_path5.join)(cwd, ".stackwright", "questions");
|
|
2762
|
+
(0, import_fs5.mkdirSync)(questionsDir, { recursive: true });
|
|
2763
|
+
const filePath = (0, import_path5.join)(questionsDir, `${phase}.json`);
|
|
1916
2764
|
const payload = {
|
|
1917
2765
|
version: "1.0",
|
|
1918
2766
|
phase,
|
|
@@ -1945,43 +2793,88 @@ function handleWritePhaseQuestions(input) {
|
|
|
1945
2793
|
function handleBuildSpecialistPrompt(input) {
|
|
1946
2794
|
const cwd = input._cwd ?? process.cwd();
|
|
1947
2795
|
const { phase } = input;
|
|
1948
|
-
if (!
|
|
2796
|
+
if (!isValidPhase2(phase)) {
|
|
1949
2797
|
return {
|
|
1950
2798
|
text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
|
|
1951
2799
|
isError: true
|
|
1952
2800
|
};
|
|
1953
2801
|
}
|
|
1954
2802
|
try {
|
|
1955
|
-
const answersPath = (0,
|
|
2803
|
+
const answersPath = (0, import_path5.join)(cwd, ".stackwright", "answers", `${phase}.json`);
|
|
1956
2804
|
let answers = {};
|
|
1957
|
-
if ((0,
|
|
2805
|
+
if ((0, import_fs5.existsSync)(answersPath)) {
|
|
1958
2806
|
answers = JSON.parse(safeReadSync(answersPath));
|
|
1959
2807
|
}
|
|
2808
|
+
let buildContextText = "";
|
|
2809
|
+
const buildContextPath = (0, import_path5.join)(cwd, ".stackwright", "build-context.json");
|
|
2810
|
+
if ((0, import_fs5.existsSync)(buildContextPath)) {
|
|
2811
|
+
try {
|
|
2812
|
+
const bcRaw = JSON.parse(safeReadSync(buildContextPath));
|
|
2813
|
+
if (typeof bcRaw.buildContext === "string" && bcRaw.buildContext.trim().length > 0) {
|
|
2814
|
+
buildContextText = bcRaw.buildContext.trim();
|
|
2815
|
+
}
|
|
2816
|
+
} catch {
|
|
2817
|
+
}
|
|
2818
|
+
}
|
|
1960
2819
|
const deps = PHASE_DEPENDENCIES[phase];
|
|
1961
2820
|
const artifactSections = [];
|
|
1962
2821
|
const missingDependencies = [];
|
|
1963
2822
|
for (const dep of deps) {
|
|
1964
2823
|
const artifactFile = PHASE_ARTIFACT[dep];
|
|
1965
|
-
const artifactPath = (0,
|
|
1966
|
-
if ((0,
|
|
1967
|
-
const
|
|
2824
|
+
const artifactPath = (0, import_path5.join)(cwd, ".stackwright", "artifacts", artifactFile);
|
|
2825
|
+
if ((0, import_fs5.existsSync)(artifactPath)) {
|
|
2826
|
+
const rawContent = safeReadSync(artifactPath);
|
|
2827
|
+
const rawBytes = Buffer.from(rawContent, "utf-8");
|
|
2828
|
+
const content = JSON.parse(rawContent);
|
|
2829
|
+
let signatureVerified = false;
|
|
2830
|
+
let signatureAvailable = false;
|
|
2831
|
+
try {
|
|
2832
|
+
const sig = getArtifactSignature(cwd, artifactFile);
|
|
2833
|
+
if (sig) {
|
|
2834
|
+
signatureAvailable = true;
|
|
2835
|
+
const { publicKey } = loadPipelineKeys(cwd);
|
|
2836
|
+
signatureVerified = verifyArtifact(rawBytes, sig, publicKey);
|
|
2837
|
+
if (!signatureVerified) {
|
|
2838
|
+
const actualDigest = (0, import_crypto3.createHash)("sha384").update(rawBytes).digest("hex");
|
|
2839
|
+
emitSignatureAuditEvent({
|
|
2840
|
+
artifactFilename: artifactFile,
|
|
2841
|
+
expectedDigest: sig.digest,
|
|
2842
|
+
actualDigest,
|
|
2843
|
+
phase: dep,
|
|
2844
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2845
|
+
source: "stackwright_pro_build_specialist_prompt"
|
|
2846
|
+
});
|
|
2847
|
+
missingDependencies.push(dep);
|
|
2848
|
+
artifactSections.push(
|
|
2849
|
+
`[${artifactFile}]:
|
|
2850
|
+
(integrity check failed: ECDSA-P384 signature verification failed \u2014 artifact may have been tampered with)`
|
|
2851
|
+
);
|
|
2852
|
+
continue;
|
|
2853
|
+
}
|
|
2854
|
+
}
|
|
2855
|
+
} catch {
|
|
2856
|
+
}
|
|
1968
2857
|
const expectedOtter = PHASE_TO_OTTER2[dep];
|
|
1969
2858
|
const artifactOtter = content["generatedBy"];
|
|
2859
|
+
const normalizedOtter = artifactOtter?.replace(/-[a-f0-9]{6}$/, "");
|
|
1970
2860
|
if (!artifactOtter) {
|
|
1971
2861
|
missingDependencies.push(dep);
|
|
1972
2862
|
artifactSections.push(
|
|
1973
2863
|
`[${artifactFile}]:
|
|
1974
2864
|
(integrity check failed: missing generatedBy field)`
|
|
1975
2865
|
);
|
|
1976
|
-
} else if (
|
|
2866
|
+
} else if (normalizedOtter !== expectedOtter) {
|
|
1977
2867
|
missingDependencies.push(dep);
|
|
1978
2868
|
artifactSections.push(
|
|
1979
2869
|
`[${artifactFile}]:
|
|
1980
2870
|
(integrity check failed: artifact claims generatedBy="${artifactOtter}" but expected="${expectedOtter}")`
|
|
1981
2871
|
);
|
|
1982
2872
|
} else {
|
|
1983
|
-
|
|
1984
|
-
|
|
2873
|
+
const sigStatus = signatureAvailable ? signatureVerified ? " [signature verified]" : " [signature check skipped]" : " [unsigned]";
|
|
2874
|
+
artifactSections.push(
|
|
2875
|
+
`[${artifactFile}]${sigStatus}:
|
|
2876
|
+
${JSON.stringify(content, null, 2)}`
|
|
2877
|
+
);
|
|
1985
2878
|
}
|
|
1986
2879
|
} else {
|
|
1987
2880
|
missingDependencies.push(dep);
|
|
@@ -1989,10 +2882,29 @@ ${JSON.stringify(content, null, 2)}`);
|
|
|
1989
2882
|
(not yet available)`);
|
|
1990
2883
|
}
|
|
1991
2884
|
}
|
|
1992
|
-
const parts = [
|
|
2885
|
+
const parts = [];
|
|
2886
|
+
if (buildContextText) {
|
|
2887
|
+
parts.push("BUILD_CONTEXT:", buildContextText, "");
|
|
2888
|
+
}
|
|
2889
|
+
if (phase === "auth") {
|
|
2890
|
+
const initContextPath = (0, import_path5.join)(cwd, ".stackwright", "init-context.json");
|
|
2891
|
+
if ((0, import_fs5.existsSync)(initContextPath)) {
|
|
2892
|
+
try {
|
|
2893
|
+
const initContext = JSON.parse(safeReadSync(initContextPath));
|
|
2894
|
+
if (initContext.devOnly === true || initContext.nonInteractive === true) {
|
|
2895
|
+
answers["devOnly"] = true;
|
|
2896
|
+
}
|
|
2897
|
+
} catch {
|
|
2898
|
+
}
|
|
2899
|
+
}
|
|
2900
|
+
}
|
|
2901
|
+
parts.push("ANSWERS:", JSON.stringify(answers, null, 2));
|
|
1993
2902
|
if (artifactSections.length > 0) {
|
|
1994
2903
|
parts.push("", "UPSTREAM ARTIFACTS:", "", ...artifactSections);
|
|
1995
2904
|
}
|
|
2905
|
+
const artifactSchema = PHASE_ARTIFACT_SCHEMA[phase];
|
|
2906
|
+
parts.push("", "REQUIRED_ARTIFACT_SCHEMA:");
|
|
2907
|
+
parts.push(artifactSchema);
|
|
1996
2908
|
parts.push("", "Execute using these answers and the upstream artifacts provided.");
|
|
1997
2909
|
const prompt = parts.join("\n");
|
|
1998
2910
|
const dependenciesSatisfied = missingDependencies.length === 0;
|
|
@@ -2027,49 +2939,323 @@ var OFF_SCRIPT_PATTERNS = [
|
|
|
2027
2939
|
var PHASE_REQUIRED_KEYS = {
|
|
2028
2940
|
designer: ["designLanguage", "themeTokenSeeds"],
|
|
2029
2941
|
theme: ["tokens"],
|
|
2030
|
-
api: ["entities"],
|
|
2942
|
+
api: ["entities", "version", "generatedBy"],
|
|
2031
2943
|
auth: ["version", "generatedBy"],
|
|
2032
|
-
data: ["version", "generatedBy"],
|
|
2944
|
+
data: ["version", "generatedBy", "strategy", "collections"],
|
|
2033
2945
|
pages: ["version", "generatedBy"],
|
|
2034
2946
|
dashboard: ["version", "generatedBy"],
|
|
2035
|
-
workflow: ["version", "generatedBy"]
|
|
2947
|
+
workflow: ["version", "generatedBy"],
|
|
2948
|
+
services: ["version", "generatedBy", "flows"],
|
|
2949
|
+
polish: ["version", "generatedBy"],
|
|
2950
|
+
geo: ["version", "generatedBy", "geoCollections"]
|
|
2036
2951
|
};
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2952
|
+
var PHASE_ARTIFACT_SCHEMA = {
|
|
2953
|
+
designer: JSON.stringify(
|
|
2954
|
+
{
|
|
2955
|
+
version: "1.0",
|
|
2956
|
+
generatedBy: "stackwright-pro-designer-otter",
|
|
2957
|
+
application: {
|
|
2958
|
+
type: "<operational|data-explorer|admin|logistics|general>",
|
|
2959
|
+
environment: "<workstation|field|control-room|mixed>",
|
|
2960
|
+
density: "<compact|balanced|spacious>",
|
|
2961
|
+
accessibility: "<wcag-aa|section-508|none>",
|
|
2962
|
+
colorScheme: "<light|dark|both>"
|
|
2963
|
+
},
|
|
2964
|
+
designLanguage: {
|
|
2965
|
+
rationale: "<design rationale>",
|
|
2966
|
+
spacingScale: { base: 8, scale: [0, 4, 8, 16, 24, 32, 48, 64] },
|
|
2967
|
+
colorSemantics: { primary: "#1a365d", accent: "#e53e3e" },
|
|
2968
|
+
typography: {
|
|
2969
|
+
dataFont: "Inter",
|
|
2970
|
+
headingFont: "Inter",
|
|
2971
|
+
monoFont: "monospace",
|
|
2972
|
+
dataSizePx: 12,
|
|
2973
|
+
bodySizePx: 14
|
|
2974
|
+
},
|
|
2975
|
+
contrastRatio: "4.5",
|
|
2976
|
+
borderRadius: "4",
|
|
2977
|
+
shadowElevation: "standard"
|
|
2978
|
+
},
|
|
2979
|
+
themeTokenSeeds: {
|
|
2980
|
+
light: {
|
|
2981
|
+
background: "#ffffff",
|
|
2982
|
+
foreground: "#1a1a1a",
|
|
2983
|
+
primary: "#1a365d",
|
|
2984
|
+
surface: "#f7f7f7",
|
|
2985
|
+
border: "#e2e8f0"
|
|
2986
|
+
},
|
|
2987
|
+
dark: {
|
|
2988
|
+
background: "#1a1a1a",
|
|
2989
|
+
foreground: "#ffffff",
|
|
2990
|
+
primary: "#90cdf4",
|
|
2991
|
+
surface: "#2d2d2d",
|
|
2992
|
+
border: "#4a5568"
|
|
2993
|
+
}
|
|
2994
|
+
},
|
|
2995
|
+
conformsTo: null,
|
|
2996
|
+
operationalNotes: []
|
|
2997
|
+
},
|
|
2998
|
+
null,
|
|
2999
|
+
2
|
|
3000
|
+
),
|
|
3001
|
+
theme: JSON.stringify(
|
|
3002
|
+
{
|
|
3003
|
+
version: "1.0",
|
|
3004
|
+
generatedBy: "stackwright-pro-theme-otter",
|
|
3005
|
+
componentLibrary: "shadcn",
|
|
3006
|
+
colorScheme: "<light|dark|both>",
|
|
3007
|
+
tokens: {
|
|
3008
|
+
colors: { "primary-500": "#1a365d", background: "#ffffff" },
|
|
3009
|
+
spacing: { "spacing-1": "8px", "spacing-2": "16px" },
|
|
3010
|
+
typography: { "font-data": "Inter", "text-sm": "12px" },
|
|
3011
|
+
shape: { "radius-sm": "4px", "radius-md": "8px" },
|
|
3012
|
+
shadows: { "shadow-sm": "0 1px 2px rgba(0,0,0,0.08)" }
|
|
3013
|
+
},
|
|
3014
|
+
cssVariables: {
|
|
3015
|
+
"--background": "0 0% 100%",
|
|
3016
|
+
"--foreground": "222.2 84% 4.9%",
|
|
3017
|
+
"--primary": "222.2 47.4% 11.2%",
|
|
3018
|
+
"--primary-foreground": "210 40% 98%",
|
|
3019
|
+
"--surface": "210 40% 98%",
|
|
3020
|
+
"--border": "214.3 31.8% 91.4%"
|
|
3021
|
+
},
|
|
3022
|
+
dark: { "--background": "222.2 84% 4.9%", "--foreground": "210 40% 98%" }
|
|
3023
|
+
},
|
|
3024
|
+
null,
|
|
3025
|
+
2
|
|
3026
|
+
),
|
|
3027
|
+
api: JSON.stringify(
|
|
3028
|
+
{
|
|
3029
|
+
version: "1.0",
|
|
3030
|
+
generatedBy: "stackwright-pro-api-otter",
|
|
3031
|
+
entities: [
|
|
3032
|
+
{
|
|
3033
|
+
name: "Shipment",
|
|
3034
|
+
endpoint: "/shipments",
|
|
3035
|
+
method: "GET",
|
|
3036
|
+
revalidate: 60,
|
|
3037
|
+
mutationType: null
|
|
3038
|
+
}
|
|
3039
|
+
],
|
|
3040
|
+
skipped: [
|
|
3041
|
+
{
|
|
3042
|
+
spec: "ais-message-models.yaml",
|
|
3043
|
+
format: "asyncapi",
|
|
3044
|
+
reason: "AsyncAPI spec \u2014 WebSocket/event integration required (no REST endpoints)"
|
|
3045
|
+
}
|
|
3046
|
+
],
|
|
3047
|
+
auth: { type: "bearer", header: "Authorization", envVar: "API_TOKEN" },
|
|
3048
|
+
baseUrl: "https://api.example.mil/v2",
|
|
3049
|
+
specPath: "./specs/api.yaml"
|
|
3050
|
+
},
|
|
3051
|
+
null,
|
|
3052
|
+
2
|
|
3053
|
+
),
|
|
3054
|
+
data: JSON.stringify(
|
|
3055
|
+
{
|
|
3056
|
+
version: "1.0",
|
|
3057
|
+
generatedBy: "stackwright-pro-data-otter",
|
|
3058
|
+
strategy: "<pulse-fast|isr-fast|isr-standard|isr-slow>",
|
|
3059
|
+
pulseMode: false,
|
|
3060
|
+
collections: [{ name: "equipment", revalidate: 60, pulse: false }],
|
|
3061
|
+
endpoints: { included: ["/equipment/**"], excluded: ["/admin/**"] },
|
|
3062
|
+
requiredPackages: { dependencies: {}, devPackages: {} }
|
|
3063
|
+
},
|
|
3064
|
+
null,
|
|
3065
|
+
2
|
|
3066
|
+
),
|
|
3067
|
+
geo: JSON.stringify(
|
|
3068
|
+
{
|
|
3069
|
+
version: "1.0",
|
|
3070
|
+
generatedBy: "stackwright-pro-geo-otter",
|
|
3071
|
+
geoCollections: [
|
|
3072
|
+
{
|
|
3073
|
+
collection: "vessels",
|
|
3074
|
+
latField: "latitude",
|
|
3075
|
+
lngField: "longitude",
|
|
3076
|
+
labelField: "vesselName",
|
|
3077
|
+
colorField: "navigationStatus"
|
|
3078
|
+
}
|
|
3079
|
+
],
|
|
3080
|
+
pages: [
|
|
3081
|
+
{
|
|
3082
|
+
slug: "fleet-tracker",
|
|
3083
|
+
type: "<tracker|zone|route|combined>",
|
|
3084
|
+
collections: ["vessels"],
|
|
3085
|
+
hasLayers: false
|
|
3086
|
+
}
|
|
3087
|
+
]
|
|
3088
|
+
},
|
|
3089
|
+
null,
|
|
3090
|
+
2
|
|
3091
|
+
),
|
|
3092
|
+
workflow: JSON.stringify(
|
|
3093
|
+
{
|
|
3094
|
+
version: "1.0",
|
|
3095
|
+
generatedBy: "stackwright-pro-workflow-otter",
|
|
3096
|
+
workflowConfig: {
|
|
3097
|
+
id: "procurement-approval",
|
|
3098
|
+
route: "/procurement",
|
|
3099
|
+
files: ["workflows/procurement-approval.yml"],
|
|
3100
|
+
serviceDependencies: ["service:workflow-state"],
|
|
3101
|
+
warnings: []
|
|
3102
|
+
}
|
|
3103
|
+
},
|
|
3104
|
+
null,
|
|
3105
|
+
2
|
|
3106
|
+
),
|
|
3107
|
+
services: JSON.stringify(
|
|
3108
|
+
{
|
|
3109
|
+
version: "1.0",
|
|
3110
|
+
generatedBy: "stackwright-services-otter",
|
|
3111
|
+
flows: [
|
|
3112
|
+
{
|
|
3113
|
+
name: "at-risk-patients",
|
|
3114
|
+
trigger: "<http|event|schedule|queue>",
|
|
3115
|
+
steps: 3,
|
|
3116
|
+
outputSpec: "at-risk-patients.openapi.json"
|
|
3117
|
+
}
|
|
3118
|
+
],
|
|
3119
|
+
workflows: [
|
|
3120
|
+
{
|
|
3121
|
+
name: "evacuation-coordination",
|
|
3122
|
+
states: 4,
|
|
3123
|
+
transitions: 5
|
|
3124
|
+
}
|
|
3125
|
+
],
|
|
3126
|
+
openApiSpecs: ["at-risk-patients.openapi.json"],
|
|
3127
|
+
capabilitiesUsed: ["service.call", "collection.join", "collection.filter"]
|
|
3128
|
+
},
|
|
3129
|
+
null,
|
|
3130
|
+
2
|
|
3131
|
+
),
|
|
3132
|
+
pages: JSON.stringify(
|
|
3133
|
+
{
|
|
3134
|
+
version: "1.0",
|
|
3135
|
+
generatedBy: "stackwright-pro-page-otter",
|
|
3136
|
+
pages: [
|
|
3137
|
+
{
|
|
3138
|
+
slug: "catalog",
|
|
3139
|
+
type: "collection_listing",
|
|
3140
|
+
collection: "products",
|
|
3141
|
+
themeApplied: true,
|
|
3142
|
+
authRequired: false
|
|
3143
|
+
},
|
|
3144
|
+
{
|
|
3145
|
+
slug: "admin",
|
|
3146
|
+
type: "protected",
|
|
3147
|
+
collection: null,
|
|
3148
|
+
themeApplied: true,
|
|
3149
|
+
authRequired: true
|
|
3150
|
+
}
|
|
3151
|
+
]
|
|
3152
|
+
},
|
|
3153
|
+
null,
|
|
3154
|
+
2
|
|
3155
|
+
),
|
|
3156
|
+
dashboard: JSON.stringify(
|
|
3157
|
+
{
|
|
3158
|
+
version: "1.0",
|
|
3159
|
+
generatedBy: "stackwright-pro-dashboard-otter",
|
|
3160
|
+
pages: [
|
|
3161
|
+
{
|
|
3162
|
+
slug: "dashboard",
|
|
3163
|
+
layout: "<grid|table|mixed>",
|
|
3164
|
+
collections: ["equipment", "supplies"],
|
|
3165
|
+
mode: "<ISR|Pulse>"
|
|
3166
|
+
}
|
|
3167
|
+
]
|
|
3168
|
+
},
|
|
3169
|
+
null,
|
|
3170
|
+
2
|
|
3171
|
+
),
|
|
3172
|
+
// type: 'pki' = CAC/DoD certificate auth | 'oidc' = enterprise SSO
|
|
3173
|
+
// For dev-only mock auth: use type: 'oidc' with devOnly: true (Zod strips devOnly — it's a convention only)
|
|
3174
|
+
auth: JSON.stringify(
|
|
3175
|
+
{
|
|
3176
|
+
version: "1.0",
|
|
3177
|
+
generatedBy: "stackwright-pro-auth-otter",
|
|
3178
|
+
authConfig: {
|
|
3179
|
+
type: "<pki|oidc>",
|
|
3180
|
+
// OIDC-only fields (omit for pki):
|
|
3181
|
+
provider: "<azure_ad|okta|cognito|auth0|authentik|keycloak|custom>",
|
|
3182
|
+
discoveryUrl: "<IdP OIDC discovery URL>",
|
|
3183
|
+
clientId: "<OIDC client ID>",
|
|
3184
|
+
clientSecret: "<OIDC client secret>",
|
|
3185
|
+
rbacRoles: ["ADMIN", "ANALYST"],
|
|
3186
|
+
rbacDefaultRole: "ANALYST",
|
|
3187
|
+
protectedRoutes: ["/dashboard/:path*", "/procurement/:path*"],
|
|
3188
|
+
auditEnabled: true,
|
|
3189
|
+
auditRetentionDays: 90
|
|
3190
|
+
},
|
|
3191
|
+
// devScripts is OPTIONAL — only present when devOnly: true was used
|
|
3192
|
+
// Polish otter and foreman MUST check devScripts.written before referencing scripts
|
|
3193
|
+
devScripts: {
|
|
3194
|
+
written: true,
|
|
3195
|
+
scripts: { "dev:admin": "MOCK_USER=admin next dev" }
|
|
3196
|
+
}
|
|
3197
|
+
},
|
|
3198
|
+
null,
|
|
3199
|
+
2
|
|
3200
|
+
),
|
|
3201
|
+
polish: JSON.stringify(
|
|
3202
|
+
{
|
|
3203
|
+
version: "1.0",
|
|
3204
|
+
generatedBy: "stackwright-pro-polish-otter",
|
|
3205
|
+
landingPage: { slug: "", rewritten: true },
|
|
3206
|
+
navigation: { itemCount: 5, items: ["/dashboard", "/equipment", "/workflows"] },
|
|
3207
|
+
gettingStarted: "<rewritten|redirected|not-found>",
|
|
3208
|
+
scaffoldCleanup: {
|
|
3209
|
+
deleted: ["content/posts/getting-started.yaml"],
|
|
3210
|
+
rewritten: ["app/not-found.tsx"],
|
|
3211
|
+
skipped: []
|
|
3212
|
+
}
|
|
3213
|
+
},
|
|
3214
|
+
null,
|
|
3215
|
+
2
|
|
3216
|
+
)
|
|
3217
|
+
};
|
|
3218
|
+
function handleValidateArtifact(input) {
|
|
3219
|
+
const cwd = input._cwd ?? process.cwd();
|
|
3220
|
+
const { phase, responseText, artifact: directArtifact } = input;
|
|
3221
|
+
if (!isValidPhase2(phase)) {
|
|
3222
|
+
return {
|
|
3223
|
+
text: JSON.stringify({ error: true, message: `Unknown phase: ${phase}` }),
|
|
3224
|
+
isError: true
|
|
3225
|
+
};
|
|
3226
|
+
}
|
|
3227
|
+
let artifact;
|
|
3228
|
+
if (directArtifact) {
|
|
3229
|
+
artifact = directArtifact;
|
|
3230
|
+
} else {
|
|
3231
|
+
const text = responseText ?? "";
|
|
3232
|
+
for (const { pattern, label } of OFF_SCRIPT_PATTERNS) {
|
|
3233
|
+
if (pattern.test(text)) {
|
|
3234
|
+
const result = {
|
|
3235
|
+
valid: false,
|
|
3236
|
+
phase,
|
|
3237
|
+
violation: "off-script",
|
|
3238
|
+
retryPrompt: `You returned code output (detected: ${label}). Return ONLY a JSON artifact \u2014 no code, no files.`
|
|
3239
|
+
};
|
|
3240
|
+
return { text: JSON.stringify(result), isError: false };
|
|
3241
|
+
}
|
|
3242
|
+
}
|
|
3243
|
+
try {
|
|
3244
|
+
artifact = extractJsonFromResponse(text);
|
|
3245
|
+
} catch {
|
|
3246
|
+
const result = {
|
|
3247
|
+
valid: false,
|
|
3248
|
+
phase,
|
|
3249
|
+
violation: "invalid-json",
|
|
3250
|
+
retryPrompt: "Your response did not contain valid JSON. Return a single JSON object with no surrounding text."
|
|
3251
|
+
};
|
|
3252
|
+
return { text: JSON.stringify(result), isError: false };
|
|
3253
|
+
}
|
|
3254
|
+
}
|
|
3255
|
+
if (!artifact.version || !artifact.generatedBy) {
|
|
3256
|
+
const result = {
|
|
3257
|
+
valid: false,
|
|
3258
|
+
phase,
|
|
2073
3259
|
violation: "missing-fields",
|
|
2074
3260
|
retryPrompt: 'Your JSON artifact is missing required fields. Every artifact MUST include "version" and "generatedBy" at the top level.'
|
|
2075
3261
|
};
|
|
@@ -2086,12 +3272,58 @@ function handleValidateArtifact(input) {
|
|
|
2086
3272
|
};
|
|
2087
3273
|
return { text: JSON.stringify(result), isError: false };
|
|
2088
3274
|
}
|
|
3275
|
+
const PHASE_ZOD_VALIDATORS = {
|
|
3276
|
+
workflow: (artifact2) => {
|
|
3277
|
+
const workflowConfig = artifact2["workflowConfig"];
|
|
3278
|
+
if (!workflowConfig) return { success: true };
|
|
3279
|
+
const result = import_types.WorkflowFileSchema.safeParse(workflowConfig);
|
|
3280
|
+
if (!result.success) {
|
|
3281
|
+
const issues = result.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
|
|
3282
|
+
return { success: false, error: { message: issues } };
|
|
3283
|
+
}
|
|
3284
|
+
return { success: true };
|
|
3285
|
+
},
|
|
3286
|
+
auth: (artifact2) => {
|
|
3287
|
+
const authConfig = artifact2["authConfig"];
|
|
3288
|
+
if (!authConfig) return { success: true };
|
|
3289
|
+
const result = import_types.authConfigSchema.safeParse(authConfig);
|
|
3290
|
+
if (!result.success) {
|
|
3291
|
+
const issues = result.error.issues.slice(0, 3).map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
|
|
3292
|
+
return { success: false, error: { message: issues } };
|
|
3293
|
+
}
|
|
3294
|
+
return { success: true };
|
|
3295
|
+
}
|
|
3296
|
+
};
|
|
3297
|
+
const zodValidator = PHASE_ZOD_VALIDATORS[phase];
|
|
3298
|
+
if (zodValidator) {
|
|
3299
|
+
const zodResult = zodValidator(artifact);
|
|
3300
|
+
if (!zodResult.success) {
|
|
3301
|
+
const result = {
|
|
3302
|
+
valid: false,
|
|
3303
|
+
phase,
|
|
3304
|
+
violation: "schema-mismatch",
|
|
3305
|
+
retryPrompt: `Your artifact failed schema validation: ${zodResult.error?.message}. Fix these fields and return the corrected JSON artifact.`
|
|
3306
|
+
};
|
|
3307
|
+
return { text: JSON.stringify(result), isError: false };
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
2089
3310
|
try {
|
|
2090
|
-
const artifactsDir = (0,
|
|
2091
|
-
(0,
|
|
3311
|
+
const artifactsDir = (0, import_path5.join)(cwd, ".stackwright", "artifacts");
|
|
3312
|
+
(0, import_fs5.mkdirSync)(artifactsDir, { recursive: true });
|
|
2092
3313
|
const artifactFile = PHASE_ARTIFACT[phase];
|
|
2093
|
-
const artifactPath = (0,
|
|
2094
|
-
|
|
3314
|
+
const artifactPath = (0, import_path5.join)(artifactsDir, artifactFile);
|
|
3315
|
+
const serialized = JSON.stringify(artifact, null, 2) + "\n";
|
|
3316
|
+
const artifactBytes = Buffer.from(serialized, "utf-8");
|
|
3317
|
+
safeWriteSync(artifactPath, serialized);
|
|
3318
|
+
let signed = false;
|
|
3319
|
+
try {
|
|
3320
|
+
const { privateKey } = loadPipelineKeys(cwd);
|
|
3321
|
+
const sig = signArtifact(artifactBytes, privateKey);
|
|
3322
|
+
const signerOtter = PHASE_TO_OTTER2[phase];
|
|
3323
|
+
saveArtifactSignature(cwd, artifactFile, sig, signerOtter);
|
|
3324
|
+
signed = true;
|
|
3325
|
+
} catch {
|
|
3326
|
+
}
|
|
2095
3327
|
const state = readState(cwd);
|
|
2096
3328
|
if (!state.phases[phase]) state.phases[phase] = defaultPhaseStatus();
|
|
2097
3329
|
const ps = state.phases[phase];
|
|
@@ -2102,7 +3334,7 @@ function handleValidateArtifact(input) {
|
|
|
2102
3334
|
valid: true,
|
|
2103
3335
|
phase,
|
|
2104
3336
|
artifactPath,
|
|
2105
|
-
summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})`
|
|
3337
|
+
summary: `Wrote ${artifactFile} (keys: ${topKeys}${Object.keys(artifact).length > 5 ? ", ..." : ""})${signed ? " [signed]" : ""}`
|
|
2106
3338
|
};
|
|
2107
3339
|
return { text: JSON.stringify(result), isError: false };
|
|
2108
3340
|
} catch (err) {
|
|
@@ -2126,11 +3358,24 @@ function registerPipelineTools(server2) {
|
|
|
2126
3358
|
"stackwright_pro_set_pipeline_state",
|
|
2127
3359
|
`Atomic read\u2192modify\u2192write pipeline state. ${DESC}`,
|
|
2128
3360
|
{
|
|
2129
|
-
phase:
|
|
2130
|
-
field:
|
|
2131
|
-
value:
|
|
2132
|
-
|
|
2133
|
-
|
|
3361
|
+
phase: import_zod11.z.string().optional().describe('Phase to update, e.g. "designer"'),
|
|
3362
|
+
field: import_zod11.z.enum(["questionsCollected", "answered", "executed", "artifactWritten"]).optional().describe("Boolean field to set"),
|
|
3363
|
+
value: boolCoerce(import_zod11.z.boolean().optional()).describe(
|
|
3364
|
+
'Value for the field \u2014 must be a JSON boolean (true/false), NOT the string "true"/"false"'
|
|
3365
|
+
),
|
|
3366
|
+
status: import_zod11.z.enum(["setup", "questions", "execution", "done"]).optional().describe("Top-level status override"),
|
|
3367
|
+
incrementRetry: boolCoerce(import_zod11.z.boolean().optional()).describe(
|
|
3368
|
+
"Bump retryCount by 1 \u2014 must be a JSON boolean"
|
|
3369
|
+
),
|
|
3370
|
+
updates: jsonCoerce(
|
|
3371
|
+
import_zod11.z.array(
|
|
3372
|
+
import_zod11.z.object({
|
|
3373
|
+
phase: import_zod11.z.string(),
|
|
3374
|
+
field: import_zod11.z.enum(["questionsCollected", "answered", "executed", "artifactWritten"]),
|
|
3375
|
+
value: import_zod11.z.boolean()
|
|
3376
|
+
})
|
|
3377
|
+
).optional()
|
|
3378
|
+
).describe("Batch updates \u2014 apply multiple field changes in one atomic read\u2192modify\u2192write")
|
|
2134
3379
|
},
|
|
2135
3380
|
async (args) => res(
|
|
2136
3381
|
handleSetPipelineState({
|
|
@@ -2138,15 +3383,24 @@ function registerPipelineTools(server2) {
|
|
|
2138
3383
|
...args.field != null ? { field: args.field } : {},
|
|
2139
3384
|
...args.value != null ? { value: args.value } : {},
|
|
2140
3385
|
...args.status != null ? { status: args.status } : {},
|
|
2141
|
-
...args.incrementRetry != null ? { incrementRetry: args.incrementRetry } : {}
|
|
3386
|
+
...args.incrementRetry != null ? { incrementRetry: args.incrementRetry } : {},
|
|
3387
|
+
...args.updates != null ? { updates: args.updates } : {}
|
|
2142
3388
|
})
|
|
2143
3389
|
)
|
|
2144
3390
|
);
|
|
2145
3391
|
server2.tool(
|
|
2146
3392
|
"stackwright_pro_check_execution_ready",
|
|
2147
|
-
`Check all phases have answer files in .stackwright/answers/. ${DESC}`,
|
|
3393
|
+
`Check all phases have answer files in .stackwright/answers/. If phase is provided, check only that phase. ${DESC}`,
|
|
3394
|
+
{
|
|
3395
|
+
phase: import_zod11.z.string().optional().describe("If provided, check only this phase's readiness. Omit to check all phases.")
|
|
3396
|
+
},
|
|
3397
|
+
async ({ phase }) => res(handleCheckExecutionReady(void 0, phase))
|
|
3398
|
+
);
|
|
3399
|
+
server2.tool(
|
|
3400
|
+
"stackwright_pro_get_ready_phases",
|
|
3401
|
+
`Return phases whose dependencies are all satisfied (executed=true). Use to determine which phases can run next \u2014 enables wave-based execution. ${DESC}`,
|
|
2148
3402
|
{},
|
|
2149
|
-
async () => res(
|
|
3403
|
+
async () => res(handleGetReadyPhases())
|
|
2150
3404
|
);
|
|
2151
3405
|
server2.tool(
|
|
2152
3406
|
"stackwright_pro_list_artifacts",
|
|
@@ -2156,40 +3410,91 @@ function registerPipelineTools(server2) {
|
|
|
2156
3410
|
);
|
|
2157
3411
|
server2.tool(
|
|
2158
3412
|
"stackwright_pro_write_phase_questions",
|
|
2159
|
-
`Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. ${DESC}`,
|
|
3413
|
+
`Parse otter question-collection response \u2192 .stackwright/questions/{phase}.json. Specialists may also call this directly with a parsed questions array. ${DESC}`,
|
|
2160
3414
|
{
|
|
2161
|
-
phase:
|
|
2162
|
-
responseText:
|
|
3415
|
+
phase: import_zod11.z.string().optional().describe('Phase name, e.g. "designer" (required for direct write)'),
|
|
3416
|
+
responseText: import_zod11.z.string().optional().describe("Raw LLM response from QUESTION_COLLECTION_MODE"),
|
|
3417
|
+
questions: jsonCoerce(import_zod11.z.array(import_zod11.z.any()).optional()).describe(
|
|
3418
|
+
"Questions array for direct specialist write"
|
|
3419
|
+
)
|
|
2163
3420
|
},
|
|
2164
|
-
async ({ phase, responseText }) =>
|
|
3421
|
+
async ({ phase, responseText, questions }) => {
|
|
3422
|
+
if (phase && questions && Array.isArray(questions)) {
|
|
3423
|
+
if (!SAFE_PHASE.test(phase)) {
|
|
3424
|
+
return {
|
|
3425
|
+
content: [
|
|
3426
|
+
{ type: "text", text: JSON.stringify({ error: `Invalid phase name` }) }
|
|
3427
|
+
],
|
|
3428
|
+
isError: true
|
|
3429
|
+
};
|
|
3430
|
+
}
|
|
3431
|
+
const questionsDir = (0, import_path5.join)(process.cwd(), ".stackwright", "questions");
|
|
3432
|
+
(0, import_fs5.mkdirSync)(questionsDir, { recursive: true });
|
|
3433
|
+
const outPath = (0, import_path5.join)(questionsDir, `${phase}.json`);
|
|
3434
|
+
(0, import_fs5.writeFileSync)(
|
|
3435
|
+
outPath,
|
|
3436
|
+
JSON.stringify({ phase, questions, writtenAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2)
|
|
3437
|
+
);
|
|
3438
|
+
return {
|
|
3439
|
+
content: [
|
|
3440
|
+
{
|
|
3441
|
+
type: "text",
|
|
3442
|
+
text: JSON.stringify({
|
|
3443
|
+
written: true,
|
|
3444
|
+
phase,
|
|
3445
|
+
count: questions.length
|
|
3446
|
+
})
|
|
3447
|
+
}
|
|
3448
|
+
]
|
|
3449
|
+
};
|
|
3450
|
+
}
|
|
3451
|
+
return res(
|
|
3452
|
+
handleWritePhaseQuestions({ phase: phase ?? "", responseText: responseText ?? "" })
|
|
3453
|
+
);
|
|
3454
|
+
}
|
|
2165
3455
|
);
|
|
2166
3456
|
server2.tool(
|
|
2167
3457
|
"stackwright_pro_build_specialist_prompt",
|
|
2168
3458
|
`Assemble execution prompt from answers + upstream artifacts. Foreman passes verbatim. ${DESC}`,
|
|
2169
|
-
{ phase:
|
|
3459
|
+
{ phase: import_zod11.z.string().describe('Phase to build prompt for, e.g. "pages"') },
|
|
2170
3460
|
async ({ phase }) => res(handleBuildSpecialistPrompt({ phase }))
|
|
2171
3461
|
);
|
|
2172
3462
|
server2.tool(
|
|
2173
3463
|
"stackwright_pro_validate_artifact",
|
|
2174
|
-
`Validate
|
|
3464
|
+
`Validate and write artifact to .stackwright/artifacts/. Returns retryPrompt on failure. ${DESC}`,
|
|
2175
3465
|
{
|
|
2176
|
-
phase:
|
|
2177
|
-
responseText:
|
|
3466
|
+
phase: import_zod11.z.string().describe('Phase that produced this artifact, e.g. "designer"'),
|
|
3467
|
+
responseText: import_zod11.z.string().optional().describe("Raw response text from the specialist otter (Foreman-mediated path, legacy)"),
|
|
3468
|
+
artifact: jsonCoerce(import_zod11.z.record(import_zod11.z.string(), import_zod11.z.unknown()).optional()).describe(
|
|
3469
|
+
"Artifact object to validate and write directly (specialist direct path \u2014 skips off-script detection and JSON parsing)"
|
|
3470
|
+
)
|
|
2178
3471
|
},
|
|
2179
|
-
async ({ phase, responseText }) =>
|
|
3472
|
+
async ({ phase, responseText, artifact }) => {
|
|
3473
|
+
if (artifact) {
|
|
3474
|
+
return res(
|
|
3475
|
+
handleValidateArtifact({ phase, artifact })
|
|
3476
|
+
);
|
|
3477
|
+
}
|
|
3478
|
+
return res(handleValidateArtifact({ phase, responseText: responseText ?? "" }));
|
|
3479
|
+
}
|
|
2180
3480
|
);
|
|
2181
3481
|
}
|
|
2182
3482
|
|
|
2183
3483
|
// src/tools/safe-write.ts
|
|
2184
|
-
var
|
|
2185
|
-
var
|
|
2186
|
-
var
|
|
3484
|
+
var import_zod12 = require("zod");
|
|
3485
|
+
var import_fs6 = require("fs");
|
|
3486
|
+
var import_path6 = require("path");
|
|
2187
3487
|
var OTTER_WRITE_ALLOWLISTS = {
|
|
2188
3488
|
"stackwright-pro-designer-otter": [
|
|
2189
3489
|
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Design language artifact" }
|
|
2190
3490
|
],
|
|
2191
3491
|
"stackwright-pro-theme-otter": [
|
|
2192
|
-
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" }
|
|
3492
|
+
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Theme tokens artifact" },
|
|
3493
|
+
{
|
|
3494
|
+
prefix: "stackwright.theme.",
|
|
3495
|
+
suffix: ".yml",
|
|
3496
|
+
description: "Theme config YAML (merged at build time)"
|
|
3497
|
+
}
|
|
2193
3498
|
],
|
|
2194
3499
|
"stackwright-pro-auth-otter": [
|
|
2195
3500
|
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Auth config artifact" },
|
|
@@ -2199,6 +3504,16 @@ var OTTER_WRITE_ALLOWLISTS = {
|
|
|
2199
3504
|
prefix: ".env",
|
|
2200
3505
|
suffix: "",
|
|
2201
3506
|
description: "Dotenv files (.env, .env.local, .env.production, etc.)"
|
|
3507
|
+
},
|
|
3508
|
+
{
|
|
3509
|
+
prefix: "lib/mock-auth",
|
|
3510
|
+
suffix: ".ts",
|
|
3511
|
+
description: "Mock auth module (DEV_ONLY_MODE role updates)"
|
|
3512
|
+
},
|
|
3513
|
+
{
|
|
3514
|
+
prefix: "package.json",
|
|
3515
|
+
suffix: ".json",
|
|
3516
|
+
description: "Project package.json (DEV_ONLY_MODE script cleanup)"
|
|
2202
3517
|
}
|
|
2203
3518
|
],
|
|
2204
3519
|
"stackwright-pro-data-otter": [
|
|
@@ -2222,19 +3537,115 @@ var OTTER_WRITE_ALLOWLISTS = {
|
|
|
2222
3537
|
],
|
|
2223
3538
|
"stackwright-pro-api-otter": [
|
|
2224
3539
|
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "API config artifact" }
|
|
3540
|
+
],
|
|
3541
|
+
"stackwright-pro-geo-otter": [
|
|
3542
|
+
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Geo manifest artifact" },
|
|
3543
|
+
{ prefix: "pages/", suffix: "/content.yml", description: "Map page content" },
|
|
3544
|
+
{ prefix: "pages/", suffix: "/content.yaml", description: "Map page content" }
|
|
3545
|
+
],
|
|
3546
|
+
"stackwright-pro-polish-otter": [
|
|
3547
|
+
{
|
|
3548
|
+
prefix: "stackwright.yml",
|
|
3549
|
+
suffix: "",
|
|
3550
|
+
description: "Stackwright config (navigation updates)"
|
|
3551
|
+
},
|
|
3552
|
+
{ prefix: "pages/", suffix: "/content.yml", description: "Landing page content" },
|
|
3553
|
+
{ prefix: "pages/", suffix: "/content.yaml", description: "Landing page content" },
|
|
3554
|
+
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Polish artifact" },
|
|
3555
|
+
{ prefix: "README.md", suffix: "", description: "Project README rewrite" }
|
|
3556
|
+
],
|
|
3557
|
+
"stackwright-services-otter": [
|
|
3558
|
+
{ prefix: ".stackwright/artifacts/", suffix: ".json", description: "Services config artifact" },
|
|
3559
|
+
{ prefix: "services/", suffix: ".ts", description: "Service implementation files" },
|
|
3560
|
+
{ prefix: "services/", suffix: ".yaml", description: "Service flow definitions" },
|
|
3561
|
+
{ prefix: "services/", suffix: ".yml", description: "Service flow definitions" },
|
|
3562
|
+
{ prefix: "lib/seeds/", suffix: ".ts", description: "Seed data files" },
|
|
3563
|
+
{ prefix: "specs/", suffix: ".json", description: "Generated OpenAPI specs" },
|
|
3564
|
+
{ prefix: "specs/", suffix: ".yaml", description: "Generated OpenAPI specs" },
|
|
3565
|
+
{ prefix: "stackwright-generated/", suffix: ".json", description: "Services manifest" }
|
|
2225
3566
|
]
|
|
2226
3567
|
};
|
|
2227
3568
|
var PROTECTED_PATH_PREFIXES = [
|
|
2228
3569
|
".stackwright/pipeline-state.json",
|
|
3570
|
+
".stackwright/pipeline-keys.json",
|
|
3571
|
+
// ephemeral signing keys
|
|
3572
|
+
".stackwright/artifacts/signatures.json",
|
|
3573
|
+
// artifact signature manifest
|
|
2229
3574
|
".stackwright/questions/",
|
|
2230
|
-
".stackwright/answers/"
|
|
3575
|
+
".stackwright/answers/",
|
|
3576
|
+
".stackwright/page-registry.json"
|
|
3577
|
+
// page ownership — managed by safe_write internally
|
|
2231
3578
|
];
|
|
3579
|
+
var MAX_SAFE_WRITE_BYTES_JSON = 512 * 1024;
|
|
3580
|
+
var MAX_SAFE_WRITE_BYTES_YAML = 256 * 1024;
|
|
3581
|
+
var MAX_SAFE_WRITE_BYTES_ENV = 4 * 1024;
|
|
3582
|
+
var MAX_SAFE_WRITE_BYTES_DEFAULT = 256 * 1024;
|
|
3583
|
+
function getMaxBytesForPath(filePath) {
|
|
3584
|
+
if (filePath.endsWith(".json")) return { limit: MAX_SAFE_WRITE_BYTES_JSON, label: "JSON" };
|
|
3585
|
+
if (filePath.endsWith(".yml") || filePath.endsWith(".yaml"))
|
|
3586
|
+
return { limit: MAX_SAFE_WRITE_BYTES_YAML, label: "YAML" };
|
|
3587
|
+
if (filePath === ".env" || /^\.env\.[a-zA-Z0-9]+/.test(filePath))
|
|
3588
|
+
return { limit: MAX_SAFE_WRITE_BYTES_ENV, label: "env" };
|
|
3589
|
+
return { limit: MAX_SAFE_WRITE_BYTES_DEFAULT, label: "default" };
|
|
3590
|
+
}
|
|
3591
|
+
var PAGE_REGISTRY_FILE = ".stackwright/page-registry.json";
|
|
3592
|
+
function extractPageSlug(filePath) {
|
|
3593
|
+
const match = (0, import_path6.normalize)(filePath).match(/^pages\/(.+?)\/content\.ya?ml$/);
|
|
3594
|
+
return match?.[1] ?? null;
|
|
3595
|
+
}
|
|
3596
|
+
function extractContentTypes(yamlContent) {
|
|
3597
|
+
const typePattern = /^\s*-?\s*type:\s*(\S+)/gm;
|
|
3598
|
+
const types = [];
|
|
3599
|
+
let m;
|
|
3600
|
+
while ((m = typePattern.exec(yamlContent)) !== null) {
|
|
3601
|
+
const typeName = m[1];
|
|
3602
|
+
if (typeName && !types.includes(typeName)) {
|
|
3603
|
+
types.push(typeName);
|
|
3604
|
+
}
|
|
3605
|
+
}
|
|
3606
|
+
return types.length > 0 ? types : ["unknown"];
|
|
3607
|
+
}
|
|
3608
|
+
function readPageRegistry(cwd) {
|
|
3609
|
+
const regPath = (0, import_path6.join)(cwd, PAGE_REGISTRY_FILE);
|
|
3610
|
+
if (!(0, import_fs6.existsSync)(regPath)) return {};
|
|
3611
|
+
try {
|
|
3612
|
+
const stat = (0, import_fs6.lstatSync)(regPath);
|
|
3613
|
+
if (stat.isSymbolicLink()) return {};
|
|
3614
|
+
return JSON.parse((0, import_fs6.readFileSync)(regPath, "utf-8"));
|
|
3615
|
+
} catch {
|
|
3616
|
+
return {};
|
|
3617
|
+
}
|
|
3618
|
+
}
|
|
3619
|
+
function writePageRegistry(cwd, registry) {
|
|
3620
|
+
const dir = (0, import_path6.join)(cwd, ".stackwright");
|
|
3621
|
+
(0, import_fs6.mkdirSync)(dir, { recursive: true });
|
|
3622
|
+
const regPath = (0, import_path6.join)(cwd, PAGE_REGISTRY_FILE);
|
|
3623
|
+
if ((0, import_fs6.existsSync)(regPath)) {
|
|
3624
|
+
const stat = (0, import_fs6.lstatSync)(regPath);
|
|
3625
|
+
if (stat.isSymbolicLink()) {
|
|
3626
|
+
throw new Error("Refusing to write page registry through symlink");
|
|
3627
|
+
}
|
|
3628
|
+
}
|
|
3629
|
+
(0, import_fs6.writeFileSync)(regPath, JSON.stringify(registry, null, 2) + "\n", { encoding: "utf-8" });
|
|
3630
|
+
}
|
|
3631
|
+
function checkPageOwnership(cwd, slug, callerOtter) {
|
|
3632
|
+
const registry = readPageRegistry(cwd);
|
|
3633
|
+
const existing = registry[slug];
|
|
3634
|
+
if (!existing || existing.claimedBy === callerOtter) {
|
|
3635
|
+
return { allowed: true };
|
|
3636
|
+
}
|
|
3637
|
+
return {
|
|
3638
|
+
allowed: false,
|
|
3639
|
+
owner: existing.claimedBy,
|
|
3640
|
+
contentTypes: existing.contentTypes
|
|
3641
|
+
};
|
|
3642
|
+
}
|
|
2232
3643
|
function checkPathAllowed(callerOtter, filePath) {
|
|
2233
|
-
const normalized = (0,
|
|
3644
|
+
const normalized = (0, import_path6.normalize)(filePath);
|
|
2234
3645
|
if (normalized.includes("..")) {
|
|
2235
3646
|
return { allowed: false, error: 'Path traversal detected: ".." segments are not allowed' };
|
|
2236
3647
|
}
|
|
2237
|
-
if ((0,
|
|
3648
|
+
if ((0, import_path6.isAbsolute)(normalized)) {
|
|
2238
3649
|
return {
|
|
2239
3650
|
allowed: false,
|
|
2240
3651
|
error: "Absolute paths are not allowed \u2014 use paths relative to project root"
|
|
@@ -2270,6 +3681,16 @@ function checkPathAllowed(callerOtter, filePath) {
|
|
|
2270
3681
|
continue;
|
|
2271
3682
|
}
|
|
2272
3683
|
}
|
|
3684
|
+
if (rule.prefix === "lib/mock-auth" && rule.suffix === ".ts") {
|
|
3685
|
+
if (normalized !== "lib/mock-auth.ts") {
|
|
3686
|
+
continue;
|
|
3687
|
+
}
|
|
3688
|
+
}
|
|
3689
|
+
if (rule.prefix === "package.json" && rule.suffix === ".json") {
|
|
3690
|
+
if (normalized !== "package.json") {
|
|
3691
|
+
continue;
|
|
3692
|
+
}
|
|
3693
|
+
}
|
|
2273
3694
|
return { allowed: true, rule: rule.description };
|
|
2274
3695
|
}
|
|
2275
3696
|
}
|
|
@@ -2354,11 +3775,23 @@ function handleSafeWrite(input) {
|
|
|
2354
3775
|
};
|
|
2355
3776
|
return { text: JSON.stringify(result), isError: true };
|
|
2356
3777
|
}
|
|
2357
|
-
const
|
|
2358
|
-
const
|
|
2359
|
-
if (
|
|
3778
|
+
const contentBytes = Buffer.byteLength(content, "utf-8");
|
|
3779
|
+
const { limit: maxBytes, label: fileTypeLabel } = getMaxBytesForPath(filePath);
|
|
3780
|
+
if (contentBytes > maxBytes) {
|
|
3781
|
+
const result = {
|
|
3782
|
+
success: false,
|
|
3783
|
+
error: `Content size ${contentBytes} bytes exceeds ${fileTypeLabel} limit of ${maxBytes} bytes (${maxBytes / 1024} KB)`,
|
|
3784
|
+
callerOtter,
|
|
3785
|
+
attemptedPath: filePath,
|
|
3786
|
+
allowedPaths: []
|
|
3787
|
+
};
|
|
3788
|
+
return { text: JSON.stringify(result), isError: true };
|
|
3789
|
+
}
|
|
3790
|
+
const normalized = (0, import_path6.normalize)(filePath);
|
|
3791
|
+
const fullPath = (0, import_path6.join)(cwd, normalized);
|
|
3792
|
+
if ((0, import_fs6.existsSync)(fullPath)) {
|
|
2360
3793
|
try {
|
|
2361
|
-
const stat = (0,
|
|
3794
|
+
const stat = (0, import_fs6.lstatSync)(fullPath);
|
|
2362
3795
|
if (stat.isSymbolicLink()) {
|
|
2363
3796
|
const result = {
|
|
2364
3797
|
success: false,
|
|
@@ -2383,11 +3816,38 @@ function handleSafeWrite(input) {
|
|
|
2383
3816
|
};
|
|
2384
3817
|
return { text: JSON.stringify(result), isError: true };
|
|
2385
3818
|
}
|
|
3819
|
+
const pageSlug = extractPageSlug(normalized);
|
|
3820
|
+
if (pageSlug) {
|
|
3821
|
+
const ownership = checkPageOwnership(cwd, pageSlug, callerOtter);
|
|
3822
|
+
if (!ownership.allowed) {
|
|
3823
|
+
const result = {
|
|
3824
|
+
success: false,
|
|
3825
|
+
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.`,
|
|
3826
|
+
callerOtter,
|
|
3827
|
+
attemptedPath: filePath,
|
|
3828
|
+
allowedPaths: []
|
|
3829
|
+
};
|
|
3830
|
+
return { text: JSON.stringify(result), isError: true };
|
|
3831
|
+
}
|
|
3832
|
+
}
|
|
2386
3833
|
try {
|
|
2387
3834
|
if (createDirectories) {
|
|
2388
|
-
(0,
|
|
3835
|
+
(0, import_fs6.mkdirSync)((0, import_path6.dirname)(fullPath), { recursive: true });
|
|
3836
|
+
}
|
|
3837
|
+
(0, import_fs6.writeFileSync)(fullPath, content, { encoding: "utf-8" });
|
|
3838
|
+
if (pageSlug) {
|
|
3839
|
+
try {
|
|
3840
|
+
const registry = readPageRegistry(cwd);
|
|
3841
|
+
registry[pageSlug] = {
|
|
3842
|
+
slug: pageSlug,
|
|
3843
|
+
claimedBy: callerOtter,
|
|
3844
|
+
contentTypes: extractContentTypes(content),
|
|
3845
|
+
writtenAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3846
|
+
};
|
|
3847
|
+
writePageRegistry(cwd, registry);
|
|
3848
|
+
} catch {
|
|
3849
|
+
}
|
|
2389
3850
|
}
|
|
2390
|
-
(0, import_fs5.writeFileSync)(fullPath, content, { encoding: "utf-8" });
|
|
2391
3851
|
const result = {
|
|
2392
3852
|
success: true,
|
|
2393
3853
|
path: normalized,
|
|
@@ -2413,10 +3873,12 @@ function registerSafeWriteTools(server2) {
|
|
|
2413
3873
|
"stackwright_pro_safe_write",
|
|
2414
3874
|
DESC,
|
|
2415
3875
|
{
|
|
2416
|
-
callerOtter:
|
|
2417
|
-
filePath:
|
|
2418
|
-
content:
|
|
2419
|
-
createDirectories:
|
|
3876
|
+
callerOtter: import_zod12.z.string().describe('The otter agent name requesting the write, e.g. "stackwright-pro-page-otter"'),
|
|
3877
|
+
filePath: import_zod12.z.string().describe('Relative path from project root, e.g. "pages/dashboard/content.yml"'),
|
|
3878
|
+
content: import_zod12.z.string().describe("File content to write"),
|
|
3879
|
+
createDirectories: boolCoerce(import_zod12.z.boolean().optional().default(true)).describe(
|
|
3880
|
+
"Create parent directories if they don't exist. Default: true"
|
|
3881
|
+
)
|
|
2420
3882
|
},
|
|
2421
3883
|
async ({ callerOtter, filePath, content, createDirectories }) => {
|
|
2422
3884
|
const result = handleSafeWrite({
|
|
@@ -2431,9 +3893,9 @@ function registerSafeWriteTools(server2) {
|
|
|
2431
3893
|
}
|
|
2432
3894
|
|
|
2433
3895
|
// src/tools/auth.ts
|
|
2434
|
-
var
|
|
2435
|
-
var
|
|
2436
|
-
var
|
|
3896
|
+
var import_zod13 = require("zod");
|
|
3897
|
+
var import_fs7 = require("fs");
|
|
3898
|
+
var import_path7 = require("path");
|
|
2437
3899
|
function buildHierarchy(roles) {
|
|
2438
3900
|
const h = {};
|
|
2439
3901
|
for (let i = 0; i < roles.length - 1; i++) {
|
|
@@ -2554,6 +4016,91 @@ ${auditBlock}
|
|
|
2554
4016
|
${routesBlock}
|
|
2555
4017
|
});
|
|
2556
4018
|
|
|
4019
|
+
${configBlock}
|
|
4020
|
+
`;
|
|
4021
|
+
}
|
|
4022
|
+
function generateProxyContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
|
|
4023
|
+
const rbacBlock = ` rbac: {
|
|
4024
|
+
roles: ${JSON.stringify(roles)},
|
|
4025
|
+
defaultRole: '${defaultRole}',
|
|
4026
|
+
hierarchy: ${JSON.stringify(hierarchy, null, 4)},
|
|
4027
|
+
},`;
|
|
4028
|
+
const auditBlock = ` audit: {
|
|
4029
|
+
enabled: ${auditEnabled},
|
|
4030
|
+
retentionDays: ${auditRetentionDays},
|
|
4031
|
+
},`;
|
|
4032
|
+
const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
|
|
4033
|
+
const configBlock = `export const config = {
|
|
4034
|
+
matcher: ${JSON.stringify(protectedRoutes)},
|
|
4035
|
+
};`;
|
|
4036
|
+
if (method === "cac") {
|
|
4037
|
+
const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
|
|
4038
|
+
const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
|
|
4039
|
+
const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
|
|
4040
|
+
const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
|
|
4041
|
+
return `// proxy.ts \u2014 generated by @stackwright-pro/auth (Next.js >=16)
|
|
4042
|
+
// SECURITY REVIEW REQUIRED \u2014 CAC/PKI certificate validation
|
|
4043
|
+
// DoD security officer review required before production deployment.
|
|
4044
|
+
// Verify: CA bundle completeness, EDIPI lookup endpoint, OCSP accessibility.
|
|
4045
|
+
import { createAuthProxy } from '@stackwright-pro/auth-nextjs';
|
|
4046
|
+
|
|
4047
|
+
export const proxy = createAuthProxy({
|
|
4048
|
+
method: 'cac',
|
|
4049
|
+
cac: {
|
|
4050
|
+
caBundle: process.env.CAC_CA_BUNDLE ?? '${caBundle}',
|
|
4051
|
+
edipiLookup: '${edipiLookup}',
|
|
4052
|
+
ocspEndpoint: process.env.CAC_OCSP_ENDPOINT ?? '${ocspEndpoint}',
|
|
4053
|
+
certHeader: '${certHeader}',
|
|
4054
|
+
},
|
|
4055
|
+
${rbacBlock}
|
|
4056
|
+
${auditBlock}
|
|
4057
|
+
${routesBlock}
|
|
4058
|
+
});
|
|
4059
|
+
|
|
4060
|
+
${configBlock}
|
|
4061
|
+
`;
|
|
4062
|
+
}
|
|
4063
|
+
if (method === "oidc") {
|
|
4064
|
+
const scopes2 = params.oidcScopes ?? "openid profile email";
|
|
4065
|
+
const roleClaim = params.oidcRoleClaim ?? "roles";
|
|
4066
|
+
return `// proxy.ts \u2014 generated by @stackwright-pro/auth (Next.js >=16)
|
|
4067
|
+
import { createAuthProxy } from '@stackwright-pro/auth-nextjs';
|
|
4068
|
+
|
|
4069
|
+
export const proxy = createAuthProxy({
|
|
4070
|
+
method: 'oidc',
|
|
4071
|
+
oidc: {
|
|
4072
|
+
discoveryUrl: process.env.OIDC_DISCOVERY_URL!,
|
|
4073
|
+
clientId: process.env.OIDC_CLIENT_ID!,
|
|
4074
|
+
clientSecret: process.env.OIDC_CLIENT_SECRET!,
|
|
4075
|
+
scopes: '${scopes2}',
|
|
4076
|
+
roleClaim: '${roleClaim}',
|
|
4077
|
+
},
|
|
4078
|
+
${rbacBlock}
|
|
4079
|
+
${auditBlock}
|
|
4080
|
+
${routesBlock}
|
|
4081
|
+
});
|
|
4082
|
+
|
|
4083
|
+
${configBlock}
|
|
4084
|
+
`;
|
|
4085
|
+
}
|
|
4086
|
+
const scopes = params.oauth2Scopes ?? "read write";
|
|
4087
|
+
return `// proxy.ts \u2014 generated by @stackwright-pro/auth (Next.js >=16)
|
|
4088
|
+
import { createAuthProxy } from '@stackwright-pro/auth-nextjs';
|
|
4089
|
+
|
|
4090
|
+
export const proxy = createAuthProxy({
|
|
4091
|
+
method: 'oauth2',
|
|
4092
|
+
oauth2: {
|
|
4093
|
+
authorizationUrl: process.env.OAUTH2_AUTH_URL!,
|
|
4094
|
+
tokenUrl: process.env.OAUTH2_TOKEN_URL!,
|
|
4095
|
+
clientId: process.env.OAUTH2_CLIENT_ID!,
|
|
4096
|
+
clientSecret: process.env.OAUTH2_CLIENT_SECRET!,
|
|
4097
|
+
scopes: '${scopes}',
|
|
4098
|
+
},
|
|
4099
|
+
${rbacBlock}
|
|
4100
|
+
${auditBlock}
|
|
4101
|
+
${routesBlock}
|
|
4102
|
+
});
|
|
4103
|
+
|
|
2557
4104
|
${configBlock}
|
|
2558
4105
|
`;
|
|
2559
4106
|
}
|
|
@@ -2583,7 +4130,7 @@ OAUTH2_CLIENT_ID=your-client-id
|
|
|
2583
4130
|
OAUTH2_CLIENT_SECRET=your-client-secret
|
|
2584
4131
|
`;
|
|
2585
4132
|
}
|
|
2586
|
-
function generateYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
|
|
4133
|
+
function generateYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes, useProxy) {
|
|
2587
4134
|
const rbacSection = ` rbac:
|
|
2588
4135
|
roles:
|
|
2589
4136
|
${rolesToYaml(roles, " ")}
|
|
@@ -2606,7 +4153,7 @@ ${routesToYaml(protectedRoutes, " ", defaultRole)}`.replace(/\n\s+,/g, "");
|
|
|
2606
4153
|
const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
|
|
2607
4154
|
return `auth:
|
|
2608
4155
|
method: cac
|
|
2609
|
-
${providerLine} middleware:
|
|
4156
|
+
${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
|
|
2610
4157
|
cac:
|
|
2611
4158
|
caBundle: \${CAC_CA_BUNDLE}
|
|
2612
4159
|
edipiLookup: ${edipiLookup}
|
|
@@ -2623,7 +4170,7 @@ ${auditSection}
|
|
|
2623
4170
|
const roleClaim = params.oidcRoleClaim ?? "roles";
|
|
2624
4171
|
return `auth:
|
|
2625
4172
|
method: oidc
|
|
2626
|
-
${providerLine} middleware:
|
|
4173
|
+
${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
|
|
2627
4174
|
oidc:
|
|
2628
4175
|
discoveryUrl: \${OIDC_DISCOVERY_URL}
|
|
2629
4176
|
clientId: \${OIDC_CLIENT_ID}
|
|
@@ -2639,7 +4186,7 @@ ${auditSection}
|
|
|
2639
4186
|
const scopes = params.oauth2Scopes ?? "read write";
|
|
2640
4187
|
return `auth:
|
|
2641
4188
|
method: oauth2
|
|
2642
|
-
${providerLine} middleware:
|
|
4189
|
+
${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
|
|
2643
4190
|
oauth2:
|
|
2644
4191
|
authorizationUrl: \${OAUTH2_AUTH_URL}
|
|
2645
4192
|
tokenUrl: \${OAUTH2_TOKEN_URL}
|
|
@@ -2652,10 +4199,321 @@ ${routeLines}
|
|
|
2652
4199
|
${auditSection}
|
|
2653
4200
|
`;
|
|
2654
4201
|
}
|
|
4202
|
+
function generateDevOnlyMiddlewareContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
|
|
4203
|
+
const rbacBlock = ` rbac: {
|
|
4204
|
+
roles: ${JSON.stringify(roles)},
|
|
4205
|
+
defaultRole: '${defaultRole}',
|
|
4206
|
+
hierarchy: ${JSON.stringify(hierarchy, null, 4)},
|
|
4207
|
+
},`;
|
|
4208
|
+
const auditBlock = ` audit: {
|
|
4209
|
+
enabled: ${auditEnabled},
|
|
4210
|
+
retentionDays: ${auditRetentionDays},
|
|
4211
|
+
},`;
|
|
4212
|
+
const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
|
|
4213
|
+
const configBlock = `export const config = {
|
|
4214
|
+
matcher: ${JSON.stringify(protectedRoutes)},
|
|
4215
|
+
};`;
|
|
4216
|
+
const devHeader = [
|
|
4217
|
+
"// middleware.ts \u2014 generated by @stackwright-pro/auth-nextjs (dev-only mock)",
|
|
4218
|
+
"// DEV ONLY \u2014 uses mock authentication from lib/mock-auth.ts",
|
|
4219
|
+
"// Do NOT deploy to production.",
|
|
4220
|
+
"import { createProMiddleware } from '@stackwright-pro/auth-nextjs';",
|
|
4221
|
+
"import { mockAuthProvider } from './lib/mock-auth';"
|
|
4222
|
+
].join("\n");
|
|
4223
|
+
if (method === "cac") {
|
|
4224
|
+
const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
|
|
4225
|
+
const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
|
|
4226
|
+
const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
|
|
4227
|
+
const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
|
|
4228
|
+
return `${devHeader}
|
|
4229
|
+
|
|
4230
|
+
export const middleware = createProMiddleware({
|
|
4231
|
+
method: 'cac',
|
|
4232
|
+
cac: {
|
|
4233
|
+
caBundle: '${caBundle}',
|
|
4234
|
+
edipiLookup: '${edipiLookup}',
|
|
4235
|
+
ocspEndpoint: '${ocspEndpoint}',
|
|
4236
|
+
certHeader: '${certHeader}',
|
|
4237
|
+
provider: mockAuthProvider,
|
|
4238
|
+
},
|
|
4239
|
+
${rbacBlock}
|
|
4240
|
+
${auditBlock}
|
|
4241
|
+
${routesBlock}
|
|
4242
|
+
});
|
|
4243
|
+
|
|
4244
|
+
${configBlock}
|
|
4245
|
+
`;
|
|
4246
|
+
}
|
|
4247
|
+
if (method === "oidc") {
|
|
4248
|
+
const scopes2 = params.oidcScopes ?? "openid profile email";
|
|
4249
|
+
const roleClaim = params.oidcRoleClaim ?? "roles";
|
|
4250
|
+
return `${devHeader}
|
|
4251
|
+
|
|
4252
|
+
export const middleware = createProMiddleware({
|
|
4253
|
+
method: 'oidc',
|
|
4254
|
+
oidc: {
|
|
4255
|
+
discoveryUrl: 'https://dev-mock-oidc/.well-known/openid-configuration',
|
|
4256
|
+
clientId: 'dev-mock-client',
|
|
4257
|
+
clientSecret: 'dev-mock-secret',
|
|
4258
|
+
scopes: '${scopes2}',
|
|
4259
|
+
roleClaim: '${roleClaim}',
|
|
4260
|
+
provider: mockAuthProvider,
|
|
4261
|
+
},
|
|
4262
|
+
${rbacBlock}
|
|
4263
|
+
${auditBlock}
|
|
4264
|
+
${routesBlock}
|
|
4265
|
+
});
|
|
4266
|
+
|
|
4267
|
+
${configBlock}
|
|
4268
|
+
`;
|
|
4269
|
+
}
|
|
4270
|
+
const scopes = params.oauth2Scopes ?? "read write";
|
|
4271
|
+
return `${devHeader}
|
|
4272
|
+
|
|
4273
|
+
export const middleware = createProMiddleware({
|
|
4274
|
+
method: 'oauth2',
|
|
4275
|
+
oauth2: {
|
|
4276
|
+
authorizationUrl: 'https://dev-mock-oauth2/authorize',
|
|
4277
|
+
tokenUrl: 'https://dev-mock-oauth2/token',
|
|
4278
|
+
clientId: 'dev-mock-client',
|
|
4279
|
+
clientSecret: 'dev-mock-secret',
|
|
4280
|
+
scopes: '${scopes}',
|
|
4281
|
+
provider: mockAuthProvider,
|
|
4282
|
+
},
|
|
4283
|
+
${rbacBlock}
|
|
4284
|
+
${auditBlock}
|
|
4285
|
+
${routesBlock}
|
|
4286
|
+
});
|
|
4287
|
+
|
|
4288
|
+
${configBlock}
|
|
4289
|
+
`;
|
|
4290
|
+
}
|
|
4291
|
+
function generateDevOnlyProxyContent(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes) {
|
|
4292
|
+
const rbacBlock = ` rbac: {
|
|
4293
|
+
roles: ${JSON.stringify(roles)},
|
|
4294
|
+
defaultRole: '${defaultRole}',
|
|
4295
|
+
hierarchy: ${JSON.stringify(hierarchy, null, 4)},
|
|
4296
|
+
},`;
|
|
4297
|
+
const auditBlock = ` audit: {
|
|
4298
|
+
enabled: ${auditEnabled},
|
|
4299
|
+
retentionDays: ${auditRetentionDays},
|
|
4300
|
+
},`;
|
|
4301
|
+
const routesBlock = ` protectedRoutes: ${JSON.stringify(protectedRoutes)},`;
|
|
4302
|
+
const configBlock = `export const config = {
|
|
4303
|
+
matcher: ${JSON.stringify(protectedRoutes)},
|
|
4304
|
+
};`;
|
|
4305
|
+
const devHeader = [
|
|
4306
|
+
"// proxy.ts -- generated by @stackwright-pro/auth (Next.js >=16, dev-only mock)",
|
|
4307
|
+
"// DEV ONLY -- uses mock authentication from lib/mock-auth.ts",
|
|
4308
|
+
"// Do NOT deploy to production.",
|
|
4309
|
+
"import { createAuthProxy } from '@stackwright-pro/auth-nextjs';",
|
|
4310
|
+
"import { mockAuthProvider } from './lib/mock-auth';"
|
|
4311
|
+
].join("\n");
|
|
4312
|
+
if (method === "cac") {
|
|
4313
|
+
const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
|
|
4314
|
+
const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
|
|
4315
|
+
const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
|
|
4316
|
+
const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
|
|
4317
|
+
return `${devHeader}
|
|
4318
|
+
|
|
4319
|
+
export const proxy = createAuthProxy({
|
|
4320
|
+
method: 'cac',
|
|
4321
|
+
cac: {
|
|
4322
|
+
caBundle: '${caBundle}',
|
|
4323
|
+
edipiLookup: '${edipiLookup}',
|
|
4324
|
+
ocspEndpoint: '${ocspEndpoint}',
|
|
4325
|
+
certHeader: '${certHeader}',
|
|
4326
|
+
provider: mockAuthProvider,
|
|
4327
|
+
},
|
|
4328
|
+
${rbacBlock}
|
|
4329
|
+
${auditBlock}
|
|
4330
|
+
${routesBlock}
|
|
4331
|
+
});
|
|
4332
|
+
|
|
4333
|
+
${configBlock}
|
|
4334
|
+
`;
|
|
4335
|
+
}
|
|
4336
|
+
if (method === "oidc") {
|
|
4337
|
+
const scopes2 = params.oidcScopes ?? "openid profile email";
|
|
4338
|
+
const roleClaim = params.oidcRoleClaim ?? "roles";
|
|
4339
|
+
return `${devHeader}
|
|
4340
|
+
|
|
4341
|
+
export const proxy = createAuthProxy({
|
|
4342
|
+
method: 'oidc',
|
|
4343
|
+
oidc: {
|
|
4344
|
+
discoveryUrl: 'https://dev-mock-oidc/.well-known/openid-configuration',
|
|
4345
|
+
clientId: 'dev-mock-client',
|
|
4346
|
+
clientSecret: 'dev-mock-secret',
|
|
4347
|
+
scopes: '${scopes2}',
|
|
4348
|
+
roleClaim: '${roleClaim}',
|
|
4349
|
+
provider: mockAuthProvider,
|
|
4350
|
+
},
|
|
4351
|
+
${rbacBlock}
|
|
4352
|
+
${auditBlock}
|
|
4353
|
+
${routesBlock}
|
|
4354
|
+
});
|
|
4355
|
+
|
|
4356
|
+
${configBlock}
|
|
4357
|
+
`;
|
|
4358
|
+
}
|
|
4359
|
+
const scopes = params.oauth2Scopes ?? "read write";
|
|
4360
|
+
return `${devHeader}
|
|
4361
|
+
|
|
4362
|
+
export const proxy = createAuthProxy({
|
|
4363
|
+
method: 'oauth2',
|
|
4364
|
+
oauth2: {
|
|
4365
|
+
authorizationUrl: 'https://dev-mock-oauth2/authorize',
|
|
4366
|
+
tokenUrl: 'https://dev-mock-oauth2/token',
|
|
4367
|
+
clientId: 'dev-mock-client',
|
|
4368
|
+
clientSecret: 'dev-mock-secret',
|
|
4369
|
+
scopes: '${scopes}',
|
|
4370
|
+
provider: mockAuthProvider,
|
|
4371
|
+
},
|
|
4372
|
+
${rbacBlock}
|
|
4373
|
+
${auditBlock}
|
|
4374
|
+
${routesBlock}
|
|
4375
|
+
});
|
|
4376
|
+
|
|
4377
|
+
${configBlock}
|
|
4378
|
+
`;
|
|
4379
|
+
}
|
|
4380
|
+
function generateDevOnlyYamlBlock(method, params, roles, defaultRole, hierarchy, auditEnabled, auditRetentionDays, protectedRoutes, useProxy) {
|
|
4381
|
+
const rbacSection = ` rbac:
|
|
4382
|
+
roles:
|
|
4383
|
+
${rolesToYaml(roles, " ")}
|
|
4384
|
+
defaultRole: ${defaultRole}
|
|
4385
|
+
hierarchy:
|
|
4386
|
+
${hierarchyToYaml(hierarchy, " ")}`;
|
|
4387
|
+
const auditSection = ` audit:
|
|
4388
|
+
enabled: ${auditEnabled}
|
|
4389
|
+
retentionDays: ${auditRetentionDays}`;
|
|
4390
|
+
const routeLines = protectedRoutes.map((r) => ` - pattern: ${r}
|
|
4391
|
+
requiredRole: ${defaultRole}`).join("\n");
|
|
4392
|
+
const providerLine = params.provider ? ` provider: ${params.provider}
|
|
4393
|
+
` : "";
|
|
4394
|
+
if (method === "cac") {
|
|
4395
|
+
const caBundle = params.cacCaBundle ?? "./certs/dod-ca-bundle.pem";
|
|
4396
|
+
const edipiLookup = params.cacEdipiLookup ?? "./config/edipi-lookup.json";
|
|
4397
|
+
const ocspEndpoint = params.cacOcspEndpoint ?? "https://ocsp.disa.mil";
|
|
4398
|
+
const certHeader = params.cacCertHeader ?? "X-SSL-Client-Cert";
|
|
4399
|
+
return `auth:
|
|
4400
|
+
method: cac
|
|
4401
|
+
devOnly: true
|
|
4402
|
+
${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
|
|
4403
|
+
cac:
|
|
4404
|
+
caBundle: ${caBundle}
|
|
4405
|
+
edipiLookup: ${edipiLookup}
|
|
4406
|
+
ocspEndpoint: ${ocspEndpoint}
|
|
4407
|
+
certHeader: ${certHeader}
|
|
4408
|
+
${rbacSection}
|
|
4409
|
+
protectedRoutes:
|
|
4410
|
+
${routeLines}
|
|
4411
|
+
${auditSection}
|
|
4412
|
+
`;
|
|
4413
|
+
}
|
|
4414
|
+
if (method === "oidc") {
|
|
4415
|
+
const scopes2 = params.oidcScopes ?? "openid profile email";
|
|
4416
|
+
const roleClaim = params.oidcRoleClaim ?? "roles";
|
|
4417
|
+
return `auth:
|
|
4418
|
+
method: oidc
|
|
4419
|
+
devOnly: true
|
|
4420
|
+
${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
|
|
4421
|
+
oidc:
|
|
4422
|
+
discoveryUrl: https://dev-mock-oidc/.well-known/openid-configuration
|
|
4423
|
+
clientId: dev-mock-client
|
|
4424
|
+
clientSecret: dev-mock-secret
|
|
4425
|
+
scopes: ${scopes2}
|
|
4426
|
+
roleClaim: ${roleClaim}
|
|
4427
|
+
${rbacSection}
|
|
4428
|
+
protectedRoutes:
|
|
4429
|
+
${routeLines}
|
|
4430
|
+
${auditSection}
|
|
4431
|
+
`;
|
|
4432
|
+
}
|
|
4433
|
+
const scopes = params.oauth2Scopes ?? "read write";
|
|
4434
|
+
return `auth:
|
|
4435
|
+
method: oauth2
|
|
4436
|
+
devOnly: true
|
|
4437
|
+
${providerLine} ${useProxy ? "proxy" : "middleware"}: ./${useProxy ? "proxy" : "middleware"}.ts
|
|
4438
|
+
oauth2:
|
|
4439
|
+
authorizationUrl: https://dev-mock-oauth2/authorize
|
|
4440
|
+
tokenUrl: https://dev-mock-oauth2/token
|
|
4441
|
+
clientId: dev-mock-client
|
|
4442
|
+
clientSecret: dev-mock-secret
|
|
4443
|
+
scopes: ${scopes}
|
|
4444
|
+
${rbacSection}
|
|
4445
|
+
protectedRoutes:
|
|
4446
|
+
${routeLines}
|
|
4447
|
+
${auditSection}
|
|
4448
|
+
`;
|
|
4449
|
+
}
|
|
4450
|
+
function deriveDevKey(roleName) {
|
|
4451
|
+
const segment = roleName.split("_")[0];
|
|
4452
|
+
return (segment ?? roleName).toLowerCase();
|
|
4453
|
+
}
|
|
4454
|
+
function generateMockAuthContent(roles, mockUsers) {
|
|
4455
|
+
const entries = [];
|
|
4456
|
+
const scriptLines = [];
|
|
4457
|
+
for (let i = 0; i < roles.length; i++) {
|
|
4458
|
+
const role = roles[i];
|
|
4459
|
+
const devKey = deriveDevKey(role);
|
|
4460
|
+
const persona = mockUsers?.[i];
|
|
4461
|
+
const name = persona?.name ?? `Dev ${role}`;
|
|
4462
|
+
const email = persona?.email ?? `dev-${devKey}@example.mil`;
|
|
4463
|
+
const edipi = String(i + 1).padStart(10, "0");
|
|
4464
|
+
entries.push(` ${devKey}: {
|
|
4465
|
+
id: 'mock-${devKey}-${String(i + 1).padStart(3, "0")}',
|
|
4466
|
+
name: '${name}',
|
|
4467
|
+
email: '${email}',
|
|
4468
|
+
roles: ['${role}'],
|
|
4469
|
+
edipi: '${edipi}',
|
|
4470
|
+
}`);
|
|
4471
|
+
scriptLines.push(` * pnpm dev:${devKey} \u2014 ${name}`);
|
|
4472
|
+
}
|
|
4473
|
+
return `/**
|
|
4474
|
+
* Mock authentication for development mode.
|
|
4475
|
+
*
|
|
4476
|
+
* DEV_ONLY_MODE \u2014 no real auth provider. Select a persona via MOCK_USER env var
|
|
4477
|
+
* or use the convenience scripts in package.json:
|
|
4478
|
+
${scriptLines.join("\n")}
|
|
4479
|
+
*/
|
|
4480
|
+
|
|
4481
|
+
export const MOCK_USERS = {
|
|
4482
|
+
${entries.join(",\n")}
|
|
4483
|
+
} as const;
|
|
4484
|
+
|
|
4485
|
+
export type MockRole = keyof typeof MOCK_USERS;
|
|
4486
|
+
|
|
4487
|
+
export function getMockUser(role?: string) {
|
|
4488
|
+
const key = (role ?? process.env.MOCK_USER) as MockRole | undefined;
|
|
4489
|
+
if (!key) return null;
|
|
4490
|
+
return MOCK_USERS[key] ?? null;
|
|
4491
|
+
}
|
|
4492
|
+
|
|
4493
|
+
export function mockAuthProvider() {
|
|
4494
|
+
return getMockUser();
|
|
4495
|
+
}
|
|
4496
|
+
`;
|
|
4497
|
+
}
|
|
4498
|
+
function updatePackageJsonScripts(existingJson, roles, mockUsers) {
|
|
4499
|
+
const pkg = JSON.parse(existingJson);
|
|
4500
|
+
const scripts = pkg.scripts ?? {};
|
|
4501
|
+
delete scripts["dev:admin"];
|
|
4502
|
+
delete scripts["dev:analyst"];
|
|
4503
|
+
delete scripts["dev:viewer"];
|
|
4504
|
+
for (let i = 0; i < roles.length; i++) {
|
|
4505
|
+
const devKey = deriveDevKey(roles[i]);
|
|
4506
|
+
scripts[`dev:${devKey}`] = `MOCK_USER=${devKey} next dev`;
|
|
4507
|
+
}
|
|
4508
|
+
pkg.scripts = scripts;
|
|
4509
|
+
return JSON.stringify(pkg, null, 2) + "\n";
|
|
4510
|
+
}
|
|
2655
4511
|
async function configureAuthHandler(params, cwd) {
|
|
2656
4512
|
const {
|
|
2657
4513
|
method,
|
|
2658
4514
|
provider,
|
|
4515
|
+
devOnly = false,
|
|
4516
|
+
mockUsers,
|
|
2659
4517
|
rbacRoles = ["SUPER_ADMIN", "ADMIN", "ANALYST"],
|
|
2660
4518
|
auditEnabled = true,
|
|
2661
4519
|
auditRetentionDays = 90,
|
|
@@ -2664,6 +4522,8 @@ async function configureAuthHandler(params, cwd) {
|
|
|
2664
4522
|
const roles = rbacRoles;
|
|
2665
4523
|
const defaultRole = params.rbacDefaultRole ?? roles[roles.length - 1];
|
|
2666
4524
|
const hierarchy = buildHierarchy(roles);
|
|
4525
|
+
const useProxy = (params.nextMajorVersion ?? 0) >= 16;
|
|
4526
|
+
const conventionFile = useProxy ? "proxy.ts" : "middleware.ts";
|
|
2667
4527
|
if (method === "none") {
|
|
2668
4528
|
return {
|
|
2669
4529
|
content: [
|
|
@@ -2685,7 +4545,34 @@ async function configureAuthHandler(params, cwd) {
|
|
|
2685
4545
|
}
|
|
2686
4546
|
const filesWritten = [];
|
|
2687
4547
|
try {
|
|
2688
|
-
const
|
|
4548
|
+
const authFileContent = devOnly ? useProxy ? generateDevOnlyProxyContent(
|
|
4549
|
+
method,
|
|
4550
|
+
params,
|
|
4551
|
+
roles,
|
|
4552
|
+
defaultRole,
|
|
4553
|
+
hierarchy,
|
|
4554
|
+
auditEnabled,
|
|
4555
|
+
auditRetentionDays,
|
|
4556
|
+
protectedRoutes
|
|
4557
|
+
) : generateDevOnlyMiddlewareContent(
|
|
4558
|
+
method,
|
|
4559
|
+
params,
|
|
4560
|
+
roles,
|
|
4561
|
+
defaultRole,
|
|
4562
|
+
hierarchy,
|
|
4563
|
+
auditEnabled,
|
|
4564
|
+
auditRetentionDays,
|
|
4565
|
+
protectedRoutes
|
|
4566
|
+
) : useProxy ? generateProxyContent(
|
|
4567
|
+
method,
|
|
4568
|
+
params,
|
|
4569
|
+
roles,
|
|
4570
|
+
defaultRole,
|
|
4571
|
+
hierarchy,
|
|
4572
|
+
auditEnabled,
|
|
4573
|
+
auditRetentionDays,
|
|
4574
|
+
protectedRoutes
|
|
4575
|
+
) : generateMiddlewareContent(
|
|
2689
4576
|
method,
|
|
2690
4577
|
params,
|
|
2691
4578
|
roles,
|
|
@@ -2695,44 +4582,95 @@ async function configureAuthHandler(params, cwd) {
|
|
|
2695
4582
|
auditRetentionDays,
|
|
2696
4583
|
protectedRoutes
|
|
2697
4584
|
);
|
|
2698
|
-
(0,
|
|
2699
|
-
filesWritten.push(
|
|
4585
|
+
(0, import_fs7.writeFileSync)((0, import_path7.join)(cwd, conventionFile), authFileContent, "utf8");
|
|
4586
|
+
filesWritten.push(conventionFile);
|
|
2700
4587
|
} catch (err) {
|
|
2701
4588
|
const msg = err instanceof Error ? err.message : String(err);
|
|
2702
4589
|
return {
|
|
2703
4590
|
content: [
|
|
2704
4591
|
{
|
|
2705
4592
|
type: "text",
|
|
2706
|
-
text: JSON.stringify({
|
|
4593
|
+
text: JSON.stringify({
|
|
4594
|
+
success: false,
|
|
4595
|
+
error: `Failed writing ${conventionFile}: ${msg}`
|
|
4596
|
+
})
|
|
2707
4597
|
}
|
|
2708
4598
|
],
|
|
2709
4599
|
isError: true
|
|
2710
4600
|
};
|
|
2711
4601
|
}
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
4602
|
+
if (!devOnly) {
|
|
4603
|
+
try {
|
|
4604
|
+
const envBlock = generateEnvBlock(method, params);
|
|
4605
|
+
const envPath = (0, import_path7.join)(cwd, ".env.example");
|
|
4606
|
+
if ((0, import_fs7.existsSync)(envPath)) {
|
|
4607
|
+
const existing = (0, import_fs7.readFileSync)(envPath, "utf8");
|
|
4608
|
+
(0, import_fs7.writeFileSync)(envPath, existing.trimEnd() + "\n\n" + envBlock, "utf8");
|
|
4609
|
+
} else {
|
|
4610
|
+
(0, import_fs7.writeFileSync)(envPath, envBlock, "utf8");
|
|
4611
|
+
}
|
|
4612
|
+
filesWritten.push(".env.example");
|
|
4613
|
+
} catch (err) {
|
|
4614
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
4615
|
+
return {
|
|
4616
|
+
content: [
|
|
4617
|
+
{
|
|
4618
|
+
type: "text",
|
|
4619
|
+
text: JSON.stringify({ success: false, error: `Failed writing .env.example: ${msg}` })
|
|
4620
|
+
}
|
|
4621
|
+
],
|
|
4622
|
+
isError: true
|
|
4623
|
+
};
|
|
4624
|
+
}
|
|
4625
|
+
}
|
|
4626
|
+
if (devOnly) {
|
|
4627
|
+
try {
|
|
4628
|
+
const mockAuthDir = (0, import_path7.join)(cwd, "lib");
|
|
4629
|
+
(0, import_fs7.mkdirSync)(mockAuthDir, { recursive: true });
|
|
4630
|
+
const mockAuthContent = generateMockAuthContent(roles, mockUsers);
|
|
4631
|
+
(0, import_fs7.writeFileSync)((0, import_path7.join)(mockAuthDir, "mock-auth.ts"), mockAuthContent, "utf8");
|
|
4632
|
+
filesWritten.push("lib/mock-auth.ts");
|
|
4633
|
+
} catch (err) {
|
|
4634
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
4635
|
+
return {
|
|
4636
|
+
content: [
|
|
4637
|
+
{
|
|
4638
|
+
type: "text",
|
|
4639
|
+
text: JSON.stringify({
|
|
4640
|
+
success: false,
|
|
4641
|
+
error: `Failed writing lib/mock-auth.ts: ${msg}`
|
|
4642
|
+
})
|
|
4643
|
+
}
|
|
4644
|
+
],
|
|
4645
|
+
isError: true
|
|
4646
|
+
};
|
|
4647
|
+
}
|
|
4648
|
+
try {
|
|
4649
|
+
const pkgPath = (0, import_path7.join)(cwd, "package.json");
|
|
4650
|
+
if ((0, import_fs7.existsSync)(pkgPath)) {
|
|
4651
|
+
const existingPkg = (0, import_fs7.readFileSync)(pkgPath, "utf8");
|
|
4652
|
+
const updatedPkg = updatePackageJsonScripts(existingPkg, roles, mockUsers);
|
|
4653
|
+
(0, import_fs7.writeFileSync)(pkgPath, updatedPkg, "utf8");
|
|
4654
|
+
filesWritten.push("package.json");
|
|
4655
|
+
}
|
|
4656
|
+
} catch (err) {
|
|
4657
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
4658
|
+
return {
|
|
4659
|
+
content: [
|
|
4660
|
+
{
|
|
4661
|
+
type: "text",
|
|
4662
|
+
text: JSON.stringify({
|
|
4663
|
+
success: false,
|
|
4664
|
+
error: `Failed updating package.json: ${msg}`
|
|
4665
|
+
})
|
|
4666
|
+
}
|
|
4667
|
+
],
|
|
4668
|
+
isError: true
|
|
4669
|
+
};
|
|
2720
4670
|
}
|
|
2721
|
-
filesWritten.push(".env.example");
|
|
2722
|
-
} catch (err) {
|
|
2723
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
2724
|
-
return {
|
|
2725
|
-
content: [
|
|
2726
|
-
{
|
|
2727
|
-
type: "text",
|
|
2728
|
-
text: JSON.stringify({ success: false, error: `Failed writing .env.example: ${msg}` })
|
|
2729
|
-
}
|
|
2730
|
-
],
|
|
2731
|
-
isError: true
|
|
2732
|
-
};
|
|
2733
4671
|
}
|
|
2734
4672
|
try {
|
|
2735
|
-
const authYaml =
|
|
4673
|
+
const authYaml = devOnly ? generateDevOnlyYamlBlock(
|
|
2736
4674
|
method,
|
|
2737
4675
|
params,
|
|
2738
4676
|
roles,
|
|
@@ -2740,14 +4678,25 @@ async function configureAuthHandler(params, cwd) {
|
|
|
2740
4678
|
hierarchy,
|
|
2741
4679
|
auditEnabled,
|
|
2742
4680
|
auditRetentionDays,
|
|
2743
|
-
protectedRoutes
|
|
4681
|
+
protectedRoutes,
|
|
4682
|
+
useProxy
|
|
4683
|
+
) : generateYamlBlock(
|
|
4684
|
+
method,
|
|
4685
|
+
params,
|
|
4686
|
+
roles,
|
|
4687
|
+
defaultRole,
|
|
4688
|
+
hierarchy,
|
|
4689
|
+
auditEnabled,
|
|
4690
|
+
auditRetentionDays,
|
|
4691
|
+
protectedRoutes,
|
|
4692
|
+
useProxy
|
|
2744
4693
|
);
|
|
2745
|
-
const ymlPath = (0,
|
|
2746
|
-
if (!(0,
|
|
2747
|
-
(0,
|
|
4694
|
+
const ymlPath = (0, import_path7.join)(cwd, "stackwright.yml");
|
|
4695
|
+
if (!(0, import_fs7.existsSync)(ymlPath)) {
|
|
4696
|
+
(0, import_fs7.writeFileSync)(ymlPath, authYaml, "utf8");
|
|
2748
4697
|
} else {
|
|
2749
|
-
const existing = (0,
|
|
2750
|
-
(0,
|
|
4698
|
+
const existing = (0, import_fs7.readFileSync)(ymlPath, "utf8");
|
|
4699
|
+
(0, import_fs7.writeFileSync)(ymlPath, upsertAuthBlock(existing, authYaml), "utf8");
|
|
2751
4700
|
}
|
|
2752
4701
|
filesWritten.push("stackwright.yml");
|
|
2753
4702
|
} catch (err) {
|
|
@@ -2775,7 +4724,23 @@ async function configureAuthHandler(params, cwd) {
|
|
|
2775
4724
|
rbacDefaultRole: defaultRole,
|
|
2776
4725
|
protectedRoutesCount: protectedRoutes.length,
|
|
2777
4726
|
filesWritten,
|
|
2778
|
-
|
|
4727
|
+
convention: useProxy ? "proxy" : "middleware",
|
|
4728
|
+
nextMajorVersion: params.nextMajorVersion ?? null,
|
|
4729
|
+
securityWarning,
|
|
4730
|
+
...devOnly ? {
|
|
4731
|
+
devScripts: {
|
|
4732
|
+
written: filesWritten.includes("package.json"),
|
|
4733
|
+
scripts: filesWritten.includes("package.json") ? Object.fromEntries(
|
|
4734
|
+
roles.map((r) => {
|
|
4735
|
+
const k = deriveDevKey(r);
|
|
4736
|
+
return [`dev:${k}`, `MOCK_USER=${k} next dev`];
|
|
4737
|
+
})
|
|
4738
|
+
) : {},
|
|
4739
|
+
...filesWritten.includes("package.json") ? {} : {
|
|
4740
|
+
warning: "package.json not found \u2014 dev scripts were not written. Run the auth phase again after scaffolding creates package.json."
|
|
4741
|
+
}
|
|
4742
|
+
}
|
|
4743
|
+
} : {}
|
|
2779
4744
|
})
|
|
2780
4745
|
}
|
|
2781
4746
|
]
|
|
@@ -2786,35 +4751,38 @@ function registerAuthTools(server2) {
|
|
|
2786
4751
|
"stackwright_pro_configure_auth",
|
|
2787
4752
|
"Generate authentication middleware and configuration for a Next.js Stackwright application. Writes `middleware.ts` from a secure template, appends/updates the `auth:` section in `stackwright.yml`, and generates `.env.example` with required environment variables. \u26A0\uFE0F For CAC/PKI: generated `middleware.ts` carries a SECURITY REVIEW REQUIRED comment \u2014 certificate chain validation must be verified by a DoD security officer before production deployment. This is the ONLY approved path to generating `middleware.ts`. Never write TypeScript auth files directly.",
|
|
2788
4753
|
{
|
|
2789
|
-
method:
|
|
2790
|
-
provider:
|
|
4754
|
+
method: import_zod13.z.enum(["cac", "oidc", "oauth2", "none"]),
|
|
4755
|
+
provider: import_zod13.z.enum(["azure-ad", "okta", "ping", "cognito", "custom"]).optional(),
|
|
2791
4756
|
// CAC
|
|
2792
|
-
cacCaBundle:
|
|
2793
|
-
cacEdipiLookup:
|
|
2794
|
-
cacOcspEndpoint:
|
|
2795
|
-
cacCertHeader:
|
|
4757
|
+
cacCaBundle: import_zod13.z.string().optional(),
|
|
4758
|
+
cacEdipiLookup: import_zod13.z.string().optional(),
|
|
4759
|
+
cacOcspEndpoint: import_zod13.z.string().optional(),
|
|
4760
|
+
cacCertHeader: import_zod13.z.string().optional(),
|
|
2796
4761
|
// OIDC
|
|
2797
|
-
oidcDiscoveryUrl:
|
|
2798
|
-
oidcClientId:
|
|
2799
|
-
oidcClientSecret:
|
|
2800
|
-
oidcScopes:
|
|
2801
|
-
oidcRoleClaim:
|
|
4762
|
+
oidcDiscoveryUrl: import_zod13.z.string().optional(),
|
|
4763
|
+
oidcClientId: import_zod13.z.string().optional(),
|
|
4764
|
+
oidcClientSecret: import_zod13.z.string().optional(),
|
|
4765
|
+
oidcScopes: import_zod13.z.string().optional(),
|
|
4766
|
+
oidcRoleClaim: import_zod13.z.string().optional(),
|
|
2802
4767
|
// OAuth2
|
|
2803
|
-
oauth2AuthUrl:
|
|
2804
|
-
oauth2TokenUrl:
|
|
2805
|
-
oauth2ClientId:
|
|
2806
|
-
oauth2ClientSecret:
|
|
2807
|
-
oauth2Scopes:
|
|
4768
|
+
oauth2AuthUrl: import_zod13.z.string().optional(),
|
|
4769
|
+
oauth2TokenUrl: import_zod13.z.string().optional(),
|
|
4770
|
+
oauth2ClientId: import_zod13.z.string().optional(),
|
|
4771
|
+
oauth2ClientSecret: import_zod13.z.string().optional(),
|
|
4772
|
+
oauth2Scopes: import_zod13.z.string().optional(),
|
|
2808
4773
|
// RBAC
|
|
2809
|
-
rbacRoles:
|
|
2810
|
-
rbacDefaultRole:
|
|
4774
|
+
rbacRoles: jsonCoerce(import_zod13.z.array(import_zod13.z.string()).optional()),
|
|
4775
|
+
rbacDefaultRole: import_zod13.z.string().optional(),
|
|
2811
4776
|
// Audit
|
|
2812
|
-
auditEnabled:
|
|
2813
|
-
auditRetentionDays:
|
|
4777
|
+
auditEnabled: boolCoerce(import_zod13.z.boolean().optional()),
|
|
4778
|
+
auditRetentionDays: numCoerce(import_zod13.z.number().int().positive().optional()),
|
|
2814
4779
|
// Routes
|
|
2815
|
-
protectedRoutes:
|
|
4780
|
+
protectedRoutes: jsonCoerce(import_zod13.z.array(import_zod13.z.string()).optional()),
|
|
2816
4781
|
// Injection for tests
|
|
2817
|
-
_cwd:
|
|
4782
|
+
_cwd: import_zod13.z.string().optional(),
|
|
4783
|
+
devOnly: boolCoerce(import_zod13.z.boolean().optional()),
|
|
4784
|
+
mockUsers: jsonCoerce(import_zod13.z.array(import_zod13.z.object({ name: import_zod13.z.string(), email: import_zod13.z.string() })).optional()),
|
|
4785
|
+
nextMajorVersion: numCoerce(import_zod13.z.number().int().positive().optional())
|
|
2818
4786
|
},
|
|
2819
4787
|
async (params) => {
|
|
2820
4788
|
const cwd = params._cwd ?? process.cwd();
|
|
@@ -2824,45 +4792,61 @@ function registerAuthTools(server2) {
|
|
|
2824
4792
|
}
|
|
2825
4793
|
|
|
2826
4794
|
// src/integrity.ts
|
|
2827
|
-
var
|
|
2828
|
-
var
|
|
2829
|
-
var
|
|
4795
|
+
var import_crypto4 = require("crypto");
|
|
4796
|
+
var import_fs8 = require("fs");
|
|
4797
|
+
var import_path8 = require("path");
|
|
2830
4798
|
var _checksums = /* @__PURE__ */ new Map([
|
|
2831
4799
|
[
|
|
2832
4800
|
"stackwright-pro-api-otter.json",
|
|
2833
|
-
"
|
|
4801
|
+
"c21f127b9bed477b1d7b66949926e00e1b93de081e792293ebfffc88b70d9424"
|
|
2834
4802
|
],
|
|
2835
4803
|
[
|
|
2836
4804
|
"stackwright-pro-auth-otter.json",
|
|
2837
|
-
"
|
|
4805
|
+
"6d4d4d50f52be84a796c2a43ed997f00b41b42ed8c5f046e1defb2e423933588"
|
|
2838
4806
|
],
|
|
2839
4807
|
[
|
|
2840
4808
|
"stackwright-pro-dashboard-otter.json",
|
|
2841
|
-
"
|
|
4809
|
+
"9c319d311801730e8dc9bc142eebb8fc5a7f48da48fa0b8d8c3b7431652447be"
|
|
2842
4810
|
],
|
|
2843
4811
|
[
|
|
2844
4812
|
"stackwright-pro-data-otter.json",
|
|
2845
|
-
"
|
|
4813
|
+
"4d9369277685a4acc484116920c9622ad8a1838012a493fcfe42a6ae5abe53cf"
|
|
2846
4814
|
],
|
|
2847
4815
|
[
|
|
2848
4816
|
"stackwright-pro-designer-otter.json",
|
|
2849
|
-
"
|
|
4817
|
+
"af09ac8f06385bdbac63e2820daa2ff7d38b8ff1ff383c161f07e3fb9d9359c5"
|
|
4818
|
+
],
|
|
4819
|
+
[
|
|
4820
|
+
"stackwright-pro-domain-expert-otter.json",
|
|
4821
|
+
"41e3a5838f05f6a51ed272860dd2d5b1df1f20bfc847eb8f39be109b89738e99"
|
|
2850
4822
|
],
|
|
2851
4823
|
[
|
|
2852
4824
|
"stackwright-pro-foreman-otter.json",
|
|
2853
|
-
"
|
|
4825
|
+
"e563a99d647fcf95401508f15f10e032fb14e826577bc6bcff5960bf2981d58d"
|
|
4826
|
+
],
|
|
4827
|
+
[
|
|
4828
|
+
"stackwright-pro-geo-otter.json",
|
|
4829
|
+
"ff1191af8108cc70c09afe6a99b008dcb46f71e20f884da1ee424e431868a1b6"
|
|
2854
4830
|
],
|
|
2855
4831
|
[
|
|
2856
4832
|
"stackwright-pro-page-otter.json",
|
|
2857
|
-
"
|
|
4833
|
+
"cdd878857c1d809c60263693ab0c6cbb45087fd9c3eeda5b4628bd7026d2bded"
|
|
4834
|
+
],
|
|
4835
|
+
[
|
|
4836
|
+
"stackwright-pro-polish-otter.json",
|
|
4837
|
+
"e5f88d054dd536646f48e5d47cbd64f825f493100002309b90c912fa69ef279e"
|
|
2858
4838
|
],
|
|
2859
4839
|
[
|
|
2860
4840
|
"stackwright-pro-theme-otter.json",
|
|
2861
|
-
"
|
|
4841
|
+
"532d9ca7db6911a09ce5029a8c74c89360bdf6cb8ede8c2636866b509cbe06f9"
|
|
2862
4842
|
],
|
|
2863
4843
|
[
|
|
2864
4844
|
"stackwright-pro-workflow-otter.json",
|
|
2865
|
-
"
|
|
4845
|
+
"e02c1a5f492dd6b11f68e293d92f5f661dbb22e57570dcf133a9d0ffc7a8be7d"
|
|
4846
|
+
],
|
|
4847
|
+
[
|
|
4848
|
+
"stackwright-services-otter.json",
|
|
4849
|
+
"b8a252d6a2c5090138899925d3ea95bf3339b6e49adc276a1f5f7304b4ae5134"
|
|
2866
4850
|
]
|
|
2867
4851
|
]);
|
|
2868
4852
|
Object.freeze(_checksums);
|
|
@@ -2877,21 +4861,21 @@ for (const [name, digest] of CANONICAL_CHECKSUMS) {
|
|
|
2877
4861
|
}
|
|
2878
4862
|
var MAX_OTTER_BYTES = 1 * 1024 * 1024;
|
|
2879
4863
|
function computeSha256(data) {
|
|
2880
|
-
return (0,
|
|
4864
|
+
return (0, import_crypto4.createHash)("sha256").update(data).digest("hex");
|
|
2881
4865
|
}
|
|
2882
4866
|
function safeEqual(a, b) {
|
|
2883
4867
|
if (a.length !== b.length) return false;
|
|
2884
|
-
return (0,
|
|
4868
|
+
return (0, import_crypto4.timingSafeEqual)(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
|
|
2885
4869
|
}
|
|
2886
4870
|
function verifyOtterFile(filePath) {
|
|
2887
|
-
const filename = (0,
|
|
4871
|
+
const filename = (0, import_path8.basename)(filePath);
|
|
2888
4872
|
const expected = CANONICAL_CHECKSUMS.get(filename);
|
|
2889
4873
|
if (expected === void 0) {
|
|
2890
4874
|
return { verified: false, filename, error: `Unknown otter file: not in canonical set` };
|
|
2891
4875
|
}
|
|
2892
4876
|
let stat;
|
|
2893
4877
|
try {
|
|
2894
|
-
stat = (0,
|
|
4878
|
+
stat = (0, import_fs8.lstatSync)(filePath);
|
|
2895
4879
|
} catch (err) {
|
|
2896
4880
|
const msg = err instanceof Error ? err.message : String(err);
|
|
2897
4881
|
return { verified: false, filename, error: `Cannot stat file: ${msg}` };
|
|
@@ -2909,7 +4893,7 @@ function verifyOtterFile(filePath) {
|
|
|
2909
4893
|
}
|
|
2910
4894
|
let raw;
|
|
2911
4895
|
try {
|
|
2912
|
-
raw = (0,
|
|
4896
|
+
raw = (0, import_fs8.readFileSync)(filePath);
|
|
2913
4897
|
} catch (err) {
|
|
2914
4898
|
const msg = err instanceof Error ? err.message : String(err);
|
|
2915
4899
|
return { verified: false, filename, error: `Cannot read file: ${msg}` };
|
|
@@ -2942,12 +4926,24 @@ function verifyOtterFile(filePath) {
|
|
|
2942
4926
|
return { verified: true, filename };
|
|
2943
4927
|
}
|
|
2944
4928
|
function verifyAllOtters(otterDir) {
|
|
4929
|
+
if (/(?:^|[/\\])\.\.(?:[/\\]|$)/.test(otterDir) || otterDir.includes("..")) {
|
|
4930
|
+
return {
|
|
4931
|
+
verified: [],
|
|
4932
|
+
failed: [
|
|
4933
|
+
{
|
|
4934
|
+
filename: "<directory>",
|
|
4935
|
+
error: `Security: path traversal sequence detected in otter directory parameter`
|
|
4936
|
+
}
|
|
4937
|
+
],
|
|
4938
|
+
unknown: []
|
|
4939
|
+
};
|
|
4940
|
+
}
|
|
2945
4941
|
const verified = [];
|
|
2946
4942
|
const failed = [];
|
|
2947
4943
|
const unknown = [];
|
|
2948
4944
|
let entries;
|
|
2949
4945
|
try {
|
|
2950
|
-
entries = (0,
|
|
4946
|
+
entries = (0, import_fs8.readdirSync)(otterDir);
|
|
2951
4947
|
} catch (err) {
|
|
2952
4948
|
const msg = err instanceof Error ? err.message : String(err);
|
|
2953
4949
|
return {
|
|
@@ -2958,9 +4954,9 @@ function verifyAllOtters(otterDir) {
|
|
|
2958
4954
|
}
|
|
2959
4955
|
const otterFiles = entries.filter((f) => f.endsWith("-otter.json"));
|
|
2960
4956
|
for (const filename of otterFiles) {
|
|
2961
|
-
const filePath = (0,
|
|
4957
|
+
const filePath = (0, import_path8.join)(otterDir, filename);
|
|
2962
4958
|
try {
|
|
2963
|
-
if ((0,
|
|
4959
|
+
if ((0, import_fs8.lstatSync)(filePath).isSymbolicLink()) {
|
|
2964
4960
|
failed.push({ filename, error: "Skipped: symlink" });
|
|
2965
4961
|
continue;
|
|
2966
4962
|
}
|
|
@@ -2986,15 +4982,30 @@ var DEFAULT_SEARCH_PATHS = ["node_modules/@stackwright-pro/otters/src/", "packag
|
|
|
2986
4982
|
function resolveOtterDir() {
|
|
2987
4983
|
const cwd = process.cwd();
|
|
2988
4984
|
for (const relative of DEFAULT_SEARCH_PATHS) {
|
|
2989
|
-
const candidate = (0,
|
|
4985
|
+
const candidate = (0, import_path8.join)(cwd, relative);
|
|
2990
4986
|
try {
|
|
2991
|
-
(0,
|
|
4987
|
+
(0, import_fs8.lstatSync)(candidate);
|
|
2992
4988
|
return candidate;
|
|
2993
4989
|
} catch {
|
|
2994
4990
|
}
|
|
2995
4991
|
}
|
|
2996
4992
|
return null;
|
|
2997
4993
|
}
|
|
4994
|
+
function emitIntegrityAuditEvent(params) {
|
|
4995
|
+
const record = JSON.stringify({
|
|
4996
|
+
level: "AUDIT",
|
|
4997
|
+
event: "INTEGRITY_FAIL",
|
|
4998
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
4999
|
+
source: "stackwright_pro_verify_otter_integrity",
|
|
5000
|
+
otterDir: params.otterDir,
|
|
5001
|
+
failedCount: params.failed.length,
|
|
5002
|
+
unknownCount: params.unknown.length,
|
|
5003
|
+
failures: params.failed,
|
|
5004
|
+
unknown: params.unknown
|
|
5005
|
+
});
|
|
5006
|
+
process.stderr.write(`INTEGRITY_FAIL ${record}
|
|
5007
|
+
`);
|
|
5008
|
+
}
|
|
2998
5009
|
function registerIntegrityTools(server2) {
|
|
2999
5010
|
server2.tool(
|
|
3000
5011
|
"stackwright_pro_verify_otter_integrity",
|
|
@@ -3018,6 +5029,13 @@ function registerIntegrityTools(server2) {
|
|
|
3018
5029
|
}
|
|
3019
5030
|
const result = verifyAllOtters(resolved);
|
|
3020
5031
|
const allGood = result.failed.length === 0 && result.unknown.length === 0;
|
|
5032
|
+
if (!allGood) {
|
|
5033
|
+
emitIntegrityAuditEvent({
|
|
5034
|
+
otterDir: resolved,
|
|
5035
|
+
failed: result.failed,
|
|
5036
|
+
unknown: result.unknown
|
|
5037
|
+
});
|
|
5038
|
+
}
|
|
3021
5039
|
return {
|
|
3022
5040
|
content: [
|
|
3023
5041
|
{
|
|
@@ -3030,7 +5048,10 @@ function registerIntegrityTools(server2) {
|
|
|
3030
5048
|
unknownCount: result.unknown.length,
|
|
3031
5049
|
verified: result.verified,
|
|
3032
5050
|
failed: result.failed,
|
|
3033
|
-
unknown: result.unknown
|
|
5051
|
+
unknown: result.unknown,
|
|
5052
|
+
...allGood ? {} : {
|
|
5053
|
+
error: "INTEGRITY CHECK FAILED: SHA-256 mismatch detected in otter agent definitions. Do not proceed \u2014 otter files may have been tampered with."
|
|
5054
|
+
}
|
|
3034
5055
|
})
|
|
3035
5056
|
}
|
|
3036
5057
|
],
|
|
@@ -3041,14 +5062,14 @@ function registerIntegrityTools(server2) {
|
|
|
3041
5062
|
}
|
|
3042
5063
|
|
|
3043
5064
|
// src/tools/domain.ts
|
|
3044
|
-
var
|
|
3045
|
-
var
|
|
3046
|
-
var
|
|
5065
|
+
var import_zod14 = require("zod");
|
|
5066
|
+
var import_fs9 = require("fs");
|
|
5067
|
+
var import_path9 = require("path");
|
|
3047
5068
|
function handleListCollections(input) {
|
|
3048
5069
|
const cwd = input._cwd ?? process.cwd();
|
|
3049
5070
|
const sources = [
|
|
3050
5071
|
{
|
|
3051
|
-
path: (0,
|
|
5072
|
+
path: (0, import_path9.join)(cwd, ".stackwright", "artifacts", "data-config.json"),
|
|
3052
5073
|
source: "data-config.json",
|
|
3053
5074
|
parse: (raw) => {
|
|
3054
5075
|
const parsed = JSON.parse(raw);
|
|
@@ -3059,15 +5080,15 @@ function handleListCollections(input) {
|
|
|
3059
5080
|
}
|
|
3060
5081
|
},
|
|
3061
5082
|
{
|
|
3062
|
-
path: (0,
|
|
5083
|
+
path: (0, import_path9.join)(cwd, "stackwright.yml"),
|
|
3063
5084
|
source: "stackwright.yml",
|
|
3064
5085
|
parse: extractCollectionsFromYaml
|
|
3065
5086
|
}
|
|
3066
5087
|
];
|
|
3067
5088
|
for (const { path: path3, source, parse } of sources) {
|
|
3068
|
-
if (!(0,
|
|
5089
|
+
if (!(0, import_fs9.existsSync)(path3)) continue;
|
|
3069
5090
|
try {
|
|
3070
|
-
const collections = parse((0,
|
|
5091
|
+
const collections = parse((0, import_fs9.readFileSync)(path3, "utf8"));
|
|
3071
5092
|
return {
|
|
3072
5093
|
text: JSON.stringify({ collections, source, collectionCount: collections.length }),
|
|
3073
5094
|
isError: false
|
|
@@ -3218,8 +5239,8 @@ function handleValidateWorkflow(input) {
|
|
|
3218
5239
|
if (input.workflow && Object.keys(input.workflow).length > 0) {
|
|
3219
5240
|
raw = input.workflow;
|
|
3220
5241
|
} else {
|
|
3221
|
-
const artifactPath = (0,
|
|
3222
|
-
if (!(0,
|
|
5242
|
+
const artifactPath = (0, import_path9.join)(cwd, ".stackwright", "artifacts", "workflow-config.json");
|
|
5243
|
+
if (!(0, import_fs9.existsSync)(artifactPath)) {
|
|
3223
5244
|
return fail([
|
|
3224
5245
|
{
|
|
3225
5246
|
code: "NO_WORKFLOW",
|
|
@@ -3228,7 +5249,7 @@ function handleValidateWorkflow(input) {
|
|
|
3228
5249
|
]);
|
|
3229
5250
|
}
|
|
3230
5251
|
try {
|
|
3231
|
-
raw = JSON.parse((0,
|
|
5252
|
+
raw = JSON.parse((0, import_fs9.readFileSync)(artifactPath, "utf8"));
|
|
3232
5253
|
} catch (err) {
|
|
3233
5254
|
return fail([{ code: "INVALID_JSON", message: `Failed to parse workflow artifact: ${err}` }]);
|
|
3234
5255
|
}
|
|
@@ -3427,7 +5448,7 @@ function registerDomainTools(server2) {
|
|
|
3427
5448
|
"stackwright_pro_resolve_data_strategy",
|
|
3428
5449
|
"Look up the data freshness strategy configuration from the user's answer. Returns mechanism, revalidation seconds, required packages, and the exact MCP tool call to make. Replaces the strategy table in the data-otter prompt.",
|
|
3429
5450
|
{
|
|
3430
|
-
strategy:
|
|
5451
|
+
strategy: import_zod14.z.string().describe(
|
|
3431
5452
|
'The data-1 answer value: "pulse-fast", "isr-fast", "isr-standard", or "isr-slow"'
|
|
3432
5453
|
)
|
|
3433
5454
|
},
|
|
@@ -3437,7 +5458,7 @@ function registerDomainTools(server2) {
|
|
|
3437
5458
|
"stackwright_pro_validate_workflow",
|
|
3438
5459
|
"Validate a workflow definition against the Stackwright workflow schema. Checks step ID uniqueness, transition targets, terminal state existence, and service references. Call this after the workflow otter produces output.",
|
|
3439
5460
|
{
|
|
3440
|
-
workflow:
|
|
5461
|
+
workflow: jsonCoerce(import_zod14.z.record(import_zod14.z.string(), import_zod14.z.unknown()).optional()).describe(
|
|
3441
5462
|
"Parsed workflow object. If omitted, reads from .stackwright/artifacts/workflow-config.json"
|
|
3442
5463
|
)
|
|
3443
5464
|
},
|
|
@@ -3445,18 +5466,524 @@ function registerDomainTools(server2) {
|
|
|
3445
5466
|
);
|
|
3446
5467
|
}
|
|
3447
5468
|
|
|
5469
|
+
// src/tools/type-schemas.ts
|
|
5470
|
+
var import_zod15 = require("zod");
|
|
5471
|
+
function buildTypeSchemaSummary() {
|
|
5472
|
+
return {
|
|
5473
|
+
version: "1.0",
|
|
5474
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5475
|
+
domains: {
|
|
5476
|
+
workflow: {
|
|
5477
|
+
description: "Workflow DSL \u2014 step definitions, auth blocks, field types, conditions",
|
|
5478
|
+
schemas: [
|
|
5479
|
+
"WorkflowFileSchema",
|
|
5480
|
+
"WorkflowDefinitionSchema",
|
|
5481
|
+
"WorkflowStepSchema",
|
|
5482
|
+
"WorkflowStepTypeSchema",
|
|
5483
|
+
"WorkflowFieldSchema",
|
|
5484
|
+
"WorkflowActionSchema",
|
|
5485
|
+
"WorkflowAuthSchema",
|
|
5486
|
+
"WorkflowThemeSchema",
|
|
5487
|
+
"TransitionConditionSchema",
|
|
5488
|
+
"PersistenceSchema"
|
|
5489
|
+
],
|
|
5490
|
+
otter: "stackwright-pro-workflow-otter",
|
|
5491
|
+
artifactKey: "workflowConfig"
|
|
5492
|
+
},
|
|
5493
|
+
auth: {
|
|
5494
|
+
description: "Authentication providers \u2014 PKI/CAC, OIDC, RBAC configuration",
|
|
5495
|
+
schemas: [
|
|
5496
|
+
"authConfigSchema",
|
|
5497
|
+
"pkiConfigSchema",
|
|
5498
|
+
"oidcConfigSchema",
|
|
5499
|
+
"rbacConfigSchema",
|
|
5500
|
+
"componentAuthSchema",
|
|
5501
|
+
"authUserSchema",
|
|
5502
|
+
"authSessionSchema"
|
|
5503
|
+
],
|
|
5504
|
+
otter: "stackwright-pro-auth-otter",
|
|
5505
|
+
artifactKey: "authConfig"
|
|
5506
|
+
},
|
|
5507
|
+
openapi: {
|
|
5508
|
+
description: "OpenAPI spec integration \u2014 collection config, endpoint filters, actions",
|
|
5509
|
+
interfaces: [
|
|
5510
|
+
"OpenAPIConfig",
|
|
5511
|
+
"ActionConfig",
|
|
5512
|
+
"EndpointFilter",
|
|
5513
|
+
"ApprovedSpec",
|
|
5514
|
+
"PrebuildSecurityConfig",
|
|
5515
|
+
"SiteConfig",
|
|
5516
|
+
"ValidationResult"
|
|
5517
|
+
],
|
|
5518
|
+
otter: "stackwright-pro-api-otter",
|
|
5519
|
+
artifactKey: "apiConfig"
|
|
5520
|
+
},
|
|
5521
|
+
pulse: {
|
|
5522
|
+
description: "Real-time data polling \u2014 source-agnostic polling options and states",
|
|
5523
|
+
interfaces: ["PulseOptions", "PulseMeta", "PulseState"],
|
|
5524
|
+
note: "React-bound types (PulseProps, PulseIndicatorProps) remain in @stackwright-pro/pulse"
|
|
5525
|
+
},
|
|
5526
|
+
enterprise: {
|
|
5527
|
+
description: "Enterprise collection access \u2014 multi-tenant provider extension",
|
|
5528
|
+
interfaces: [
|
|
5529
|
+
"EnterpriseCollectionProvider",
|
|
5530
|
+
"CollectionProvider",
|
|
5531
|
+
"CollectionEntry",
|
|
5532
|
+
"CollectionListOptions",
|
|
5533
|
+
"CollectionListResult",
|
|
5534
|
+
"TenantFilter",
|
|
5535
|
+
"Collection"
|
|
5536
|
+
],
|
|
5537
|
+
note: "CollectionProvider, CollectionEntry, CollectionListOptions, and CollectionListResult are re-exported from @stackwright/types (^1.5.0). EnterpriseCollectionProvider, TenantFilter, and Collection are Pro-only extensions."
|
|
5538
|
+
}
|
|
5539
|
+
}
|
|
5540
|
+
};
|
|
5541
|
+
}
|
|
5542
|
+
function registerTypeSchemasTool(server2) {
|
|
5543
|
+
server2.tool(
|
|
5544
|
+
"stackwright_pro_get_type_schemas",
|
|
5545
|
+
"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.",
|
|
5546
|
+
{
|
|
5547
|
+
format: import_zod15.z.enum(["full", "domains-only"]).optional().default("full").describe("full = complete summary with all fields; domains-only = just domain names")
|
|
5548
|
+
},
|
|
5549
|
+
async ({ format }) => {
|
|
5550
|
+
const summary = buildTypeSchemaSummary();
|
|
5551
|
+
const output = format === "domains-only" ? Object.keys(summary.domains) : summary;
|
|
5552
|
+
return {
|
|
5553
|
+
content: [{ type: "text", text: JSON.stringify(output, null, 2) }]
|
|
5554
|
+
};
|
|
5555
|
+
}
|
|
5556
|
+
);
|
|
5557
|
+
}
|
|
5558
|
+
|
|
5559
|
+
// src/tools/scaffold-cleanup.ts
|
|
5560
|
+
var import_fs10 = require("fs");
|
|
5561
|
+
var import_path10 = require("path");
|
|
5562
|
+
var SCAFFOLD_FILES_TO_DELETE = [
|
|
5563
|
+
"content/posts/getting-started.yaml",
|
|
5564
|
+
"content/posts/hello-world.yaml"
|
|
5565
|
+
];
|
|
5566
|
+
var SCAFFOLD_DIRS_TO_PRUNE = [
|
|
5567
|
+
"content/posts"
|
|
5568
|
+
// Don't prune 'content' — user may have other content directories
|
|
5569
|
+
];
|
|
5570
|
+
var NOT_FOUND_PATH = "app/not-found.tsx";
|
|
5571
|
+
var FALLBACK_COLORS = {
|
|
5572
|
+
background: "#ffffff",
|
|
5573
|
+
foreground: "#171717",
|
|
5574
|
+
primary: "#525252",
|
|
5575
|
+
mutedForeground: "#737373"
|
|
5576
|
+
};
|
|
5577
|
+
function readThemeColors(cwd) {
|
|
5578
|
+
const tokenPath = (0, import_path10.join)(cwd, ".stackwright", "artifacts", "theme-tokens.json");
|
|
5579
|
+
if (!(0, import_fs10.existsSync)(tokenPath)) return { ...FALLBACK_COLORS };
|
|
5580
|
+
const stat = (0, import_fs10.lstatSync)(tokenPath);
|
|
5581
|
+
if (stat.isSymbolicLink()) return { ...FALLBACK_COLORS };
|
|
5582
|
+
try {
|
|
5583
|
+
const raw = JSON.parse((0, import_fs10.readFileSync)(tokenPath, "utf-8"));
|
|
5584
|
+
const css = raw?.cssVariables ?? {};
|
|
5585
|
+
const toHsl = (hslValue) => {
|
|
5586
|
+
if (!hslValue || typeof hslValue !== "string") return null;
|
|
5587
|
+
return `hsl(${hslValue})`;
|
|
5588
|
+
};
|
|
5589
|
+
return {
|
|
5590
|
+
background: toHsl(css["--background"]) ?? FALLBACK_COLORS.background,
|
|
5591
|
+
foreground: toHsl(css["--foreground"]) ?? FALLBACK_COLORS.foreground,
|
|
5592
|
+
primary: toHsl(css["--primary"]) ?? FALLBACK_COLORS.primary,
|
|
5593
|
+
mutedForeground: toHsl(css["--muted-foreground"]) ?? FALLBACK_COLORS.mutedForeground
|
|
5594
|
+
};
|
|
5595
|
+
} catch {
|
|
5596
|
+
return { ...FALLBACK_COLORS };
|
|
5597
|
+
}
|
|
5598
|
+
}
|
|
5599
|
+
function generateNotFoundPage(colors) {
|
|
5600
|
+
return `export default function NotFound() {
|
|
5601
|
+
return (
|
|
5602
|
+
<div
|
|
5603
|
+
style={{
|
|
5604
|
+
display: 'flex',
|
|
5605
|
+
flexDirection: 'column',
|
|
5606
|
+
alignItems: 'center',
|
|
5607
|
+
justifyContent: 'center',
|
|
5608
|
+
minHeight: '100vh',
|
|
5609
|
+
backgroundColor: '${colors.background}',
|
|
5610
|
+
color: '${colors.foreground}',
|
|
5611
|
+
fontFamily: 'system-ui, -apple-system, sans-serif',
|
|
5612
|
+
padding: '2rem',
|
|
5613
|
+
textAlign: 'center',
|
|
5614
|
+
}}
|
|
5615
|
+
>
|
|
5616
|
+
<h1 style={{ fontSize: '4rem', fontWeight: 700, margin: 0, color: '${colors.primary}' }}>
|
|
5617
|
+
404
|
|
5618
|
+
</h1>
|
|
5619
|
+
<p style={{ fontSize: '1.25rem', color: '${colors.mutedForeground}', marginTop: '0.5rem' }}>
|
|
5620
|
+
Page not found
|
|
5621
|
+
</p>
|
|
5622
|
+
<a
|
|
5623
|
+
href="/"
|
|
5624
|
+
style={{
|
|
5625
|
+
marginTop: '2rem',
|
|
5626
|
+
padding: '0.75rem 1.5rem',
|
|
5627
|
+
backgroundColor: '${colors.primary}',
|
|
5628
|
+
color: '${colors.background}',
|
|
5629
|
+
borderRadius: '0.5rem',
|
|
5630
|
+
textDecoration: 'none',
|
|
5631
|
+
fontSize: '0.875rem',
|
|
5632
|
+
fontWeight: 500,
|
|
5633
|
+
}}
|
|
5634
|
+
>
|
|
5635
|
+
Go Home
|
|
5636
|
+
</a>
|
|
5637
|
+
</div>
|
|
5638
|
+
);
|
|
5639
|
+
}
|
|
5640
|
+
`;
|
|
5641
|
+
}
|
|
5642
|
+
function isSafePath(fullPath) {
|
|
5643
|
+
if (!(0, import_fs10.existsSync)(fullPath)) return true;
|
|
5644
|
+
const stat = (0, import_fs10.lstatSync)(fullPath);
|
|
5645
|
+
return !stat.isSymbolicLink();
|
|
5646
|
+
}
|
|
5647
|
+
function isDirEmpty(dirPath) {
|
|
5648
|
+
if (!(0, import_fs10.existsSync)(dirPath)) return false;
|
|
5649
|
+
const stat = (0, import_fs10.lstatSync)(dirPath);
|
|
5650
|
+
if (!stat.isDirectory()) return false;
|
|
5651
|
+
return (0, import_fs10.readdirSync)(dirPath).length === 0;
|
|
5652
|
+
}
|
|
5653
|
+
function handleCleanupScaffold(_cwd) {
|
|
5654
|
+
const cwd = _cwd ?? process.cwd();
|
|
5655
|
+
const result = {
|
|
5656
|
+
deleted: [],
|
|
5657
|
+
rewritten: [],
|
|
5658
|
+
skipped: [],
|
|
5659
|
+
errors: [],
|
|
5660
|
+
prunedDirs: []
|
|
5661
|
+
};
|
|
5662
|
+
for (const relPath of SCAFFOLD_FILES_TO_DELETE) {
|
|
5663
|
+
const fullPath = (0, import_path10.join)(cwd, relPath);
|
|
5664
|
+
if (!(0, import_fs10.existsSync)(fullPath)) {
|
|
5665
|
+
result.skipped.push(relPath);
|
|
5666
|
+
continue;
|
|
5667
|
+
}
|
|
5668
|
+
if (!isSafePath(fullPath)) {
|
|
5669
|
+
result.errors.push(`Refusing to delete symlink: ${relPath}`);
|
|
5670
|
+
continue;
|
|
5671
|
+
}
|
|
5672
|
+
try {
|
|
5673
|
+
(0, import_fs10.unlinkSync)(fullPath);
|
|
5674
|
+
result.deleted.push(relPath);
|
|
5675
|
+
} catch (err) {
|
|
5676
|
+
result.errors.push(`Failed to delete ${relPath}: ${String(err)}`);
|
|
5677
|
+
}
|
|
5678
|
+
}
|
|
5679
|
+
for (const relDir of SCAFFOLD_DIRS_TO_PRUNE) {
|
|
5680
|
+
const fullDir = (0, import_path10.join)(cwd, relDir);
|
|
5681
|
+
if (!(0, import_fs10.existsSync)(fullDir)) continue;
|
|
5682
|
+
if (!isSafePath(fullDir)) {
|
|
5683
|
+
result.errors.push(`Refusing to prune symlink directory: ${relDir}`);
|
|
5684
|
+
continue;
|
|
5685
|
+
}
|
|
5686
|
+
if (isDirEmpty(fullDir)) {
|
|
5687
|
+
try {
|
|
5688
|
+
(0, import_fs10.rmdirSync)(fullDir);
|
|
5689
|
+
result.prunedDirs.push(relDir);
|
|
5690
|
+
} catch (err) {
|
|
5691
|
+
result.errors.push(`Failed to prune directory ${relDir}: ${String(err)}`);
|
|
5692
|
+
}
|
|
5693
|
+
}
|
|
5694
|
+
}
|
|
5695
|
+
{
|
|
5696
|
+
const fullPath = (0, import_path10.join)(cwd, NOT_FOUND_PATH);
|
|
5697
|
+
if (!(0, import_fs10.existsSync)(fullPath)) {
|
|
5698
|
+
result.skipped.push(NOT_FOUND_PATH);
|
|
5699
|
+
} else if (!isSafePath(fullPath)) {
|
|
5700
|
+
result.errors.push(`Refusing to rewrite symlink: ${NOT_FOUND_PATH}`);
|
|
5701
|
+
} else {
|
|
5702
|
+
try {
|
|
5703
|
+
const colors = readThemeColors(cwd);
|
|
5704
|
+
const content = generateNotFoundPage(colors);
|
|
5705
|
+
const dir = (0, import_path10.dirname)(fullPath);
|
|
5706
|
+
(0, import_fs10.mkdirSync)(dir, { recursive: true });
|
|
5707
|
+
(0, import_fs10.writeFileSync)(fullPath, content, "utf-8");
|
|
5708
|
+
result.rewritten.push(NOT_FOUND_PATH);
|
|
5709
|
+
} catch (err) {
|
|
5710
|
+
result.errors.push(`Failed to rewrite ${NOT_FOUND_PATH}: ${String(err)}`);
|
|
5711
|
+
}
|
|
5712
|
+
}
|
|
5713
|
+
}
|
|
5714
|
+
return {
|
|
5715
|
+
text: JSON.stringify(result),
|
|
5716
|
+
isError: false
|
|
5717
|
+
};
|
|
5718
|
+
}
|
|
5719
|
+
function registerScaffoldCleanupTools(server2) {
|
|
5720
|
+
const DESC = "Deterministic scaffold remnant cleanup \u2014 removes stale OSS scaffold files after raft run.";
|
|
5721
|
+
server2.tool(
|
|
5722
|
+
"stackwright_pro_cleanup_scaffold",
|
|
5723
|
+
`Remove/rewrite stale scaffold files (blog posts, hardcoded not-found page) after the raft pipeline completes. ${DESC}`,
|
|
5724
|
+
{},
|
|
5725
|
+
async () => {
|
|
5726
|
+
const r = handleCleanupScaffold();
|
|
5727
|
+
return {
|
|
5728
|
+
content: [{ type: "text", text: r.text }],
|
|
5729
|
+
isError: r.isError
|
|
5730
|
+
};
|
|
5731
|
+
}
|
|
5732
|
+
);
|
|
5733
|
+
}
|
|
5734
|
+
|
|
5735
|
+
// src/tools/contrast.ts
|
|
5736
|
+
var import_zod16 = require("zod");
|
|
5737
|
+
function linearizeChannel(c255) {
|
|
5738
|
+
const c = c255 / 255;
|
|
5739
|
+
return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
|
|
5740
|
+
}
|
|
5741
|
+
function relativeLuminance(r, g, b) {
|
|
5742
|
+
return 0.2126 * linearizeChannel(r) + 0.7152 * linearizeChannel(g) + 0.0722 * linearizeChannel(b);
|
|
5743
|
+
}
|
|
5744
|
+
function contrastRatioFromLuminance(l1, l2) {
|
|
5745
|
+
const lighter = Math.max(l1, l2);
|
|
5746
|
+
const darker = Math.min(l1, l2);
|
|
5747
|
+
return (lighter + 0.05) / (darker + 0.05);
|
|
5748
|
+
}
|
|
5749
|
+
function parseHex(hex) {
|
|
5750
|
+
const clean = hex.replace("#", "").trim().toLowerCase();
|
|
5751
|
+
if (clean.length === 3) {
|
|
5752
|
+
const r = parseInt(clean.charAt(0) + clean.charAt(0), 16);
|
|
5753
|
+
const g = parseInt(clean.charAt(1) + clean.charAt(1), 16);
|
|
5754
|
+
const b = parseInt(clean.charAt(2) + clean.charAt(2), 16);
|
|
5755
|
+
if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
|
|
5756
|
+
return [r, g, b];
|
|
5757
|
+
}
|
|
5758
|
+
if (clean.length === 6) {
|
|
5759
|
+
const r = parseInt(clean.slice(0, 2), 16);
|
|
5760
|
+
const g = parseInt(clean.slice(2, 4), 16);
|
|
5761
|
+
const b = parseInt(clean.slice(4, 6), 16);
|
|
5762
|
+
if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
|
|
5763
|
+
return [r, g, b];
|
|
5764
|
+
}
|
|
5765
|
+
return null;
|
|
5766
|
+
}
|
|
5767
|
+
function hslToRgb(h, s, l) {
|
|
5768
|
+
const hn = h / 360;
|
|
5769
|
+
const sn = s / 100;
|
|
5770
|
+
const ln = l / 100;
|
|
5771
|
+
const hue2rgb = (p, q, t) => {
|
|
5772
|
+
let tt = t;
|
|
5773
|
+
if (tt < 0) tt += 1;
|
|
5774
|
+
if (tt > 1) tt -= 1;
|
|
5775
|
+
if (tt < 1 / 6) return p + (q - p) * 6 * tt;
|
|
5776
|
+
if (tt < 1 / 2) return q;
|
|
5777
|
+
if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6;
|
|
5778
|
+
return p;
|
|
5779
|
+
};
|
|
5780
|
+
let r, g, b;
|
|
5781
|
+
if (sn === 0) {
|
|
5782
|
+
r = g = b = ln;
|
|
5783
|
+
} else {
|
|
5784
|
+
const q = ln < 0.5 ? ln * (1 + sn) : ln + sn - ln * sn;
|
|
5785
|
+
const p = 2 * ln - q;
|
|
5786
|
+
r = hue2rgb(p, q, hn + 1 / 3);
|
|
5787
|
+
g = hue2rgb(p, q, hn);
|
|
5788
|
+
b = hue2rgb(p, q, hn - 1 / 3);
|
|
5789
|
+
}
|
|
5790
|
+
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
|
|
5791
|
+
}
|
|
5792
|
+
function parseHsl(hsl) {
|
|
5793
|
+
let str = hsl.replace(/^hsl\s*\(\s*/i, "").replace(/\s*\)$/, "").trim();
|
|
5794
|
+
str = str.replace(/%/g, "");
|
|
5795
|
+
const parts = str.split(/[\s,]+/).filter(Boolean);
|
|
5796
|
+
if (parts.length !== 3) return null;
|
|
5797
|
+
const h = parseFloat(parts[0]);
|
|
5798
|
+
const s = parseFloat(parts[1]);
|
|
5799
|
+
const l = parseFloat(parts[2]);
|
|
5800
|
+
if (isNaN(h) || isNaN(s) || isNaN(l)) return null;
|
|
5801
|
+
return hslToRgb(h, s, l);
|
|
5802
|
+
}
|
|
5803
|
+
function parseColor(color) {
|
|
5804
|
+
const trimmed = color.trim();
|
|
5805
|
+
if (trimmed.startsWith("#")) return parseHex(trimmed);
|
|
5806
|
+
if (/^hsl\s*\(/i.test(trimmed)) return parseHsl(trimmed);
|
|
5807
|
+
if (/^\d[\d.]*[\s,]+\d[\d.]*%?[\s,]+\d[\d.]*%?$/.test(trimmed)) return parseHsl(trimmed);
|
|
5808
|
+
return null;
|
|
5809
|
+
}
|
|
5810
|
+
function rgbToHex(r, g, b) {
|
|
5811
|
+
return "#" + [r, g, b].map(
|
|
5812
|
+
(c) => Math.max(0, Math.min(255, Math.round(c))).toString(16).padStart(2, "0")
|
|
5813
|
+
).join("");
|
|
5814
|
+
}
|
|
5815
|
+
function handleCheckContrast(fg, bg) {
|
|
5816
|
+
const fgRgb = parseColor(fg);
|
|
5817
|
+
const bgRgb = parseColor(bg);
|
|
5818
|
+
if (!fgRgb) throw new Error(`Cannot parse foreground color: "${fg}"`);
|
|
5819
|
+
if (!bgRgb) throw new Error(`Cannot parse background color: "${bg}"`);
|
|
5820
|
+
const fgL = relativeLuminance(...fgRgb);
|
|
5821
|
+
const bgL = relativeLuminance(...bgRgb);
|
|
5822
|
+
const ratio = parseFloat(contrastRatioFromLuminance(fgL, bgL).toFixed(2));
|
|
5823
|
+
return {
|
|
5824
|
+
fgHex: rgbToHex(...fgRgb),
|
|
5825
|
+
bgHex: rgbToHex(...bgRgb),
|
|
5826
|
+
ratio,
|
|
5827
|
+
aa: ratio >= 4.5,
|
|
5828
|
+
aaLarge: ratio >= 3,
|
|
5829
|
+
aaa: ratio >= 7,
|
|
5830
|
+
aaaLarge: ratio >= 4.5
|
|
5831
|
+
};
|
|
5832
|
+
}
|
|
5833
|
+
function handleDeriveAccessiblePalette(seed, targetRatio) {
|
|
5834
|
+
const seedRgb = parseColor(seed);
|
|
5835
|
+
if (!seedRgb) throw new Error(`Cannot parse seed color: "${seed}"`);
|
|
5836
|
+
const seedHex = rgbToHex(...seedRgb);
|
|
5837
|
+
const seedL = relativeLuminance(...seedRgb);
|
|
5838
|
+
const whiteRatio = parseFloat(contrastRatioFromLuminance(1, seedL).toFixed(2));
|
|
5839
|
+
const blackRatio = parseFloat(contrastRatioFromLuminance(0, seedL).toFixed(2));
|
|
5840
|
+
const whiteWorks = whiteRatio >= targetRatio;
|
|
5841
|
+
const blackWorks = blackRatio >= targetRatio;
|
|
5842
|
+
let strategy;
|
|
5843
|
+
let foreground;
|
|
5844
|
+
let ratio;
|
|
5845
|
+
let alternativeForeground;
|
|
5846
|
+
let alternativeRatio;
|
|
5847
|
+
if (blackWorks && whiteWorks) {
|
|
5848
|
+
if (blackRatio >= whiteRatio) {
|
|
5849
|
+
strategy = "black";
|
|
5850
|
+
foreground = "#000000";
|
|
5851
|
+
ratio = blackRatio;
|
|
5852
|
+
alternativeForeground = "#ffffff";
|
|
5853
|
+
alternativeRatio = whiteRatio;
|
|
5854
|
+
} else {
|
|
5855
|
+
strategy = "white";
|
|
5856
|
+
foreground = "#ffffff";
|
|
5857
|
+
ratio = whiteRatio;
|
|
5858
|
+
alternativeForeground = "#000000";
|
|
5859
|
+
alternativeRatio = blackRatio;
|
|
5860
|
+
}
|
|
5861
|
+
} else if (blackWorks) {
|
|
5862
|
+
strategy = "black";
|
|
5863
|
+
foreground = "#000000";
|
|
5864
|
+
ratio = blackRatio;
|
|
5865
|
+
alternativeForeground = "#ffffff";
|
|
5866
|
+
alternativeRatio = whiteRatio;
|
|
5867
|
+
} else if (whiteWorks) {
|
|
5868
|
+
strategy = "white";
|
|
5869
|
+
foreground = "#ffffff";
|
|
5870
|
+
ratio = whiteRatio;
|
|
5871
|
+
alternativeForeground = "#000000";
|
|
5872
|
+
alternativeRatio = blackRatio;
|
|
5873
|
+
} else {
|
|
5874
|
+
strategy = "unachievable";
|
|
5875
|
+
if (blackRatio >= whiteRatio) {
|
|
5876
|
+
foreground = "#000000";
|
|
5877
|
+
ratio = blackRatio;
|
|
5878
|
+
alternativeForeground = "#ffffff";
|
|
5879
|
+
alternativeRatio = whiteRatio;
|
|
5880
|
+
} else {
|
|
5881
|
+
foreground = "#ffffff";
|
|
5882
|
+
ratio = whiteRatio;
|
|
5883
|
+
alternativeForeground = "#000000";
|
|
5884
|
+
alternativeRatio = blackRatio;
|
|
5885
|
+
}
|
|
5886
|
+
}
|
|
5887
|
+
return {
|
|
5888
|
+
seedHex,
|
|
5889
|
+
foreground,
|
|
5890
|
+
ratio,
|
|
5891
|
+
aa: ratio >= 4.5,
|
|
5892
|
+
aaLarge: ratio >= 3,
|
|
5893
|
+
aaa: ratio >= 7,
|
|
5894
|
+
meetsTarget: ratio >= targetRatio,
|
|
5895
|
+
strategy,
|
|
5896
|
+
alternativeForeground,
|
|
5897
|
+
alternativeRatio
|
|
5898
|
+
};
|
|
5899
|
+
}
|
|
5900
|
+
var PASS = "[PASS]";
|
|
5901
|
+
var FAIL = "[FAIL]";
|
|
5902
|
+
var mark = (ok) => ok ? PASS : FAIL;
|
|
5903
|
+
function registerContrastTools(server2) {
|
|
5904
|
+
server2.tool(
|
|
5905
|
+
"stackwright_pro_check_contrast",
|
|
5906
|
+
'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%").',
|
|
5907
|
+
{
|
|
5908
|
+
fg: import_zod16.z.string().describe("Foreground (text) color \u2014 hex or HSL"),
|
|
5909
|
+
bg: import_zod16.z.string().describe("Background color \u2014 hex or HSL")
|
|
5910
|
+
},
|
|
5911
|
+
async ({ fg, bg }) => {
|
|
5912
|
+
let result;
|
|
5913
|
+
try {
|
|
5914
|
+
result = handleCheckContrast(fg, bg);
|
|
5915
|
+
} catch (err) {
|
|
5916
|
+
return {
|
|
5917
|
+
content: [{ type: "text", text: `Error: ${err.message}` }]
|
|
5918
|
+
};
|
|
5919
|
+
}
|
|
5920
|
+
const text = [
|
|
5921
|
+
`WCAG 2.1 Contrast Check`,
|
|
5922
|
+
``,
|
|
5923
|
+
` Foreground : ${result.fgHex}`,
|
|
5924
|
+
` Background : ${result.bgHex}`,
|
|
5925
|
+
` Ratio : ${result.ratio}:1`,
|
|
5926
|
+
``,
|
|
5927
|
+
` ${mark(result.aa)} AA \u2014 normal text (\u22654.5:1)`,
|
|
5928
|
+
` ${mark(result.aaLarge)} AA \u2014 large text (\u22653.0:1)`,
|
|
5929
|
+
` ${mark(result.aaa)} AAA \u2014 normal text (\u22657.0:1)`,
|
|
5930
|
+
` ${mark(result.aaaLarge)} AAA \u2014 large text (\u22654.5:1)`
|
|
5931
|
+
].join("\n");
|
|
5932
|
+
return { content: [{ type: "text", text }] };
|
|
5933
|
+
}
|
|
5934
|
+
);
|
|
5935
|
+
server2.tool(
|
|
5936
|
+
"stackwright_pro_derive_accessible_palette",
|
|
5937
|
+
'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%").',
|
|
5938
|
+
{
|
|
5939
|
+
seed: import_zod16.z.string().describe("Background (seed) color \u2014 hex or HSL"),
|
|
5940
|
+
targetRatio: numCoerce(import_zod16.z.number().default(4.5)).describe(
|
|
5941
|
+
"Minimum required contrast ratio (default 4.5 for WCAG AA)"
|
|
5942
|
+
)
|
|
5943
|
+
},
|
|
5944
|
+
async ({ seed, targetRatio }) => {
|
|
5945
|
+
let result;
|
|
5946
|
+
try {
|
|
5947
|
+
result = handleDeriveAccessiblePalette(seed, targetRatio ?? 4.5);
|
|
5948
|
+
} catch (err) {
|
|
5949
|
+
return {
|
|
5950
|
+
content: [{ type: "text", text: `Error: ${err.message}` }]
|
|
5951
|
+
};
|
|
5952
|
+
}
|
|
5953
|
+
const metLine = result.meetsTarget ? `${PASS} Meets target (${targetRatio}:1)` : `${FAIL} Target (${targetRatio}:1) UNACHIEVABLE with white or black \u2014 best available used`;
|
|
5954
|
+
const altNote = result.alternativeRatio >= (targetRatio ?? 4.5) ? `also passes (${result.alternativeRatio}:1)` : `fails at ${result.alternativeRatio}:1`;
|
|
5955
|
+
const text = [
|
|
5956
|
+
`Accessible Palette Derivation`,
|
|
5957
|
+
``,
|
|
5958
|
+
` Background (seed) : ${result.seedHex}`,
|
|
5959
|
+
` Foreground : ${result.foreground} (${result.strategy})`,
|
|
5960
|
+
` Contrast ratio : ${result.ratio}:1`,
|
|
5961
|
+
` ${metLine}`,
|
|
5962
|
+
``,
|
|
5963
|
+
` ${mark(result.aa)} AA \u2014 normal text (\u22654.5:1)`,
|
|
5964
|
+
` ${mark(result.aaLarge)} AA \u2014 large text (\u22653.0:1)`,
|
|
5965
|
+
` ${mark(result.aaa)} AAA \u2014 normal text (\u22657.0:1)`,
|
|
5966
|
+
``,
|
|
5967
|
+
` Alternative (${result.alternativeForeground}): ${altNote}`
|
|
5968
|
+
].join("\n");
|
|
5969
|
+
return { content: [{ type: "text", text }] };
|
|
5970
|
+
}
|
|
5971
|
+
);
|
|
5972
|
+
}
|
|
5973
|
+
|
|
3448
5974
|
// package.json
|
|
3449
5975
|
var package_default = {
|
|
3450
5976
|
dependencies: {
|
|
5977
|
+
"@stackwright-pro/types": "workspace:*",
|
|
3451
5978
|
"@modelcontextprotocol/sdk": "^1.10.0",
|
|
3452
5979
|
"@stackwright-pro/cli-data-explorer": "workspace:*",
|
|
3453
|
-
zod: "^4.3
|
|
5980
|
+
zod: "^4.4.3"
|
|
3454
5981
|
},
|
|
3455
5982
|
devDependencies: {
|
|
3456
|
-
"@types/node": "
|
|
3457
|
-
tsup: "
|
|
3458
|
-
typescript: "
|
|
3459
|
-
vitest: "
|
|
5983
|
+
"@types/node": "catalog:",
|
|
5984
|
+
tsup: "catalog:",
|
|
5985
|
+
typescript: "catalog:",
|
|
5986
|
+
vitest: "catalog:"
|
|
3460
5987
|
},
|
|
3461
5988
|
scripts: {
|
|
3462
5989
|
prepublishOnly: "node scripts/verify-integrity-sync.js",
|
|
@@ -3467,10 +5994,13 @@ var package_default = {
|
|
|
3467
5994
|
"test:coverage": "vitest run --coverage"
|
|
3468
5995
|
},
|
|
3469
5996
|
name: "@stackwright-pro/mcp",
|
|
3470
|
-
version: "0.2.0-alpha.
|
|
5997
|
+
version: "0.2.0-alpha.71",
|
|
3471
5998
|
description: "MCP tools for Stackwright Pro - Data Explorer, Security, ISR, and Dashboard generation",
|
|
3472
|
-
license: "
|
|
5999
|
+
license: "SEE LICENSE IN LICENSE",
|
|
3473
6000
|
main: "./dist/server.js",
|
|
6001
|
+
bin: {
|
|
6002
|
+
"stackwright-pro-mcp": "./dist/server.js"
|
|
6003
|
+
},
|
|
3474
6004
|
module: "./dist/server.mjs",
|
|
3475
6005
|
types: "./dist/server.d.ts",
|
|
3476
6006
|
exports: {
|
|
@@ -3483,6 +6013,11 @@ var package_default = {
|
|
|
3483
6013
|
types: "./dist/integrity.d.ts",
|
|
3484
6014
|
import: "./dist/integrity.mjs",
|
|
3485
6015
|
require: "./dist/integrity.js"
|
|
6016
|
+
},
|
|
6017
|
+
"./type-schemas": {
|
|
6018
|
+
types: "./dist/tools/type-schemas.d.ts",
|
|
6019
|
+
import: "./dist/tools/type-schemas.mjs",
|
|
6020
|
+
require: "./dist/tools/type-schemas.js"
|
|
3486
6021
|
}
|
|
3487
6022
|
},
|
|
3488
6023
|
files: [
|
|
@@ -3510,9 +6045,22 @@ registerPipelineTools(server);
|
|
|
3510
6045
|
registerSafeWriteTools(server);
|
|
3511
6046
|
registerAuthTools(server);
|
|
3512
6047
|
registerIntegrityTools(server);
|
|
6048
|
+
registerArtifactSigningTools(server);
|
|
3513
6049
|
registerDomainTools(server);
|
|
6050
|
+
registerTypeSchemasTool(server);
|
|
6051
|
+
registerScaffoldCleanupTools(server);
|
|
6052
|
+
registerContrastTools(server);
|
|
3514
6053
|
async function main() {
|
|
3515
6054
|
const transport = new import_stdio.StdioServerTransport();
|
|
6055
|
+
try {
|
|
6056
|
+
const servicesRegisterPkg = "@stackwright-services/mcp/register";
|
|
6057
|
+
const mod = await import(servicesRegisterPkg);
|
|
6058
|
+
if (typeof mod.registerServicesTools === "function") {
|
|
6059
|
+
mod.registerServicesTools(server);
|
|
6060
|
+
console.error("Stackwright Services tools registered on pro MCP");
|
|
6061
|
+
}
|
|
6062
|
+
} catch {
|
|
6063
|
+
}
|
|
3516
6064
|
await server.connect(transport);
|
|
3517
6065
|
console.error("Stackwright Pro MCP server running on stdio");
|
|
3518
6066
|
}
|