@duct-sdk/sdk 0.5.13 → 0.6.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 +385 -344
- package/README.md +418 -264
- package/TOKEN_SPEC.md +243 -243
- package/dist/cli/add.d.ts +7 -0
- package/dist/cli/add.js +152 -0
- package/dist/cli/agent-prompt.d.ts +3 -0
- package/dist/cli/agent-prompt.js +39 -0
- package/dist/cli/api-sources.d.ts +26 -0
- package/dist/cli/api-sources.js +222 -0
- package/dist/cli/cloud.d.ts +133 -0
- package/dist/cli/cloud.js +298 -0
- package/dist/cli/config-loader.d.ts +14 -0
- package/dist/cli/config-loader.js +56 -7
- package/dist/cli/device-login.d.ts +17 -0
- package/dist/cli/device-login.js +75 -0
- package/dist/cli/drift.js +6 -6
- package/dist/cli/generators/any-stack.d.ts +3 -0
- package/dist/cli/generators/any-stack.js +97 -0
- package/dist/cli/generators/config.js +3 -2
- package/dist/cli/generators/receiver.js +7 -7
- package/dist/cli/generators/shell.js +12 -12
- package/dist/cli/generators/token-route.js +245 -245
- package/dist/cli/index.js +396 -611
- package/dist/cli/mcp-core.d.ts +42 -0
- package/dist/cli/mcp-core.js +161 -0
- package/dist/cli/mcp-setup.d.ts +4 -0
- package/dist/cli/mcp-setup.js +360 -0
- package/dist/cli/mcp.d.ts +2 -0
- package/dist/cli/mcp.js +457 -0
- package/dist/cli/migrate-intershell.js +5 -5
- package/dist/cli/policy-defaults.d.ts +37 -0
- package/dist/cli/policy-defaults.js +127 -0
- package/dist/cli/processors/integration-audit.js +2 -2
- package/dist/cli/processors/openapi-parser.d.ts +5 -0
- package/dist/cli/processors/openapi-parser.js +8 -3
- package/dist/cli/project-loader.d.ts +58 -0
- package/dist/cli/project-loader.js +198 -0
- package/dist/cli/project-writer.d.ts +23 -0
- package/dist/cli/project-writer.js +171 -0
- package/dist/cli/push.d.ts +43 -0
- package/dist/cli/push.js +276 -0
- package/dist/cli/safety-checks.d.ts +9 -0
- package/dist/cli/safety-checks.js +29 -0
- package/dist/cli/setup.d.ts +20 -0
- package/dist/cli/setup.js +349 -0
- package/dist/cli/shell-name.d.ts +8 -0
- package/dist/cli/shell-name.js +29 -0
- package/dist/cli/shells.d.ts +22 -0
- package/dist/cli/shells.js +122 -0
- package/dist/cli/split.d.ts +7 -0
- package/dist/cli/split.js +71 -0
- package/dist/cli/sync.d.ts +25 -0
- package/dist/cli/sync.js +120 -0
- package/dist/cli/test-runner.d.ts +21 -0
- package/dist/cli/test-runner.js +281 -0
- package/dist/core/compile.d.ts +43 -0
- package/dist/core/compile.js +510 -0
- package/dist/core/config.d.ts +464 -1
- package/dist/core/config.js +14 -14
- package/dist/core/login-handoff.d.ts +1 -1
- package/dist/core/login-handoff.js +1 -1
- package/dist/core/project.d.ts +1798 -0
- package/dist/core/project.js +278 -0
- package/dist/core/readiness-checks.js +2 -2
- package/dist/core/types.d.ts +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/project.d.ts +4 -0
- package/dist/project.js +8 -0
- package/dist/server.d.ts +2 -0
- package/dist/server.js +1 -0
- package/package.json +94 -95
- package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
- package/dist/adapters/react/page-context-guard.test.js +0 -15
- package/dist/cli/agents/api-agent.d.ts +0 -22
- package/dist/cli/agents/api-agent.js +0 -761
- package/dist/cli/agents/auth-agent.d.ts +0 -7
- package/dist/cli/agents/auth-agent.js +0 -212
- package/dist/cli/agents/deeplink-agent.d.ts +0 -6
- package/dist/cli/agents/deeplink-agent.js +0 -285
- package/dist/cli/agents/llm.d.ts +0 -33
- package/dist/cli/agents/llm.js +0 -309
- package/dist/cli/agents/pipeline.d.ts +0 -72
- package/dist/cli/agents/pipeline.js +0 -421
- package/dist/cli/agents/reviewer-agent.d.ts +0 -13
- package/dist/cli/agents/reviewer-agent.js +0 -450
- package/dist/cli/agents/route-agent.d.ts +0 -17
- package/dist/cli/agents/route-agent.js +0 -383
- package/dist/cli/config-loader.test.d.ts +0 -1
- package/dist/cli/config-loader.test.js +0 -63
- package/dist/cli/detectors/topology.d.ts +0 -46
- package/dist/cli/detectors/topology.js +0 -417
- package/dist/cli/generators/config.test.d.ts +0 -1
- package/dist/cli/generators/config.test.js +0 -222
- package/dist/cli/generators/shell.test.d.ts +0 -1
- package/dist/cli/generators/shell.test.js +0 -73
- package/dist/cli/generators/token-route.test.d.ts +0 -1
- package/dist/cli/generators/token-route.test.js +0 -53
- package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
- package/dist/cli/generators/wiring-snippets.test.js +0 -80
- package/dist/cli/init.d.ts +0 -32
- package/dist/cli/init.js +0 -1336
- package/dist/cli/manifest-diff.test.d.ts +0 -1
- package/dist/cli/manifest-diff.test.js +0 -144
- package/dist/cli/processors/curl-parser.test.d.ts +0 -1
- package/dist/cli/processors/curl-parser.test.js +0 -24
- package/dist/cli/processors/integration-audit.test.d.ts +0 -1
- package/dist/cli/processors/integration-audit.test.js +0 -154
- package/dist/cli/processors/postprocess.d.ts +0 -22
- package/dist/cli/processors/postprocess.js +0 -107
- package/dist/cli/processors/prisma-parser.d.ts +0 -35
- package/dist/cli/processors/prisma-parser.js +0 -117
- package/dist/cli/processors/verify-discovery.d.ts +0 -33
- package/dist/cli/processors/verify-discovery.js +0 -193
- package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
- package/dist/cli/processors/verify-discovery.test.js +0 -153
- package/dist/cli/processors/zod-extractor.d.ts +0 -27
- package/dist/cli/processors/zod-extractor.js +0 -153
- package/dist/cli/prompts/review.d.ts +0 -61
- package/dist/cli/prompts/review.js +0 -410
- package/dist/cli/selectors/express.d.ts +0 -12
- package/dist/cli/selectors/express.js +0 -117
- package/dist/cli/selectors/fastapi.d.ts +0 -12
- package/dist/cli/selectors/fastapi.js +0 -122
- package/dist/cli/selectors/generic.d.ts +0 -10
- package/dist/cli/selectors/generic.js +0 -74
- package/dist/cli/selectors/index.d.ts +0 -37
- package/dist/cli/selectors/index.js +0 -315
- package/dist/cli/selectors/next.d.ts +0 -12
- package/dist/cli/selectors/next.js +0 -130
- package/dist/core/config-policy.test.d.ts +0 -1
- package/dist/core/config-policy.test.js +0 -101
- package/dist/core/config-roundtrip.test.d.ts +0 -1
- package/dist/core/config-roundtrip.test.js +0 -180
- package/dist/core/endpoint-guard.test.d.ts +0 -1
- package/dist/core/endpoint-guard.test.js +0 -57
- package/dist/core/env-diagnostics.test.d.ts +0 -1
- package/dist/core/env-diagnostics.test.js +0 -31
- package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
- package/dist/core/evidence-bundle.conformance.test.js +0 -110
- package/dist/core/evidence-bundle.test.d.ts +0 -1
- package/dist/core/evidence-bundle.test.js +0 -58
- package/dist/core/invariants.test.d.ts +0 -1
- package/dist/core/invariants.test.js +0 -217
- package/dist/core/login-handoff.test.d.ts +0 -1
- package/dist/core/login-handoff.test.js +0 -31
- package/dist/core/profile.test.d.ts +0 -1
- package/dist/core/profile.test.js +0 -95
- package/dist/core/readiness-checks.test.d.ts +0 -1
- package/dist/core/readiness-checks.test.js +0 -106
- package/dist/core/receipt.test.d.ts +0 -1
- package/dist/core/receipt.test.js +0 -75
- package/dist/core/sdk-entrypoint.test.d.ts +0 -1
- package/dist/core/sdk-entrypoint.test.js +0 -8
- package/dist/core/side-effects-review.test.d.ts +0 -1
- package/dist/core/side-effects-review.test.js +0 -28
- package/dist/core/token.conformance.test.d.ts +0 -1
- package/dist/core/token.conformance.test.js +0 -43
- package/dist/core/token.test.d.ts +0 -1
- package/dist/core/token.test.js +0 -66
|
@@ -1,193 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,153 +0,0 @@
|
|
|
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,27 +0,0 @@
|
|
|
1
|
-
export interface ZodField {
|
|
2
|
-
name: string;
|
|
3
|
-
type: "string" | "number" | "boolean" | "object" | "array" | "enum" | "unknown";
|
|
4
|
-
required: boolean;
|
|
5
|
-
enumValues?: string[];
|
|
6
|
-
}
|
|
7
|
-
export interface ExtractedZodSchema {
|
|
8
|
-
name?: string;
|
|
9
|
-
fields: ZodField[];
|
|
10
|
-
}
|
|
11
|
-
export interface FileSchemaHint {
|
|
12
|
-
filePath: string;
|
|
13
|
-
schemas: ExtractedZodSchema[];
|
|
14
|
-
/** Formatted annotation string for injection into agent prompt */
|
|
15
|
-
annotation: string;
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
|
-
* Extract Zod schema hints from a list of API source files.
|
|
19
|
-
* Returns one FileSchemaHint per file that contains at least one z.object declaration.
|
|
20
|
-
*
|
|
21
|
-
* @example
|
|
22
|
-
* ```ts
|
|
23
|
-
* const hints = await extractZodHintsFromFiles(sandboxFs, readList.apiFiles);
|
|
24
|
-
* // Inject hints[n].annotation into the agent prompt alongside each file snippet.
|
|
25
|
-
* ```
|
|
26
|
-
*/
|
|
27
|
-
export declare function extractZodHintsFromFiles(readFile: (path: string) => Promise<string | null>, filePaths: string[]): Promise<Map<string, FileSchemaHint>>;
|
|
@@ -1,153 +0,0 @@
|
|
|
1
|
-
// ============================================================
|
|
2
|
-
// @duct/sdk — Zod Schema Extractor
|
|
3
|
-
// Scans API source files for z.object({...}) patterns and
|
|
4
|
-
// converts them to JSON Schema annotations injected into agent
|
|
5
|
-
// prompts so agents receive structured param info directly.
|
|
6
|
-
// Covers 90%+ of Next.js API routes without LLM guesswork.
|
|
7
|
-
// ============================================================
|
|
8
|
-
// Maps Zod method names to JSON Schema-like types
|
|
9
|
-
const ZOD_TYPE_MAP = {
|
|
10
|
-
string: "string",
|
|
11
|
-
number: "number",
|
|
12
|
-
boolean: "boolean",
|
|
13
|
-
object: "object",
|
|
14
|
-
array: "array",
|
|
15
|
-
enum: "enum",
|
|
16
|
-
literal: "string",
|
|
17
|
-
date: "string",
|
|
18
|
-
bigint: "number",
|
|
19
|
-
coerce: "string",
|
|
20
|
-
};
|
|
21
|
-
/**
|
|
22
|
-
* Parse z.object({...}) declarations from TypeScript source.
|
|
23
|
-
* Uses regex — intentionally naive but covers the common patterns.
|
|
24
|
-
*/
|
|
25
|
-
function parseZodObjects(source) {
|
|
26
|
-
const results = [];
|
|
27
|
-
// Match: [const VarName = ]z.object({ ... })
|
|
28
|
-
// We walk character-by-character to handle nested braces correctly.
|
|
29
|
-
const zodMarker = "z.object(";
|
|
30
|
-
let pos = 0;
|
|
31
|
-
while (pos < source.length) {
|
|
32
|
-
const idx = source.indexOf(zodMarker, pos);
|
|
33
|
-
if (idx === -1)
|
|
34
|
-
break;
|
|
35
|
-
// Try to find the variable name before z.object(
|
|
36
|
-
let varName;
|
|
37
|
-
const prefix = source.slice(Math.max(0, idx - 80), idx);
|
|
38
|
-
const varMatch = /(?:const|let|var)\s+(\w+)\s*(?:=\s*(?:\w+\s*\()?\s*)?$/.exec(prefix);
|
|
39
|
-
if (varMatch)
|
|
40
|
-
varName = varMatch[1];
|
|
41
|
-
// Find the matching closing paren for z.object(
|
|
42
|
-
// The structure is z.object({ fields... })
|
|
43
|
-
const openBrace = source.indexOf("{", idx + zodMarker.length);
|
|
44
|
-
if (openBrace === -1) {
|
|
45
|
-
pos = idx + 1;
|
|
46
|
-
continue;
|
|
47
|
-
}
|
|
48
|
-
let depth = 0;
|
|
49
|
-
let closeBrace = -1;
|
|
50
|
-
for (let i = openBrace; i < source.length; i++) {
|
|
51
|
-
if (source[i] === "{")
|
|
52
|
-
depth++;
|
|
53
|
-
else if (source[i] === "}") {
|
|
54
|
-
depth--;
|
|
55
|
-
if (depth === 0) {
|
|
56
|
-
closeBrace = i;
|
|
57
|
-
break;
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
if (closeBrace === -1) {
|
|
62
|
-
pos = idx + 1;
|
|
63
|
-
continue;
|
|
64
|
-
}
|
|
65
|
-
const fieldsStr = source.slice(openBrace + 1, closeBrace);
|
|
66
|
-
const fields = parseZodFields(fieldsStr);
|
|
67
|
-
if (fields.length > 0) {
|
|
68
|
-
results.push({ name: varName, fields });
|
|
69
|
-
}
|
|
70
|
-
pos = closeBrace + 1;
|
|
71
|
-
}
|
|
72
|
-
return results;
|
|
73
|
-
}
|
|
74
|
-
function parseZodFields(fieldsStr) {
|
|
75
|
-
const fields = [];
|
|
76
|
-
// Match: fieldName: z.type(...) with optional .optional() / .nullable()
|
|
77
|
-
// Handles: name: z.string(), age: z.number().optional(), status: z.enum([...])
|
|
78
|
-
const fieldRe = /(\w+)\s*:\s*z(?:\.coerce)?\.(\w+)\s*(?:\(([^)]*)\))?([^,}\n]*)/g;
|
|
79
|
-
let m;
|
|
80
|
-
while ((m = fieldRe.exec(fieldsStr)) !== null) {
|
|
81
|
-
const fieldName = m[1];
|
|
82
|
-
const zodMethod = m[2].toLowerCase();
|
|
83
|
-
const methodArgs = m[3] ?? "";
|
|
84
|
-
const chainStr = m[4] ?? "";
|
|
85
|
-
// Skip z.object(...) nested calls — the outer schema captures the parent
|
|
86
|
-
if (zodMethod === "object")
|
|
87
|
-
continue;
|
|
88
|
-
const type = ZOD_TYPE_MAP[zodMethod] ?? "unknown";
|
|
89
|
-
const isOptional = chainStr.includes(".optional()") ||
|
|
90
|
-
chainStr.includes(".nullable()") ||
|
|
91
|
-
chainStr.includes(".nullish()");
|
|
92
|
-
const field = { name: fieldName, type, required: !isOptional };
|
|
93
|
-
if (type === "enum") {
|
|
94
|
-
// Extract enum values from z.enum(["a", "b", "c"])
|
|
95
|
-
const enumContentMatch = /\[([^\]]*)\]/.exec(methodArgs + chainStr);
|
|
96
|
-
if (enumContentMatch) {
|
|
97
|
-
field.enumValues = enumContentMatch[1]
|
|
98
|
-
.split(",")
|
|
99
|
-
.map((v) => v.trim().replace(/^["'`]|["'`]$/g, ""))
|
|
100
|
-
.filter(Boolean);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
fields.push(field);
|
|
104
|
-
}
|
|
105
|
-
return fields;
|
|
106
|
-
}
|
|
107
|
-
function formatSchemaAnnotation(schemas, filePath) {
|
|
108
|
-
if (schemas.length === 0)
|
|
109
|
-
return "";
|
|
110
|
-
const lines = [`// EXTRACTED_SCHEMAS from ${filePath}:`];
|
|
111
|
-
for (const schema of schemas.slice(0, 5)) { // cap at 5 schemas per file
|
|
112
|
-
const label = schema.name ?? "anonymous";
|
|
113
|
-
lines.push(`// Schema "${label}":`);
|
|
114
|
-
for (const field of schema.fields) {
|
|
115
|
-
const optStr = field.required ? "required" : "optional";
|
|
116
|
-
const enumStr = field.enumValues?.length
|
|
117
|
-
? ` [${field.enumValues.slice(0, 6).join("|")}]`
|
|
118
|
-
: "";
|
|
119
|
-
lines.push(`// ${field.name}: ${field.type}${enumStr} (${optStr})`);
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
return lines.join("\n");
|
|
123
|
-
}
|
|
124
|
-
/**
|
|
125
|
-
* Extract Zod schema hints from a list of API source files.
|
|
126
|
-
* Returns one FileSchemaHint per file that contains at least one z.object declaration.
|
|
127
|
-
*
|
|
128
|
-
* @example
|
|
129
|
-
* ```ts
|
|
130
|
-
* const hints = await extractZodHintsFromFiles(sandboxFs, readList.apiFiles);
|
|
131
|
-
* // Inject hints[n].annotation into the agent prompt alongside each file snippet.
|
|
132
|
-
* ```
|
|
133
|
-
*/
|
|
134
|
-
export async function extractZodHintsFromFiles(readFile, filePaths) {
|
|
135
|
-
const hints = new Map();
|
|
136
|
-
for (const filePath of filePaths) {
|
|
137
|
-
// Only scan TypeScript/JavaScript files
|
|
138
|
-
if (!/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(filePath))
|
|
139
|
-
continue;
|
|
140
|
-
const source = await readFile(filePath);
|
|
141
|
-
if (!source || !source.includes("z.object("))
|
|
142
|
-
continue;
|
|
143
|
-
const schemas = parseZodObjects(source);
|
|
144
|
-
if (schemas.length === 0)
|
|
145
|
-
continue;
|
|
146
|
-
hints.set(filePath, {
|
|
147
|
-
filePath,
|
|
148
|
-
schemas,
|
|
149
|
-
annotation: formatSchemaAnnotation(schemas, filePath),
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
return hints;
|
|
153
|
-
}
|
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import type { ActionManifest, RouteManifest, DeeplinkDefinition, AuthSchema } from "../../core/types.js";
|
|
2
|
-
import type { PipelineResult } from "../agents/pipeline.js";
|
|
3
|
-
export interface ReviewOptions {
|
|
4
|
-
/** Auto-approve all prompts — for CI / scripted use */
|
|
5
|
-
yes?: boolean;
|
|
6
|
-
/** Write unresolved decisions to duct-review.json instead of prompting */
|
|
7
|
-
noInteractive?: boolean;
|
|
8
|
-
/** Directory to write duct-review.json (defaults to cwd) */
|
|
9
|
-
cwd?: string;
|
|
10
|
-
}
|
|
11
|
-
export interface ReviewedPipelineResult {
|
|
12
|
-
routes: RouteManifest[];
|
|
13
|
-
actions: ActionManifest[];
|
|
14
|
-
auth: AuthSchema;
|
|
15
|
-
deeplinks: DeeplinkDefinition[];
|
|
16
|
-
/** Actions the user explicitly rejected or marked never */
|
|
17
|
-
rejectedActions: ActionManifest[];
|
|
18
|
-
/** Decisions written to duct-review.json (noInteractive mode) */
|
|
19
|
-
reviewFilePath?: string;
|
|
20
|
-
/** Whether this shell should accept cross-shell calls (default false) */
|
|
21
|
-
intershell_enabled?: boolean;
|
|
22
|
-
/** Whether this shell should be discoverable in the Duct network (default 'private') */
|
|
23
|
-
registry_visibility?: 'public' | 'private';
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Interactive Review CLI.
|
|
27
|
-
*
|
|
28
|
-
* Decision rules:
|
|
29
|
-
* - Auto-approve: GET/HEAD with confidence ≥ 0.85 → no prompt
|
|
30
|
-
* - Always prompt: POST/PUT/PATCH/DELETE, confidence < 0.85, auth ambiguity
|
|
31
|
-
*
|
|
32
|
-
* Flags:
|
|
33
|
-
* - `--yes`: auto-approve everything, skip interactive review
|
|
34
|
-
* - `--no-interactive`: write unresolved decisions to duct-review.json
|
|
35
|
-
*/
|
|
36
|
-
export declare function runInteractiveReview(pipelineResult: PipelineResult, opts?: ReviewOptions): Promise<ReviewedPipelineResult>;
|
|
37
|
-
export interface InteractiveReviewOptions {
|
|
38
|
-
/** Auto-approve everything (--yes / CI mode) */
|
|
39
|
-
yes: boolean;
|
|
40
|
-
/** Write manifest to duct-review.json instead of prompting (--no-interactive) */
|
|
41
|
-
noInteractive: boolean;
|
|
42
|
-
/** Working directory for writing duct-review.json (defaults to cwd) */
|
|
43
|
-
cwd?: string;
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Interactive review for a generated manifest.
|
|
47
|
-
*
|
|
48
|
-
* Decision rules:
|
|
49
|
-
* - `options.yes` → return manifest unchanged, all actions approved
|
|
50
|
-
* - `options.noInteractive` → write to duct-review.json, return manifest unchanged
|
|
51
|
-
* - Otherwise:
|
|
52
|
-
* - GET + confidence ≥ 0.85 → auto-approve (prints "✓ Auto-approved: [id]")
|
|
53
|
-
* - POST / DELETE / PATCH / PUT → always prompt
|
|
54
|
-
* - confidence < 0.85 → prompt regardless of method
|
|
55
|
-
* - Shows evidence: "Detected from: [files]"
|
|
56
|
-
*
|
|
57
|
-
* @param manifest The generated DuctConfig-like manifest (any shape, operates on .actions[])
|
|
58
|
-
* @param options Review mode flags
|
|
59
|
-
* @returns The manifest with only approved actions
|
|
60
|
-
*/
|
|
61
|
-
export declare function interactiveReview(manifest: any, options: InteractiveReviewOptions): Promise<any>;
|