@duct-sdk/sdk 0.3.11 → 0.4.0

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.
Files changed (63) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/adapters/next/receiver.d.ts +2 -6
  3. package/dist/adapters/next/receiver.js +20 -66
  4. package/dist/adapters/remix/receiver.d.ts +2 -6
  5. package/dist/adapters/remix/receiver.js +16 -33
  6. package/dist/adapters/sveltekit/receiver.d.ts +2 -6
  7. package/dist/adapters/sveltekit/receiver.js +13 -40
  8. package/dist/adapters/vite/receiver.d.ts +2 -4
  9. package/dist/adapters/vite/receiver.js +13 -30
  10. package/dist/cli/agents/api-agent.d.ts +3 -1
  11. package/dist/cli/agents/api-agent.js +22 -11
  12. package/dist/cli/agents/auth-agent.js +4 -4
  13. package/dist/cli/agents/pipeline.js +63 -7
  14. package/dist/cli/agents/route-agent.d.ts +3 -1
  15. package/dist/cli/agents/route-agent.js +17 -6
  16. package/dist/cli/detectors/topology.d.ts +1 -1
  17. package/dist/cli/detectors/topology.js +1 -1
  18. package/dist/cli/generators/config.js +71 -44
  19. package/dist/cli/generators/config.test.d.ts +1 -0
  20. package/dist/cli/generators/config.test.js +219 -0
  21. package/dist/cli/generators/normalize.d.ts +10 -0
  22. package/dist/cli/generators/normalize.js +49 -0
  23. package/dist/cli/generators/receiver.d.ts +2 -1
  24. package/dist/cli/generators/receiver.js +20 -201
  25. package/dist/cli/generators/token-route.d.ts +8 -0
  26. package/dist/cli/generators/token-route.js +235 -0
  27. package/dist/cli/generators/token-route.test.d.ts +1 -0
  28. package/dist/cli/generators/token-route.test.js +53 -0
  29. package/dist/cli/generators/wiring-snippets.d.ts +23 -0
  30. package/dist/cli/generators/wiring-snippets.js +233 -0
  31. package/dist/cli/generators/wiring-snippets.test.d.ts +1 -0
  32. package/dist/cli/generators/wiring-snippets.test.js +66 -0
  33. package/dist/cli/index.js +41 -1
  34. package/dist/cli/init.d.ts +1 -7
  35. package/dist/cli/init.js +100 -53
  36. package/dist/cli/output-paths.d.ts +10 -0
  37. package/dist/cli/output-paths.js +60 -0
  38. package/dist/cli/processors/curl-parser.test.d.ts +1 -0
  39. package/dist/cli/processors/curl-parser.test.js +24 -0
  40. package/dist/cli/processors/integration-audit.d.ts +23 -0
  41. package/dist/cli/processors/integration-audit.js +208 -0
  42. package/dist/cli/processors/integration-audit.test.d.ts +1 -0
  43. package/dist/cli/processors/integration-audit.test.js +154 -0
  44. package/dist/cli/processors/prisma-parser.js +1 -1
  45. package/dist/cli/processors/verify-discovery.d.ts +33 -0
  46. package/dist/cli/processors/verify-discovery.js +193 -0
  47. package/dist/cli/processors/verify-discovery.test.d.ts +1 -0
  48. package/dist/cli/processors/verify-discovery.test.js +153 -0
  49. package/dist/cli/processors/zod-extractor.js +1 -1
  50. package/dist/core/config.d.ts +59 -0
  51. package/dist/core/config.js +66 -28
  52. package/dist/core/endpoints.d.ts +2 -0
  53. package/dist/core/endpoints.js +10 -0
  54. package/dist/core/limits.d.ts +1 -1
  55. package/dist/core/limits.js +1 -1
  56. package/dist/core/page-resolve.d.ts +49 -0
  57. package/dist/core/page-resolve.js +87 -0
  58. package/dist/core/receiver.d.ts +33 -0
  59. package/dist/core/receiver.js +77 -0
  60. package/dist/core/types.d.ts +16 -0
  61. package/dist/server.d.ts +4 -0
  62. package/dist/server.js +4 -0
  63. package/package.json +2 -1
