@duct-sdk/sdk 0.3.12 → 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.
- package/CHANGELOG.md +35 -0
- package/dist/adapters/next/receiver.d.ts +2 -6
- package/dist/adapters/next/receiver.js +20 -66
- package/dist/adapters/remix/receiver.d.ts +2 -6
- package/dist/adapters/remix/receiver.js +16 -33
- package/dist/adapters/sveltekit/receiver.d.ts +2 -6
- package/dist/adapters/sveltekit/receiver.js +13 -40
- package/dist/adapters/vite/receiver.d.ts +2 -4
- package/dist/adapters/vite/receiver.js +13 -30
- package/dist/cli/agents/api-agent.d.ts +3 -1
- package/dist/cli/agents/api-agent.js +22 -11
- package/dist/cli/agents/auth-agent.js +4 -4
- package/dist/cli/agents/pipeline.js +63 -7
- package/dist/cli/agents/route-agent.d.ts +3 -1
- package/dist/cli/agents/route-agent.js +17 -6
- package/dist/cli/detectors/topology.d.ts +1 -1
- package/dist/cli/detectors/topology.js +1 -1
- package/dist/cli/generators/config.js +71 -44
- package/dist/cli/generators/config.test.d.ts +1 -0
- package/dist/cli/generators/config.test.js +219 -0
- package/dist/cli/generators/normalize.d.ts +10 -0
- package/dist/cli/generators/normalize.js +49 -0
- package/dist/cli/generators/receiver.d.ts +2 -1
- package/dist/cli/generators/receiver.js +20 -201
- package/dist/cli/generators/token-route.d.ts +8 -0
- package/dist/cli/generators/token-route.js +235 -0
- package/dist/cli/generators/token-route.test.d.ts +1 -0
- package/dist/cli/generators/token-route.test.js +53 -0
- package/dist/cli/generators/wiring-snippets.d.ts +23 -0
- package/dist/cli/generators/wiring-snippets.js +233 -0
- package/dist/cli/generators/wiring-snippets.test.d.ts +1 -0
- package/dist/cli/generators/wiring-snippets.test.js +66 -0
- package/dist/cli/index.js +41 -1
- package/dist/cli/init.d.ts +1 -7
- package/dist/cli/init.js +100 -53
- package/dist/cli/output-paths.d.ts +10 -0
- package/dist/cli/output-paths.js +60 -0
- package/dist/cli/processors/curl-parser.test.d.ts +1 -0
- package/dist/cli/processors/curl-parser.test.js +24 -0
- package/dist/cli/processors/integration-audit.d.ts +23 -0
- package/dist/cli/processors/integration-audit.js +208 -0
- package/dist/cli/processors/integration-audit.test.d.ts +1 -0
- package/dist/cli/processors/integration-audit.test.js +154 -0
- package/dist/cli/processors/prisma-parser.js +1 -1
- package/dist/cli/processors/verify-discovery.d.ts +33 -0
- package/dist/cli/processors/verify-discovery.js +193 -0
- package/dist/cli/processors/verify-discovery.test.d.ts +1 -0
- package/dist/cli/processors/verify-discovery.test.js +153 -0
- package/dist/cli/processors/zod-extractor.js +1 -1
- package/dist/core/config.d.ts +16 -0
- package/dist/core/config.js +59 -28
- package/dist/core/endpoints.d.ts +2 -0
- package/dist/core/endpoints.js +10 -0
- package/dist/core/receiver.d.ts +33 -0
- package/dist/core/receiver.js +77 -0
- package/dist/server.d.ts +2 -0
- package/dist/server.js +2 -0
- 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
|
|
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
|
|
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.
|
package/dist/core/config.d.ts
CHANGED
|
@@ -569,6 +569,22 @@ export declare const DuctConfigSchema: z.ZodObject<{
|
|
|
569
569
|
intershell_enabled?: boolean | undefined;
|
|
570
570
|
}>;
|
|
571
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
|
+
};
|
|
572
588
|
/**
|
|
573
589
|
* Define and validate a Duct configuration.
|
|
574
590
|
* This is the primary entrypoint for companies configuring their Duct shell.
|
package/dist/core/config.js
CHANGED
|
@@ -172,6 +172,60 @@ export const DuctConfigSchema = z.object({
|
|
|
172
172
|
registry_visibility: z.enum(['public', 'private']).optional().default('private'),
|
|
173
173
|
intershell_enabled: z.boolean().optional().default(false),
|
|
174
174
|
});
|
|
175
|
+
function zodIssuesToValidationIssues(errors) {
|
|
176
|
+
return errors.map((e) => ({
|
|
177
|
+
severity: "error",
|
|
178
|
+
area: e.path.length > 0 ? e.path.join(".") : "config",
|
|
179
|
+
issue: e.message,
|
|
180
|
+
fix: e.path.join(".") === "auth.tokenEndpoint"
|
|
181
|
+
? "Set auth.tokenEndpoint to a full URL (e.g. https://app.example.com/api/duct/token) or omit the field"
|
|
182
|
+
: "Correct the field per the Duct config reference",
|
|
183
|
+
}));
|
|
184
|
+
}
|
|
185
|
+
function crossValidateDuctConfig(data) {
|
|
186
|
+
const issues = [];
|
|
187
|
+
const routePaths = new Set(data.routes.map((r) => r.path));
|
|
188
|
+
for (const deeplink of data.deeplinks) {
|
|
189
|
+
const normalizedTarget = deeplink.targetRoute.replace(/\[([^\]]+)\]/g, ":$1");
|
|
190
|
+
const normalizedRoutes = Array.from(routePaths).map((p) => p.replace(/\[([^\]]+)\]/g, ":$1"));
|
|
191
|
+
if (!normalizedRoutes.some((r) => r === normalizedTarget || routePaths.has(deeplink.targetRoute))) {
|
|
192
|
+
issues.push({
|
|
193
|
+
severity: "error",
|
|
194
|
+
area: "deeplinks",
|
|
195
|
+
issue: `Deeplink "${deeplink.id}" targets route "${deeplink.targetRoute}" which is not defined in routes[]`,
|
|
196
|
+
fix: `Add a matching route to routes[] or update deeplink "${deeplink.id}".targetRoute`,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const actionIds = new Set(data.actions.map((a) => a.id));
|
|
201
|
+
if (data.agentPermissions.actionOverrides) {
|
|
202
|
+
for (const actionId of Object.keys(data.agentPermissions.actionOverrides)) {
|
|
203
|
+
if (!actionIds.has(actionId)) {
|
|
204
|
+
issues.push({
|
|
205
|
+
severity: "error",
|
|
206
|
+
area: "agentPermissions",
|
|
207
|
+
issue: `actionOverrides references unknown action ID "${actionId}"`,
|
|
208
|
+
fix: `Remove the override or add action "${actionId}" to actions[]`,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return issues;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Validate a Duct config without throwing — used by `duct init` before writing files.
|
|
217
|
+
*/
|
|
218
|
+
export function validateDuctConfigStrict(config) {
|
|
219
|
+
const result = DuctConfigSchema.safeParse(config);
|
|
220
|
+
if (!result.success) {
|
|
221
|
+
return { ok: false, issues: zodIssuesToValidationIssues(result.error.errors) };
|
|
222
|
+
}
|
|
223
|
+
const crossIssues = crossValidateDuctConfig(result.data);
|
|
224
|
+
if (crossIssues.length > 0) {
|
|
225
|
+
return { ok: false, issues: crossIssues };
|
|
226
|
+
}
|
|
227
|
+
return { ok: true, data: result.data };
|
|
228
|
+
}
|
|
175
229
|
/**
|
|
176
230
|
* Define and validate a Duct configuration.
|
|
177
231
|
* This is the primary entrypoint for companies configuring their Duct shell.
|
|
@@ -204,35 +258,12 @@ export const DuctConfigSchema = z.object({
|
|
|
204
258
|
* ```
|
|
205
259
|
*/
|
|
206
260
|
export function defineDuctConfig(config) {
|
|
207
|
-
const
|
|
208
|
-
if (!
|
|
209
|
-
const formatted =
|
|
210
|
-
.map((
|
|
261
|
+
const validation = validateDuctConfigStrict(config);
|
|
262
|
+
if (!validation.ok) {
|
|
263
|
+
const formatted = validation.issues
|
|
264
|
+
.map((i) => ` • [${i.area}] ${i.issue}`)
|
|
211
265
|
.join("\n");
|
|
212
266
|
throw new Error(`Invalid Duct configuration:\n${formatted}\n\nSee your Duct docs /config reference for details.`);
|
|
213
267
|
}
|
|
214
|
-
|
|
215
|
-
const routePaths = new Set(result.data.routes.map((r) => r.path));
|
|
216
|
-
const deeplinkErrors = [];
|
|
217
|
-
for (const deeplink of result.data.deeplinks) {
|
|
218
|
-
// Normalize dynamic segments for comparison
|
|
219
|
-
const normalizedTarget = deeplink.targetRoute.replace(/\[([^\]]+)\]/g, ":$1");
|
|
220
|
-
const normalizedRoutes = Array.from(routePaths).map((p) => p.replace(/\[([^\]]+)\]/g, ":$1"));
|
|
221
|
-
if (!normalizedRoutes.some((r) => r === normalizedTarget || routePaths.has(deeplink.targetRoute))) {
|
|
222
|
-
deeplinkErrors.push(`Deeplink "${deeplink.id}" targets route "${deeplink.targetRoute}" which is not defined in routes[]`);
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
if (deeplinkErrors.length > 0) {
|
|
226
|
-
throw new Error(`Duct configuration validation errors:\n${deeplinkErrors.map((e) => ` • ${e}`).join("\n")}`);
|
|
227
|
-
}
|
|
228
|
-
// Cross-validate: agent permission actionOverrides must reference valid action IDs
|
|
229
|
-
const actionIds = new Set(result.data.actions.map((a) => a.id));
|
|
230
|
-
if (result.data.agentPermissions.actionOverrides) {
|
|
231
|
-
for (const actionId of Object.keys(result.data.agentPermissions.actionOverrides)) {
|
|
232
|
-
if (!actionIds.has(actionId)) {
|
|
233
|
-
throw new Error(`agentPermissions.actionOverrides references unknown action ID: "${actionId}"`);
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
return result.data;
|
|
268
|
+
return validation.data;
|
|
238
269
|
}
|