@@ -0,0 +1,154 @@
1
+ import { describe, it, beforeEach, afterEach } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import * as fs from "fs";
4
+ import * as os from "os";
5
+ import * as path from "path";
6
+ import { SandboxFS } from "../fs/sandbox.js";
7
+ import { integrationAuditFailed, runIntegrationAudit, } from "./integration-audit.js";
8
+ function nextAppFramework() {
9
+ return {
10
+ name: "next-app",
11
+ version: "14.0.0",
12
+ hasAppRouter: true,
13
+ hasPagesRouter: false,
14
+ packageManager: "npm",
15
+ srcDir: ".",
16
+ };
17
+ }
18
+ describe("runIntegrationAudit", () => {
19
+ let tempDir = "";
20
+ beforeEach(() => {
21
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "duct-audit-"));
22
+ fs.mkdirSync(path.join(tempDir, "app", "api", "duct", "token"), { recursive: true });
23
+ fs.mkdirSync(path.join(tempDir, "app", "api", "duct", "receive"), { recursive: true });
24
+ fs.writeFileSync(path.join(tempDir, "app", "api", "duct", "token", "route.ts"), `import { generateDuctToken } from "@duct-sdk/sdk/server";\nexport async function POST() { return generateDuctToken({}); }`);
25
+ fs.writeFileSync(path.join(tempDir, "app", "api", "duct", "receive", "route.ts"), `import { verifyDeeplinkToken } from "@duct-sdk/sdk/server";\nexport async function POST() { return verifyDeeplinkToken({}); }`);
26
+ fs.writeFileSync(path.join(tempDir, ".env.local.example"), "DUCT_SECRET_KEY=\nDUCT_SHELL_ID=\n");
27
+ });
28
+ afterEach(() => {
29
+ if (tempDir) {
30
+ fs.rmSync(tempDir, { recursive: true, force: true });
31
+ }
32
+ });
33
+ it("flags missing config and passes when core files exist", async () => {
34
+ const sandbox = new SandboxFS(tempDir);
35
+ const framework = nextAppFramework();
36
+ const config = {
37
+ shellId: "shell_test",
38
+ product: { name: "Test", description: "Test", baseUrl: "https://test.dev" },
39
+ auth: {
40
+ strategy: "nextauth",
41
+ sessionFields: ["id"],
42
+ guestAllowed: false,
43
+ tokenExpirySeconds: 300,
44
+ tokenEndpoint: "/api/duct/token",
45
+ },
46
+ routes: [
47
+ {
48
+ path: "/home",
49
+ name: "Home",
50
+ description: "Home",
51
+ params: [],
52
+ queryParams: [],
53
+ uiStateHint: "list",
54
+ requiresAuth: false,
55
+ deeplinkable: true,
56
+ },
57
+ ],
58
+ actions: [],
59
+ deeplinks: [],
60
+ agentPermissions: { defaultLevel: "none", requireUserConsent: true },
61
+ };
62
+ const outputPaths = {
63
+ configPath: path.join(tempDir, "duct.config.ts"),
64
+ tokenRoutePath: path.join(tempDir, "app", "api", "duct", "token", "route.ts"),
65
+ receiverPath: path.join(tempDir, "app", "api", "duct", "receive", "route.ts"),
66
+ shellComponentPath: path.join(tempDir, "components", "DuctShell.tsx"),
67
+ envTemplatePath: path.join(tempDir, ".env.local.example"),
68
+ };
69
+ const missingConfigIssues = await runIntegrationAudit(sandbox, {
70
+ projectRoot: tempDir,
71
+ config,
72
+ framework,
73
+ outputPaths,
74
+ authDetection: {
75
+ system: "nextauth",
76
+ confidence: 0.9,
77
+ sessionFields: ["id"],
78
+ guestAllowed: false,
79
+ configFiles: [],
80
+ notes: [],
81
+ },
82
+ });
83
+ assert.ok(missingConfigIssues.some((issue) => issue.area === "manifest"));
84
+ fs.writeFileSync(path.join(tempDir, "duct.config.ts"), "export default {};\n");
85
+ const issues = await runIntegrationAudit(sandbox, {
86
+ projectRoot: tempDir,
87
+ config,
88
+ framework,
89
+ outputPaths,
90
+ authDetection: {
91
+ system: "nextauth",
92
+ confidence: 0.9,
93
+ sessionFields: ["id"],
94
+ guestAllowed: false,
95
+ configFiles: [],
96
+ notes: [],
97
+ },
98
+ });
99
+ assert.equal(integrationAuditFailed(issues), false);
100
+ assert.ok(issues.some((issue) => issue.area === "middleware"));
101
+ });
102
+ it("errors when deeplink targets unknown route", async () => {
103
+ const sandbox = new SandboxFS(tempDir);
104
+ fs.writeFileSync(path.join(tempDir, "duct.config.ts"), "export default {};\n");
105
+ const framework = nextAppFramework();
106
+ const config = {
107
+ shellId: "shell_test",
108
+ product: { name: "Test", description: "Test", baseUrl: "https://test.dev" },
109
+ auth: {
110
+ strategy: "nextauth",
111
+ sessionFields: ["id"],
112
+ guestAllowed: false,
113
+ tokenExpirySeconds: 300,
114
+ tokenEndpoint: "/api/duct/token",
115
+ },
116
+ routes: [],
117
+ actions: [],
118
+ deeplinks: [
119
+ {
120
+ id: "open-order",
121
+ name: "Open order",
122
+ description: "Navigate to an order",
123
+ targetRoute: "/orders/:orderId",
124
+ stateFields: [],
125
+ expirySeconds: 300,
126
+ requiresAuth: true,
127
+ },
128
+ ],
129
+ agentPermissions: { defaultLevel: "none", requireUserConsent: true },
130
+ };
131
+ const outputPaths = {
132
+ configPath: path.join(tempDir, "duct.config.ts"),
133
+ tokenRoutePath: path.join(tempDir, "app", "api", "duct", "token", "route.ts"),
134
+ receiverPath: path.join(tempDir, "app", "api", "duct", "receive", "route.ts"),
135
+ shellComponentPath: path.join(tempDir, "components", "DuctShell.tsx"),
136
+ envTemplatePath: path.join(tempDir, ".env.local.example"),
137
+ };
138
+ const issues = await runIntegrationAudit(sandbox, {
139
+ projectRoot: tempDir,
140
+ config,
141
+ framework,
142
+ outputPaths,
143
+ authDetection: {
144
+ system: "nextauth",
145
+ confidence: 0.9,
146
+ sessionFields: ["id"],
147
+ guestAllowed: false,
148
+ configFiles: [],
149
+ notes: [],
150
+ },
151
+ });
152
+ assert.ok(issues.some((issue) => issue.area === "deeplinks" && issue.severity === "error"));
153
+ });
154
+ });
@@ -1,5 +1,5 @@
1
1
  // ============================================================
2
- // @duct/sdk — Prisma Schema Parser (Phase 0.5)
2
+ // @duct/sdk — Prisma Schema Parser
3
3
  // Parses prisma/schema.prisma model definitions (no LLM).
4
4
  // Maps each model to a candidate dataModel entity and injects
5
5
  // field names into the API Agent prompt so it recognises CRUD
@@ -0,0 +1,33 @@
1
+ import type { SandboxFS } from "../fs/sandbox.js";
2
+ import type { ActionManifest, RouteManifest } from "../../core/types.js";
3
+ export interface VerifyDiscoveryOptions {
4
+ /** Drop items with no filesystem match (default: false — downgrade confidence instead). */
5
+ dropUnverified?: boolean;
6
+ /** Confidence subtracted when no match is found (default: 0.35). */
7
+ confidencePenalty?: number;
8
+ /** Minimum confidence to keep when dropUnverified is true (default: 0.5). */
9
+ minConfidenceToKeep?: number;
10
+ }
11
+ export interface VerifyDiscoveryResult {
12
+ routes: RouteManifest[];
13
+ actions: ActionManifest[];
14
+ warnings: string[];
15
+ droppedRoutes: number;
16
+ droppedActions: number;
17
+ downgradedRoutes: number;
18
+ downgradedActions: number;
19
+ }
20
+ /** Normalize LLM evidence to string[]. */
21
+ export declare function normalizeEvidenceArray(evidence: unknown): string[];
22
+ /** Split a manifest path into comparable lowercase segments. */
23
+ export declare function pathToSegments(manifestPath: string): string[];
24
+ /** True when all path segments appear in order within a project file path. */
25
+ export declare function pathMatchesFilePath(segments: string[], filePath: string): boolean;
26
+ /** Build a path literal regex for content search (params become wildcards). */
27
+ export declare function pathToContentPattern(manifestPath: string): RegExp;
28
+ /**
29
+ * Verify discovered routes/actions against handler files in the project.
30
+ */
31
+ export declare function verifyDiscoveryAgainstFilesystem(sandboxFs: SandboxFS, routes: RouteManifest[], actions: ActionManifest[], options?: VerifyDiscoveryOptions): Promise<VerifyDiscoveryResult>;
32
+ /** Reset module cache — for tests only. */
33
+ export declare function resetVerifyDiscoveryCache(): void;
@@ -0,0 +1,193 @@
1
+ // ============================================================
2
+ // @duct/sdk — Ground-truth discovery verification
3
+ // Matches LLM-discovered routes/actions against the filesystem.
4
+ // ============================================================
5
+ const HANDLER_GLOBS = [
6
+ "app/**/route.{ts,tsx,js,jsx}",
7
+ "app/**/page.{ts,tsx,js,jsx}",
8
+ "pages/**/*.{ts,tsx,js,jsx}",
9
+ "src/app/**/route.{ts,tsx,js,jsx}",
10
+ "src/app/**/page.{ts,tsx,js,jsx}",
11
+ "src/routes/**/*.{ts,tsx,js,jsx,py}",
12
+ "src/pages/**/*.{ts,tsx,js,jsx}",
13
+ "routes/**/*.{ts,tsx,js,jsx,py}",
14
+ "server/**/*.{ts,js}",
15
+ "**/+server.{ts,js}",
16
+ ];
17
+ let cachedFileIndexKey = "";
18
+ let cachedFileIndex = [];
19
+ /** Normalize LLM evidence to string[]. */
20
+ export function normalizeEvidenceArray(evidence) {
21
+ if (Array.isArray(evidence)) {
22
+ return evidence.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
23
+ }
24
+ if (typeof evidence === "string" && evidence.trim()) {
25
+ return [evidence.trim()];
26
+ }
27
+ return [];
28
+ }
29
+ /** Split a manifest path into comparable lowercase segments. */
30
+ export function pathToSegments(manifestPath) {
31
+ return manifestPath
32
+ .replace(/\\/g, "/")
33
+ .replace(/^\//, "")
34
+ .split("/")
35
+ .filter(Boolean)
36
+ .map((segment) => segment
37
+ .replace(/^\[(.+)\]$/, "$1")
38
+ .replace(/^\{(.+)\}$/, "$1")
39
+ .replace(/^:(.+)$/, "$1")
40
+ .toLowerCase());
41
+ }
42
+ /** True when all path segments appear in order within a project file path. */
43
+ export function pathMatchesFilePath(segments, filePath) {
44
+ if (segments.length === 0)
45
+ return false;
46
+ const normalizedFile = filePath.replace(/\\/g, "/").toLowerCase();
47
+ let searchFrom = 0;
48
+ for (const segment of segments) {
49
+ const direct = normalizedFile.indexOf(segment, searchFrom);
50
+ const bracket = normalizedFile.indexOf(`[${segment}]`, searchFrom);
51
+ const colon = normalizedFile.indexOf(`:${segment}`, searchFrom);
52
+ const candidates = [direct, bracket, colon].filter((idx) => idx >= 0);
53
+ if (candidates.length === 0) {
54
+ return false;
55
+ }
56
+ searchFrom = Math.min(...candidates) + Math.max(segment.length, 1);
57
+ }
58
+ return true;
59
+ }
60
+ /** Build a path literal regex for content search (params become wildcards). */
61
+ export function pathToContentPattern(manifestPath) {
62
+ const escaped = manifestPath
63
+ .replace(/\\/g, "/")
64
+ .split("/")
65
+ .filter(Boolean)
66
+ .map((segment) => {
67
+ if (/^[:[\{]/.test(segment)) {
68
+ return "[^/\"'`]+";
69
+ }
70
+ return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
71
+ })
72
+ .join("/");
73
+ return new RegExp(`['"\`]/?${escaped}['"\`]`, "i");
74
+ }
75
+ async function loadFileIndex(sandboxFs) {
76
+ const key = sandboxFs.projectRoot;
77
+ if (cachedFileIndexKey === key && cachedFileIndex.length > 0) {
78
+ return cachedFileIndex;
79
+ }
80
+ const files = new Set();
81
+ for (const pattern of HANDLER_GLOBS) {
82
+ const matches = await sandboxFs.findFiles(pattern, { maxFiles: 400 });
83
+ for (const match of matches) {
84
+ files.add(match.replace(/\\/g, "/"));
85
+ }
86
+ }
87
+ cachedFileIndexKey = key;
88
+ cachedFileIndex = [...files];
89
+ return cachedFileIndex;
90
+ }
91
+ async function hasContentMatch(sandboxFs, manifestPath, candidateFiles) {
92
+ const pattern = pathToContentPattern(manifestPath);
93
+ const toScan = candidateFiles.slice(0, 12);
94
+ for (const filePath of toScan) {
95
+ const content = await sandboxFs.readFile(filePath);
96
+ if (content && pattern.test(content)) {
97
+ return true;
98
+ }
99
+ }
100
+ return false;
101
+ }
102
+ async function verifyManifestPath(sandboxFs, manifestPath, fileIndex) {
103
+ const segments = pathToSegments(manifestPath);
104
+ if (segments.length === 0)
105
+ return false;
106
+ const pathMatches = fileIndex.filter((filePath) => pathMatchesFilePath(segments, filePath));
107
+ if (pathMatches.length > 0) {
108
+ return true;
109
+ }
110
+ const prefix = segments.slice(0, Math.min(2, segments.length)).join("/");
111
+ const candidates = fileIndex.filter((filePath) => filePath.toLowerCase().includes(prefix));
112
+ return hasContentMatch(sandboxFs, manifestPath, candidates);
113
+ }
114
+ function applyVerification(item, verified, options, label) {
115
+ if (verified) {
116
+ return { item, dropped: false, downgraded: false };
117
+ }
118
+ const evidence = normalizeEvidenceArray(item.evidence);
119
+ evidence.push("verification: no matching handler file found in project");
120
+ const currentConfidence = typeof item.confidence === "number" ? item.confidence : 0.75;
121
+ const nextConfidence = Math.max(0, currentConfidence - options.confidencePenalty);
122
+ const updated = {
123
+ ...item,
124
+ evidence,
125
+ confidence: nextConfidence,
126
+ };
127
+ const labelValue = "path" in item && typeof item.path === "string"
128
+ ? item.path
129
+ : item.id;
130
+ const warning = `${label} "${labelValue}" could not be verified against the codebase`;
131
+ if (options.dropUnverified && nextConfidence < options.minConfidenceToKeep) {
132
+ return { item: updated, dropped: true, downgraded: false, warning };
133
+ }
134
+ return { item: updated, dropped: false, downgraded: true, warning };
135
+ }
136
+ /**
137
+ * Verify discovered routes/actions against handler files in the project.
138
+ */
139
+ export async function verifyDiscoveryAgainstFilesystem(sandboxFs, routes, actions, options = {}) {
140
+ const resolved = {
141
+ dropUnverified: options.dropUnverified ?? false,
142
+ confidencePenalty: options.confidencePenalty ?? 0.35,
143
+ minConfidenceToKeep: options.minConfidenceToKeep ?? 0.5,
144
+ };
145
+ const fileIndex = await loadFileIndex(sandboxFs);
146
+ const warnings = [];
147
+ const verifiedRoutes = [];
148
+ const verifiedActions = [];
149
+ let droppedRoutes = 0;
150
+ let droppedActions = 0;
151
+ let downgradedRoutes = 0;
152
+ let downgradedActions = 0;
153
+ for (const route of routes) {
154
+ const verified = await verifyManifestPath(sandboxFs, route.path, fileIndex);
155
+ const outcome = applyVerification(route, verified, resolved, "Route");
156
+ if (outcome.warning)
157
+ warnings.push(outcome.warning);
158
+ if (outcome.dropped) {
159
+ droppedRoutes += 1;
160
+ continue;
161
+ }
162
+ if (outcome.downgraded)
163
+ downgradedRoutes += 1;
164
+ verifiedRoutes.push(outcome.item);
165
+ }
166
+ for (const action of actions) {
167
+ const verified = await verifyManifestPath(sandboxFs, action.path, fileIndex);
168
+ const outcome = applyVerification(action, verified, resolved, "Action");
169
+ if (outcome.warning)
170
+ warnings.push(outcome.warning);
171
+ if (outcome.dropped) {
172
+ droppedActions += 1;
173
+ continue;
174
+ }
175
+ if (outcome.downgraded)
176
+ downgradedActions += 1;
177
+ verifiedActions.push(outcome.item);
178
+ }
179
+ return {
180
+ routes: verifiedRoutes,
181
+ actions: verifiedActions,
182
+ warnings,
183
+ droppedRoutes,
184
+ droppedActions,
185
+ downgradedRoutes,
186
+ downgradedActions,
187
+ };
188
+ }
189
+ /** Reset module cache — for tests only. */
190
+ export function resetVerifyDiscoveryCache() {
191
+ cachedFileIndexKey = "";
192
+ cachedFileIndex = [];
193
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,153 @@
1
+ import { describe, it, beforeEach, afterEach } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import * as fs from "fs";
4
+ import * as os from "os";
5
+ import * as path from "path";
6
+ import { SandboxFS } from "../fs/sandbox.js";
7
+ import { normalizeEvidenceArray, pathMatchesFilePath, pathToContentPattern, pathToSegments, resetVerifyDiscoveryCache, verifyDiscoveryAgainstFilesystem, } from "./verify-discovery.js";
8
+ describe("verify-discovery helpers", () => {
9
+ it("normalizes string and array evidence", () => {
10
+ assert.deepEqual(normalizeEvidenceArray("app/api/orders/route.ts:12"), [
11
+ "app/api/orders/route.ts:12",
12
+ ]);
13
+ assert.deepEqual(normalizeEvidenceArray(["a.ts", "", 1]), ["a.ts"]);
14
+ });
15
+ it("matches dynamic route segments in file paths", () => {
16
+ const segments = pathToSegments("/api/orders/:orderId");
17
+ assert.equal(pathMatchesFilePath(segments, "app/api/orders/[orderId]/route.ts"), true);
18
+ assert.equal(pathMatchesFilePath(segments, "pages/about.tsx"), false);
19
+ });
20
+ it("builds content patterns for quoted paths", () => {
21
+ const pattern = pathToContentPattern("/api/orders/:orderId");
22
+ assert.match(`router.get("/api/orders/:orderId"`, pattern);
23
+ });
24
+ });
25
+ describe("verifyDiscoveryAgainstFilesystem", () => {
26
+ let tempDir = "";
27
+ beforeEach(() => {
28
+ resetVerifyDiscoveryCache();
29
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "duct-verify-"));
30
+ fs.mkdirSync(path.join(tempDir, "app", "api", "orders", "[orderId]"), {
31
+ recursive: true,
32
+ });
33
+ fs.writeFileSync(path.join(tempDir, "app", "api", "orders", "[orderId]", "route.ts"), `export async function GET() { return Response.json({ ok: true }); }`);
34
+ fs.mkdirSync(path.join(tempDir, "app", "orders", "[orderId]"), {
35
+ recursive: true,
36
+ });
37
+ fs.writeFileSync(path.join(tempDir, "app", "orders", "[orderId]", "page.tsx"), `export default function OrderPage() { return null; }`);
38
+ });
39
+ afterEach(() => {
40
+ if (tempDir) {
41
+ fs.rmSync(tempDir, { recursive: true, force: true });
42
+ }
43
+ resetVerifyDiscoveryCache();
44
+ });
45
+ it("keeps verified routes/actions and downgrades hallucinated ones", async () => {
46
+ const sandbox = new SandboxFS(tempDir);
47
+ const routes = [
48
+ {
49
+ path: "/orders/:orderId",
50
+ name: "Order Detail",
51
+ description: "Verified order page",
52
+ params: [],
53
+ queryParams: [],
54
+ uiStateHint: "detail",
55
+ requiresAuth: true,
56
+ deeplinkable: true,
57
+ confidence: 0.9,
58
+ evidence: ["app/orders/[orderId]/page.tsx"],
59
+ },
60
+ {
61
+ path: "/made-up",
62
+ name: "Fake",
63
+ description: "Should downgrade",
64
+ params: [],
65
+ queryParams: [],
66
+ uiStateHint: "empty",
67
+ requiresAuth: false,
68
+ deeplinkable: false,
69
+ confidence: 0.9,
70
+ },
71
+ ];
72
+ const actions = [
73
+ {
74
+ id: "get_order",
75
+ name: "Get Order",
76
+ description: "Verified API route",
77
+ method: "GET",
78
+ path: "/api/orders/:orderId",
79
+ agentAccessible: true,
80
+ sideEffects: false,
81
+ sensitivityLevel: "low",
82
+ params: [],
83
+ requiresAuth: true,
84
+ confidence: 0.92,
85
+ },
86
+ {
87
+ id: "get_fake",
88
+ name: "Get Fake",
89
+ description: "Hallucinated endpoint",
90
+ method: "GET",
91
+ path: "/api/does-not-exist",
92
+ agentAccessible: false,
93
+ sideEffects: false,
94
+ sensitivityLevel: "low",
95
+ params: [],
96
+ requiresAuth: false,
97
+ confidence: 0.92,
98
+ },
99
+ {
100
+ id: "get_legacy",
101
+ name: "Legacy",
102
+ description: "Non /api path kept with warning",
103
+ method: "GET",
104
+ path: "/v1/health",
105
+ agentAccessible: true,
106
+ sideEffects: false,
107
+ sensitivityLevel: "none",
108
+ params: [],
109
+ requiresAuth: false,
110
+ confidence: 0.8,
111
+ },
112
+ ];
113
+ fs.mkdirSync(path.join(tempDir, "server"), { recursive: true });
114
+ fs.writeFileSync(path.join(tempDir, "server", "routes.ts"), `app.get("/v1/health", (_req, res) => res.json({ ok: true }));`);
115
+ const result = await verifyDiscoveryAgainstFilesystem(sandbox, routes, actions);
116
+ assert.equal(result.routes.length, 2);
117
+ assert.equal(result.actions.length, 3);
118
+ assert.equal(result.downgradedRoutes, 1);
119
+ assert.equal(result.downgradedActions, 2);
120
+ assert.ok(result.warnings.length >= 2);
121
+ const fakeRoute = result.routes.find((route) => route.path === "/made-up");
122
+ assert.ok(fakeRoute);
123
+ assert.ok((fakeRoute.confidence ?? 1) < 0.9);
124
+ assert.ok(fakeRoute.evidence?.some((entry) => entry.includes("verification:")));
125
+ const legacy = result.actions.find((action) => action.id === "get_legacy");
126
+ assert.ok(legacy);
127
+ });
128
+ it("drops unverified items when dropUnverified is enabled", async () => {
129
+ const sandbox = new SandboxFS(tempDir);
130
+ const actions = [
131
+ {
132
+ id: "get_fake",
133
+ name: "Get Fake",
134
+ description: "Hallucinated endpoint",
135
+ method: "GET",
136
+ path: "/api/does-not-exist",
137
+ agentAccessible: false,
138
+ sideEffects: false,
139
+ sensitivityLevel: "low",
140
+ params: [],
141
+ requiresAuth: false,
142
+ confidence: 0.55,
143
+ },
144
+ ];
145
+ const result = await verifyDiscoveryAgainstFilesystem(sandbox, [], actions, {
146
+ dropUnverified: true,
147
+ confidencePenalty: 0.35,
148
+ minConfidenceToKeep: 0.5,
149
+ });
150
+ assert.equal(result.actions.length, 0);
151
+ assert.equal(result.droppedActions, 1);
152
+ });
153
+ });
@@ -1,5 +1,5 @@
1
1
  // ============================================================
2
- // @duct/sdk — Zod Schema Extractor (Phase 1.5)
2
+ // @duct/sdk — Zod Schema Extractor
3
3
  // Scans API source files for z.object({...}) patterns and
4
4
  // converts them to JSON Schema annotations injected into agent
5
5
  // prompts so agents receive structured param info directly.
@@ -229,6 +229,21 @@ export declare const DuctConfigSchema: z.ZodObject<{
229
229
  expirySeconds: z.ZodDefault<z.ZodNumber>;
230
230
  requiresAuth: z.ZodBoolean;
231
231
  intent: z.ZodOptional<z.ZodString>;
232
+ pageResolver: z.ZodOptional<z.ZodUnion<[z.ZodObject<{
233
+ actionId: z.ZodString;
234
+ }, "strip", z.ZodTypeAny, {
235
+ actionId: string;
236
+ }, {
237
+ actionId: string;
238
+ }>, z.ZodObject<{
239
+ endpoint: z.ZodString;
240
+ }, "strip", z.ZodTypeAny, {
241
+ endpoint: string;
242
+ }, {
243
+ endpoint: string;
244
+ }>]>>;
245
+ allowFetch: z.ZodOptional<z.ZodBoolean>;
246
+ contentSelector: z.ZodOptional<z.ZodString>;
232
247
  }, "strip", z.ZodTypeAny, {
233
248
  id: string;
234
249
  name: string;
@@ -244,6 +259,13 @@ export declare const DuctConfigSchema: z.ZodObject<{
244
259
  }[];
245
260
  expirySeconds: number;
246
261
  intent?: string | undefined;
262
+ pageResolver?: {
263
+ actionId: string;
264
+ } | {
265
+ endpoint: string;
266
+ } | undefined;
267
+ allowFetch?: boolean | undefined;
268
+ contentSelector?: string | undefined;
247
269
  }, {
248
270
  id: string;
249
271
  name: string;
@@ -259,6 +281,13 @@ export declare const DuctConfigSchema: z.ZodObject<{
259
281
  }[] | undefined;
260
282
  expirySeconds?: number | undefined;
261
283
  intent?: string | undefined;
284
+ pageResolver?: {
285
+ actionId: string;
286
+ } | {
287
+ endpoint: string;
288
+ } | undefined;
289
+ allowFetch?: boolean | undefined;
290
+ contentSelector?: string | undefined;
262
291
  }>, "many">>;
263
292
  agentPermissions: z.ZodObject<{
264
293
  defaultLevel: z.ZodEnum<["none", "read", "write", "admin"]>;
@@ -399,6 +428,13 @@ export declare const DuctConfigSchema: z.ZodObject<{
399
428
  }[];
400
429
  expirySeconds: number;
401
430
  intent?: string | undefined;
431
+ pageResolver?: {
432
+ actionId: string;
433
+ } | {
434
+ endpoint: string;
435
+ } | undefined;
436
+ allowFetch?: boolean | undefined;
437
+ contentSelector?: string | undefined;
402
438
  }[];
403
439
  agentPermissions: {
404
440
  defaultLevel: "none" | "read" | "write" | "admin";
@@ -506,6 +542,13 @@ export declare const DuctConfigSchema: z.ZodObject<{
506
542
  }[] | undefined;
507
543
  expirySeconds?: number | undefined;
508
544
  intent?: string | undefined;
545
+ pageResolver?: {
546
+ actionId: string;
547
+ } | {
548
+ endpoint: string;
549
+ } | undefined;
550
+ allowFetch?: boolean | undefined;
551
+ contentSelector?: string | undefined;
509
552
  }[] | undefined;
510
553
  widget?: {
511
554
  primaryColor?: string | undefined;
@@ -526,6 +569,22 @@ export declare const DuctConfigSchema: z.ZodObject<{
526
569
  intershell_enabled?: boolean | undefined;
527
570
  }>;
528
571
  export type ValidatedDuctConfig = z.infer<typeof DuctConfigSchema>;
572
+ export interface DuctConfigValidationIssue {
573
+ severity: "error" | "warning";
574
+ area: string;
575
+ issue: string;
576
+ fix: string;
577
+ }
578
+ /**
579
+ * Validate a Duct config without throwing — used by `duct init` before writing files.
580
+ */
581
+ export declare function validateDuctConfigStrict(config: DuctConfig): {
582
+ ok: true;
583
+ data: ValidatedDuctConfig;
584
+ } | {
585
+ ok: false;
586
+ issues: DuctConfigValidationIssue[];
587
+ };
529
588
  /**
530
589
  * Define and validate a Duct configuration.
531
590
  * This is the primary entrypoint for companies configuring their Duct shell.