@duct-sdk/sdk 0.5.13 → 0.7.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 (166) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +418 -264
  3. package/TOKEN_SPEC.md +243 -243
  4. package/dist/cli/action-confusion-format.d.ts +17 -0
  5. package/dist/cli/action-confusion-format.js +24 -0
  6. package/dist/cli/add.d.ts +7 -0
  7. package/dist/cli/add.js +152 -0
  8. package/dist/cli/agent-prompt.d.ts +3 -0
  9. package/dist/cli/agent-prompt.js +39 -0
  10. package/dist/cli/api-sources.d.ts +26 -0
  11. package/dist/cli/api-sources.js +222 -0
  12. package/dist/cli/cloud.d.ts +162 -0
  13. package/dist/cli/cloud.js +306 -0
  14. package/dist/cli/config-loader.d.ts +14 -0
  15. package/dist/cli/config-loader.js +56 -7
  16. package/dist/cli/device-login.d.ts +17 -0
  17. package/dist/cli/device-login.js +75 -0
  18. package/dist/cli/drift.js +6 -6
  19. package/dist/cli/generators/any-stack.d.ts +3 -0
  20. package/dist/cli/generators/any-stack.js +97 -0
  21. package/dist/cli/generators/config.js +3 -2
  22. package/dist/cli/generators/receiver.js +7 -7
  23. package/dist/cli/generators/shell.js +12 -12
  24. package/dist/cli/generators/token-route.js +245 -245
  25. package/dist/cli/generators/wiring-snippets.d.ts +0 -14
  26. package/dist/cli/generators/wiring-snippets.js +188 -305
  27. package/dist/cli/index.js +396 -611
  28. package/dist/cli/mcp-core.d.ts +42 -0
  29. package/dist/cli/mcp-core.js +161 -0
  30. package/dist/cli/mcp-setup.d.ts +4 -0
  31. package/dist/cli/mcp-setup.js +352 -0
  32. package/dist/cli/mcp.d.ts +2 -0
  33. package/dist/cli/mcp.js +457 -0
  34. package/dist/cli/migrate-intershell.js +5 -5
  35. package/dist/cli/policy-defaults.d.ts +37 -0
  36. package/dist/cli/policy-defaults.js +127 -0
  37. package/dist/cli/policy-replay-format.d.ts +9 -0
  38. package/dist/cli/policy-replay-format.js +46 -0
  39. package/dist/cli/processors/integration-audit.js +2 -2
  40. package/dist/cli/processors/openapi-parser.d.ts +5 -0
  41. package/dist/cli/processors/openapi-parser.js +8 -3
  42. package/dist/cli/project-loader.d.ts +58 -0
  43. package/dist/cli/project-loader.js +198 -0
  44. package/dist/cli/project-writer.d.ts +23 -0
  45. package/dist/cli/project-writer.js +171 -0
  46. package/dist/cli/push.d.ts +43 -0
  47. package/dist/cli/push.js +308 -0
  48. package/dist/cli/safety-checks.d.ts +9 -0
  49. package/dist/cli/safety-checks.js +29 -0
  50. package/dist/cli/setup.d.ts +20 -0
  51. package/dist/cli/setup.js +349 -0
  52. package/dist/cli/shell-name.d.ts +8 -0
  53. package/dist/cli/shell-name.js +29 -0
  54. package/dist/cli/shells.d.ts +22 -0
  55. package/dist/cli/shells.js +122 -0
  56. package/dist/cli/split.d.ts +7 -0
  57. package/dist/cli/split.js +71 -0
  58. package/dist/cli/sync.d.ts +25 -0
  59. package/dist/cli/sync.js +120 -0
  60. package/dist/cli/test-runner.d.ts +21 -0
  61. package/dist/cli/test-runner.js +281 -0
  62. package/dist/core/compile.d.ts +43 -0
  63. package/dist/core/compile.js +512 -0
  64. package/dist/core/config.d.ts +538 -19
  65. package/dist/core/config.js +22 -14
  66. package/dist/core/login-handoff.d.ts +1 -1
  67. package/dist/core/login-handoff.js +1 -1
  68. package/dist/core/project.d.ts +1864 -0
  69. package/dist/core/project.js +291 -0
  70. package/dist/core/readiness-checks.js +2 -2
  71. package/dist/core/types.d.ts +10 -1
  72. package/dist/index.d.ts +2 -0
  73. package/dist/index.js +1 -0
  74. package/dist/project.d.ts +4 -0
  75. package/dist/project.js +8 -0
  76. package/dist/server.d.ts +2 -0
  77. package/dist/server.js +1 -0
  78. package/package.json +94 -95
  79. package/dist/adapters/react/page-context-guard.test.d.ts +0 -1
  80. package/dist/adapters/react/page-context-guard.test.js +0 -15
  81. package/dist/cli/agents/api-agent.d.ts +0 -22
  82. package/dist/cli/agents/api-agent.js +0 -761
  83. package/dist/cli/agents/auth-agent.d.ts +0 -7
  84. package/dist/cli/agents/auth-agent.js +0 -212
  85. package/dist/cli/agents/deeplink-agent.d.ts +0 -6
  86. package/dist/cli/agents/deeplink-agent.js +0 -285
  87. package/dist/cli/agents/llm.d.ts +0 -33
  88. package/dist/cli/agents/llm.js +0 -309
  89. package/dist/cli/agents/pipeline.d.ts +0 -72
  90. package/dist/cli/agents/pipeline.js +0 -421
  91. package/dist/cli/agents/reviewer-agent.d.ts +0 -13
  92. package/dist/cli/agents/reviewer-agent.js +0 -450
  93. package/dist/cli/agents/route-agent.d.ts +0 -17
  94. package/dist/cli/agents/route-agent.js +0 -383
  95. package/dist/cli/config-loader.test.d.ts +0 -1
  96. package/dist/cli/config-loader.test.js +0 -63
  97. package/dist/cli/detectors/topology.d.ts +0 -46
  98. package/dist/cli/detectors/topology.js +0 -417
  99. package/dist/cli/generators/config.test.d.ts +0 -1
  100. package/dist/cli/generators/config.test.js +0 -222
  101. package/dist/cli/generators/shell.test.d.ts +0 -1
  102. package/dist/cli/generators/shell.test.js +0 -73
  103. package/dist/cli/generators/token-route.test.d.ts +0 -1
  104. package/dist/cli/generators/token-route.test.js +0 -53
  105. package/dist/cli/generators/wiring-snippets.test.d.ts +0 -1
  106. package/dist/cli/generators/wiring-snippets.test.js +0 -80
  107. package/dist/cli/init.d.ts +0 -32
  108. package/dist/cli/init.js +0 -1336
  109. package/dist/cli/manifest-diff.test.d.ts +0 -1
  110. package/dist/cli/manifest-diff.test.js +0 -144
  111. package/dist/cli/processors/curl-parser.test.d.ts +0 -1
  112. package/dist/cli/processors/curl-parser.test.js +0 -24
  113. package/dist/cli/processors/integration-audit.test.d.ts +0 -1
  114. package/dist/cli/processors/integration-audit.test.js +0 -154
  115. package/dist/cli/processors/postprocess.d.ts +0 -22
  116. package/dist/cli/processors/postprocess.js +0 -107
  117. package/dist/cli/processors/prisma-parser.d.ts +0 -35
  118. package/dist/cli/processors/prisma-parser.js +0 -117
  119. package/dist/cli/processors/verify-discovery.d.ts +0 -33
  120. package/dist/cli/processors/verify-discovery.js +0 -193
  121. package/dist/cli/processors/verify-discovery.test.d.ts +0 -1
  122. package/dist/cli/processors/verify-discovery.test.js +0 -153
  123. package/dist/cli/processors/zod-extractor.d.ts +0 -27
  124. package/dist/cli/processors/zod-extractor.js +0 -153
  125. package/dist/cli/prompts/review.d.ts +0 -61
  126. package/dist/cli/prompts/review.js +0 -410
  127. package/dist/cli/selectors/express.d.ts +0 -12
  128. package/dist/cli/selectors/express.js +0 -117
  129. package/dist/cli/selectors/fastapi.d.ts +0 -12
  130. package/dist/cli/selectors/fastapi.js +0 -122
  131. package/dist/cli/selectors/generic.d.ts +0 -10
  132. package/dist/cli/selectors/generic.js +0 -74
  133. package/dist/cli/selectors/index.d.ts +0 -37
  134. package/dist/cli/selectors/index.js +0 -315
  135. package/dist/cli/selectors/next.d.ts +0 -12
  136. package/dist/cli/selectors/next.js +0 -130
  137. package/dist/core/config-policy.test.d.ts +0 -1
  138. package/dist/core/config-policy.test.js +0 -101
  139. package/dist/core/config-roundtrip.test.d.ts +0 -1
  140. package/dist/core/config-roundtrip.test.js +0 -180
  141. package/dist/core/endpoint-guard.test.d.ts +0 -1
  142. package/dist/core/endpoint-guard.test.js +0 -57
  143. package/dist/core/env-diagnostics.test.d.ts +0 -1
  144. package/dist/core/env-diagnostics.test.js +0 -31
  145. package/dist/core/evidence-bundle.conformance.test.d.ts +0 -1
  146. package/dist/core/evidence-bundle.conformance.test.js +0 -110
  147. package/dist/core/evidence-bundle.test.d.ts +0 -1
  148. package/dist/core/evidence-bundle.test.js +0 -58
  149. package/dist/core/invariants.test.d.ts +0 -1
  150. package/dist/core/invariants.test.js +0 -217
  151. package/dist/core/login-handoff.test.d.ts +0 -1
  152. package/dist/core/login-handoff.test.js +0 -31
  153. package/dist/core/profile.test.d.ts +0 -1
  154. package/dist/core/profile.test.js +0 -95
  155. package/dist/core/readiness-checks.test.d.ts +0 -1
  156. package/dist/core/readiness-checks.test.js +0 -106
  157. package/dist/core/receipt.test.d.ts +0 -1
  158. package/dist/core/receipt.test.js +0 -75
  159. package/dist/core/sdk-entrypoint.test.d.ts +0 -1
  160. package/dist/core/sdk-entrypoint.test.js +0 -8
  161. package/dist/core/side-effects-review.test.d.ts +0 -1
  162. package/dist/core/side-effects-review.test.js +0 -28
  163. package/dist/core/token.conformance.test.d.ts +0 -1
  164. package/dist/core/token.conformance.test.js +0 -43
  165. package/dist/core/token.test.d.ts +0 -1
  166. package/dist/core/token.test.js +0 -66
@@ -0,0 +1,120 @@
1
+ // ============================================================
2
+ // @duct-sdk/sdk — duct sync
3
+ //
4
+ // Refresh duct/capabilities.json from its recorded source (OpenAPI file,
5
+ // served spec, Postman). Human-reviewed fields survive: names, descriptions,
6
+ // sensitivity, and side-effect review notes. The policy is never touched.
7
+ // ============================================================
8
+ import * as fs from "fs/promises";
9
+ import chalk from "chalk";
10
+ import ora from "ora";
11
+ import { CapabilitiesFileSchema } from "../core/project.js";
12
+ import { classifySourceLocation, loadApiSource } from "./api-sources.js";
13
+ import { findProjectRoot, projectPaths } from "./project-loader.js";
14
+ import { renderCapabilitiesFile } from "./project-writer.js";
15
+ const REVIEWED_FIELDS = ["name", "description", "sensitivityLevel"];
16
+ const SPEC_FIELDS = ["method", "path", "params", "inputSchema", "responseSchema", "requiresAuth"];
17
+ function same(a, b) {
18
+ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
19
+ }
20
+ /** Merge fresh actions from the source into the current file. Pure — exported for tests. */
21
+ export function mergeCapabilities(current, fresh, source, opts = {}) {
22
+ const byId = new Map(current.actions.map((action) => [action.id, action]));
23
+ const byRoute = new Map(current.actions.map((action) => [`${action.method} ${action.path}`, action]));
24
+ const matched = new Set();
25
+ const added = [];
26
+ const changed = [];
27
+ const merged = fresh.map((incoming) => {
28
+ const existing = byId.get(incoming.id) ?? byRoute.get(`${incoming.method} ${incoming.path}`);
29
+ if (!existing) {
30
+ added.push(incoming.id);
31
+ return incoming;
32
+ }
33
+ matched.add(existing.id);
34
+ const fields = SPEC_FIELDS.filter((field) => !same(existing[field], incoming[field]));
35
+ const next = { ...incoming, id: existing.id };
36
+ for (const field of REVIEWED_FIELDS) {
37
+ if (existing[field] !== undefined)
38
+ next[field] = existing[field];
39
+ }
40
+ // A method change re-derives side effects; otherwise keep the reviewed classification.
41
+ if (existing.method === incoming.method) {
42
+ next.sideEffects = existing.sideEffects;
43
+ if (existing.sideEffectsReviewAck)
44
+ next.sideEffectsReviewAck = existing.sideEffectsReviewAck;
45
+ }
46
+ else {
47
+ fields.push("sideEffects (re-derived from new method)");
48
+ }
49
+ if (fields.length > 0)
50
+ changed.push({ id: existing.id, fields });
51
+ return next;
52
+ });
53
+ const removedActions = current.actions.filter((action) => !matched.has(action.id));
54
+ if (opts.keepRemoved)
55
+ merged.push(...removedActions);
56
+ return {
57
+ added,
58
+ removed: opts.keepRemoved ? [] : removedActions.map((action) => action.id),
59
+ changed,
60
+ next: { ...current, source, actions: merged },
61
+ };
62
+ }
63
+ export async function runSync(opts) {
64
+ const found = findProjectRoot(opts.cwd);
65
+ if (!found || found.layout !== "split") {
66
+ throw new Error(found?.layout === "legacy"
67
+ ? "This project uses duct.config.ts — run `npx @duct-sdk/sdk split` first."
68
+ : "No duct/ folder found — run `npx @duct-sdk/sdk setup`.");
69
+ }
70
+ const paths = projectPaths(found.root);
71
+ const parsed = CapabilitiesFileSchema.safeParse(JSON.parse(await fs.readFile(paths.capabilities, "utf-8")));
72
+ if (!parsed.success) {
73
+ throw new Error(`duct/capabilities.json is invalid: ${parsed.error.issues[0]?.message ?? "unknown error"}`);
74
+ }
75
+ const current = parsed.data;
76
+ let source;
77
+ if (opts.source) {
78
+ source = classifySourceLocation(opts.source);
79
+ }
80
+ else if (current.source.location && current.source.kind !== "manual" && current.source.kind !== "imported") {
81
+ source = {
82
+ kind: current.source.kind,
83
+ location: current.source.location,
84
+ remote: /^https?:\/\//i.test(current.source.location),
85
+ };
86
+ }
87
+ else {
88
+ throw new Error("duct/capabilities.json has no source to sync from. Pass --source <openapi file or URL>.");
89
+ }
90
+ const spinner = ora(`Reading ${source.location}…`).start();
91
+ const loaded = await loadApiSource(found.root, source).catch((err) => {
92
+ spinner.fail(`Could not read ${source.location}`);
93
+ throw err;
94
+ });
95
+ spinner.succeed(`${loaded.actions.length} actions in ${source.location}`);
96
+ const diff = mergeCapabilities(current, loaded.actions, { kind: source.kind, location: source.location, syncedAt: new Date().toISOString() }, { keepRemoved: opts.keepRemoved });
97
+ if (diff.added.length + diff.removed.length + diff.changed.length === 0) {
98
+ console.log(chalk.green("\n ✓ Capabilities already match the source.\n"));
99
+ }
100
+ else {
101
+ console.log();
102
+ for (const id of diff.added)
103
+ console.log(` ${chalk.green("+")} ${id}`);
104
+ for (const id of diff.removed)
105
+ console.log(` ${chalk.red("-")} ${id}`);
106
+ for (const change of diff.changed)
107
+ console.log(` ${chalk.yellow("~")} ${change.id} ${chalk.gray(change.fields.join(", "))}`);
108
+ console.log();
109
+ if (diff.added.length > 0) {
110
+ console.log(chalk.gray(" New actions follow duct/policy.ts (reads open to agents by default, writes off until you allow them)."));
111
+ }
112
+ }
113
+ if (opts.dryRun) {
114
+ console.log(chalk.gray(" Dry run — nothing written.\n"));
115
+ return diff;
116
+ }
117
+ await fs.writeFile(paths.capabilities, renderCapabilitiesFile(diff.next), "utf-8");
118
+ console.log(chalk.gray(" Updated duct/capabilities.json — run `npx @duct-sdk/sdk test`, then `push`.\n"));
119
+ return diff;
120
+ }
@@ -0,0 +1,21 @@
1
+ export type CheckStatus = "pass" | "fail" | "warn" | "skip";
2
+ export interface CheckResult {
3
+ id: string;
4
+ label: string;
5
+ status: CheckStatus;
6
+ message: string;
7
+ details?: string[];
8
+ }
9
+ export interface TestReport {
10
+ ok: boolean;
11
+ shellId?: string;
12
+ checks: CheckResult[];
13
+ }
14
+ export interface TestOptions {
15
+ cwd: string;
16
+ config?: string;
17
+ /** Only run local checks (no network). */
18
+ offline?: boolean;
19
+ }
20
+ export declare function runTests(opts: TestOptions): Promise<TestReport>;
21
+ export declare function printTestReport(report: TestReport): void;
@@ -0,0 +1,281 @@
1
+ // ============================================================
2
+ // @duct-sdk/sdk — duct test
3
+ //
4
+ // "Will Duct work for my API?" in one command:
5
+ // 1. project files compile and pass the same gates as push (local)
6
+ // 2. signed in, and the shell belongs to your workspace (cloud)
7
+ // 3. Duct can reach your API origin (cloud)
8
+ // 4. built-in guardrails hold for your policy (cloud)
9
+ // 5. your duct/tests.ts expectations hold (cloud)
10
+ // 6. what is live matches what you have locally (cloud)
11
+ //
12
+ // Cloud checks evaluate the policy you are about to push (sent in the
13
+ // request, never stored) with the gateway's real policy kernel.
14
+ // ============================================================
15
+ import chalk from "chalk";
16
+ import { DuctConfigSchema } from "../core/config.js";
17
+ import { enforcementDiff } from "../core/compile.js";
18
+ import { loadAndValidateProject, PushAbortedError } from "./push.js";
19
+ import { ProjectLoadError, ProjectNotFoundError } from "./project-loader.js";
20
+ import { CloudError, checkPolicy, checkUpstream, fetchLiveFullManifest, listAccountShells, readAuth, resolveApiKey, } from "./cloud.js";
21
+ import { builtinGuardrailCases, expectationMet } from "./policy-defaults.js";
22
+ const POLICY_BATCH = 200;
23
+ async function evaluateInBatches(run, cases) {
24
+ const results = [];
25
+ for (let i = 0; i < cases.length; i += POLICY_BATCH) {
26
+ results.push(...(await run(cases.slice(i, i + POLICY_BATCH))));
27
+ }
28
+ return results;
29
+ }
30
+ function describeCase(c) {
31
+ return `${c.as}${c.withUserConsent ? " (with consent)" : ""} → ${c.action}`;
32
+ }
33
+ function compareExpectations(cases, results) {
34
+ const failures = [];
35
+ let passed = 0;
36
+ cases.forEach((testCase, index) => {
37
+ const result = results[index];
38
+ if (!result) {
39
+ failures.push(`${testCase.name ?? describeCase(testCase)}: no result returned`);
40
+ return;
41
+ }
42
+ if (expectationMet(testCase.expect, result.decision)) {
43
+ passed++;
44
+ return;
45
+ }
46
+ failures.push(`${testCase.name ?? describeCase(testCase)}: expected ${testCase.expect}, got ${result.decision}` +
47
+ ` (${result.reason})`);
48
+ });
49
+ return { failures, passed };
50
+ }
51
+ export async function runTests(opts) {
52
+ const checks = [];
53
+ const add = (check) => checks.push(check);
54
+ // ── 1. Local: compile + validate ────────────────────────────────
55
+ let project;
56
+ try {
57
+ project = await loadAndValidateProject(opts.cwd, opts.config);
58
+ }
59
+ catch (err) {
60
+ const details = err instanceof ProjectLoadError
61
+ ? err.issues
62
+ : err instanceof PushAbortedError
63
+ ? err.details
64
+ : undefined;
65
+ const message = err instanceof ProjectNotFoundError
66
+ ? "No Duct project here — run `npx @duct-sdk/sdk setup`"
67
+ : err instanceof ProjectLoadError
68
+ ? "Project files have problems"
69
+ : err instanceof Error
70
+ ? err.message
71
+ : String(err);
72
+ add({ id: "project", label: "Project files", status: "fail", message, details });
73
+ return { ok: false, checks };
74
+ }
75
+ const { validated, config, resolved } = project;
76
+ const actionCount = validated.actions.length;
77
+ add({
78
+ id: "project",
79
+ label: "Project files",
80
+ status: project.safetyWarnings.length > 0 || resolved.warnings.length > 0 ? "warn" : "pass",
81
+ message: `${resolved.layout === "split" ? "duct/" : "duct.config.ts"} compiles · ${actionCount} action` +
82
+ `${actionCount === 1 ? "" : "s"} · passes push validation`,
83
+ details: [...resolved.warnings, ...project.safetyWarnings],
84
+ });
85
+ const testCases = (resolved.files?.tests?.policy ?? []).map((c) => ({
86
+ name: c.name,
87
+ as: c.as,
88
+ action: c.action,
89
+ params: c.params,
90
+ withUserConsent: c.withUserConsent,
91
+ expect: c.expect,
92
+ }));
93
+ const unknownTestActions = testCases
94
+ .filter((c) => !validated.actions.some((action) => action.id === c.action))
95
+ .map((c) => `${c.name ?? describeCase(c)}: unknown action "${c.action}"`);
96
+ if (unknownTestActions.length > 0) {
97
+ add({
98
+ id: "tests_file",
99
+ label: "duct/tests.ts",
100
+ status: "fail",
101
+ message: "Some test cases reference actions that do not exist",
102
+ details: unknownTestActions,
103
+ });
104
+ }
105
+ if (opts.offline) {
106
+ add({ id: "cloud", label: "Cloud checks", status: "skip", message: "Skipped (--offline)" });
107
+ return { ok: !checks.some((c) => c.status === "fail"), shellId: validated.shellId, checks };
108
+ }
109
+ // ── 2. Cloud: credentials + shell ownership ─────────────────────
110
+ const auth = await readAuth();
111
+ const apiKey = resolveApiKey(auth);
112
+ const shellId = validated.shellId;
113
+ if (!apiKey) {
114
+ add({
115
+ id: "auth",
116
+ label: "Signed in",
117
+ status: "fail",
118
+ message: "Not signed in — run `npx @duct-sdk/sdk login` (CI: set DUCT_API_KEY)",
119
+ });
120
+ return { ok: false, shellId, checks };
121
+ }
122
+ try {
123
+ const shells = await listAccountShells(auth, apiKey);
124
+ const shell = shells.find((s) => s.id === shellId);
125
+ if (!shell) {
126
+ add({
127
+ id: "auth",
128
+ label: "Shell",
129
+ status: "fail",
130
+ message: `${shellId} is not in your workspace${auth?.email ? ` (${auth.email})` : ""}`,
131
+ details: shells.length > 0 ? [`Your shells: ${shells.map((s) => s.id).join(", ")}`] : undefined,
132
+ });
133
+ return { ok: false, shellId, checks };
134
+ }
135
+ add({
136
+ id: "auth",
137
+ label: "Shell",
138
+ status: shell.status && shell.status !== "active" ? "warn" : "pass",
139
+ message: `${shellId}${shell.environment ? ` · ${shell.environment}` : ""}${auth?.email ? ` · ${auth.email}` : ""}`,
140
+ });
141
+ }
142
+ catch (err) {
143
+ add({
144
+ id: "auth",
145
+ label: "Signed in",
146
+ status: "fail",
147
+ message: err instanceof Error ? err.message : String(err),
148
+ });
149
+ return { ok: false, shellId, checks };
150
+ }
151
+ // ── 3. Cloud: upstream reachability ─────────────────────────────
152
+ try {
153
+ const upstream = await checkUpstream(auth, apiKey, shellId, config);
154
+ add({
155
+ id: "upstream",
156
+ label: "Duct → your API",
157
+ status: upstream.ok ? (upstream.status && upstream.status >= 500 ? "warn" : "pass") : "fail",
158
+ message: `${upstream.origin ? `${upstream.origin} · ` : ""}${upstream.message}`,
159
+ });
160
+ }
161
+ catch (err) {
162
+ add({ id: "upstream", label: "Duct → your API", status: "fail", message: cloudMessage(err) });
163
+ }
164
+ // ── 4 + 5. Cloud: guardrails and your policy tests ───────────────
165
+ const guardrails = builtinGuardrailCases(validated);
166
+ const runPolicy = (cases) => checkPolicy(auth, apiKey, shellId, config, cases);
167
+ if (guardrails.length === 0) {
168
+ add({ id: "guardrails", label: "Built-in guardrails", status: "skip", message: "No write or sensitive actions" });
169
+ }
170
+ else {
171
+ try {
172
+ const results = await evaluateInBatches(runPolicy, guardrails.map(stripExpectation));
173
+ const { failures, passed } = compareExpectations(guardrails, results);
174
+ add({
175
+ id: "guardrails",
176
+ label: "Built-in guardrails",
177
+ status: failures.length > 0 ? "fail" : "pass",
178
+ message: failures.length > 0
179
+ ? `${failures.length} of ${guardrails.length} guardrail checks failed`
180
+ : `${passed} checks · agents cannot write or touch sensitive data without a human`,
181
+ details: failures,
182
+ });
183
+ }
184
+ catch (err) {
185
+ add({ id: "guardrails", label: "Built-in guardrails", status: "fail", message: cloudMessage(err) });
186
+ }
187
+ }
188
+ const runnableTests = testCases.filter((c) => validated.actions.some((action) => action.id === c.action));
189
+ if (runnableTests.length === 0) {
190
+ add({
191
+ id: "policy_tests",
192
+ label: "Your policy tests",
193
+ status: "skip",
194
+ message: resolved.layout === "split" ? "No cases in duct/tests.ts" : "Legacy layout has no tests file",
195
+ });
196
+ }
197
+ else {
198
+ try {
199
+ const results = await evaluateInBatches(runPolicy, runnableTests.map(stripExpectation));
200
+ const { failures, passed } = compareExpectations(runnableTests, results);
201
+ add({
202
+ id: "policy_tests",
203
+ label: "Your policy tests",
204
+ status: failures.length > 0 ? "fail" : "pass",
205
+ message: failures.length > 0 ? `${failures.length} of ${runnableTests.length} failed` : `${passed} passed`,
206
+ details: failures,
207
+ });
208
+ }
209
+ catch (err) {
210
+ add({ id: "policy_tests", label: "Your policy tests", status: "fail", message: cloudMessage(err) });
211
+ }
212
+ }
213
+ // ── 6. Cloud: live vs local (full owner snapshot, compared on enforcement) ──
214
+ try {
215
+ const live = await fetchLiveFullManifest(auth, apiKey, shellId);
216
+ if (!live) {
217
+ add({ id: "sync", label: "Live on Duct", status: "warn", message: "Not pushed yet — run `npx @duct-sdk/sdk push`" });
218
+ }
219
+ else {
220
+ const parsedLive = DuctConfigSchema.safeParse(live);
221
+ const diffs = parsedLive.success
222
+ ? enforcementDiff(parsedLive.data, validated)
223
+ : ["live manifest predates the current schema"];
224
+ add({
225
+ id: "sync",
226
+ label: "Live on Duct",
227
+ status: diffs.length > 0 ? "warn" : "pass",
228
+ message: diffs.length > 0
229
+ ? `${diffs.length} enforcement change${diffs.length === 1 ? "" : "s"} not pushed — run \`npx @duct-sdk/sdk push\``
230
+ : "Live enforcement matches your project",
231
+ details: diffs.slice(0, 8),
232
+ });
233
+ }
234
+ }
235
+ catch (err) {
236
+ add({ id: "sync", label: "Live on Duct", status: "warn", message: cloudMessage(err) });
237
+ }
238
+ return { ok: !checks.some((c) => c.status === "fail"), shellId, checks };
239
+ }
240
+ function stripExpectation(c) {
241
+ return {
242
+ ...(c.name ? { name: c.name } : {}),
243
+ as: c.as,
244
+ action: c.action,
245
+ ...(c.params ? { params: c.params } : {}),
246
+ ...(c.withUserConsent ? { withUserConsent: true } : {}),
247
+ };
248
+ }
249
+ function cloudMessage(err) {
250
+ if (err instanceof CloudError) {
251
+ if (err.status === 404 && !err.code) {
252
+ return "This Duct deployment does not support `duct test` checks yet — update the Duct API to 0.16.0+";
253
+ }
254
+ if (err.status === 429)
255
+ return "Rate limited — wait a minute and retry";
256
+ return err.message;
257
+ }
258
+ return err instanceof Error ? err.message : String(err);
259
+ }
260
+ const ICONS = {
261
+ pass: chalk.green("✓"),
262
+ fail: chalk.red("✗"),
263
+ warn: chalk.yellow("!"),
264
+ skip: chalk.gray("–"),
265
+ };
266
+ export function printTestReport(report) {
267
+ for (const check of report.checks) {
268
+ const text = check.status === "fail" ? chalk.red(check.message) : check.status === "skip" ? chalk.gray(check.message) : check.message;
269
+ console.log(` ${ICONS[check.status]} ${chalk.bold(check.label.padEnd(20))} ${text}`);
270
+ for (const detail of check.details ?? []) {
271
+ console.log(chalk.gray(` • ${detail}`));
272
+ }
273
+ }
274
+ console.log();
275
+ if (report.ok) {
276
+ console.log(chalk.green(" All checks passed.\n"));
277
+ }
278
+ else {
279
+ console.log(chalk.red(" Some checks failed — fix the items above and re-run `npx @duct-sdk/sdk test`.\n"));
280
+ }
281
+ }
@@ -0,0 +1,43 @@
1
+ import type { ActionLimitPolicy, ActionManifest, ApprovalPredicate, AuthSchema, DuctConfig } from "./types.js";
2
+ import type { Condition, LimitSpec, ParsedCapabilitiesFile, ParsedPolicyFile, ParsedProjectFile, ParsedShellFile, PolicyFile, ProjectFile, ShellFile, CapabilitiesFile } from "./project.js";
3
+ /** Fallback when duct/project.ts omits `auth` (only identity + chat use it). */
4
+ export declare const DEFAULT_PROJECT_AUTH: AuthSchema;
5
+ export interface ProjectInput {
6
+ project: ParsedProjectFile;
7
+ capabilities: ParsedCapabilitiesFile;
8
+ policy: ParsedPolicyFile;
9
+ shell?: ParsedShellFile | null;
10
+ }
11
+ export interface CompileResult {
12
+ config: DuctConfig;
13
+ /** Non-fatal issues worth showing (unused patterns, unknown hint ids, …). */
14
+ warnings: string[];
15
+ }
16
+ export declare function patternToRegExp(pattern: string): RegExp;
17
+ export declare function matchesPattern(pattern: string, actionId: string): boolean;
18
+ export declare function compileCondition(condition: Condition): ApprovalPredicate;
19
+ export declare function decompilePredicate(predicate: ApprovalPredicate): Condition;
20
+ export declare function limitToFields(spec: LimitSpec): {
21
+ rateLimit?: number;
22
+ actionLimit?: ActionLimitPolicy;
23
+ };
24
+ export declare function fieldsToLimit(action: {
25
+ rateLimit?: number;
26
+ actionLimit?: ActionLimitPolicy;
27
+ }): LimitSpec | null;
28
+ export declare function compileProject(input: ProjectInput): CompileResult;
29
+ /**
30
+ * Every enforcement-relevant difference between two manifests, per action.
31
+ * Empty = the gateway makes the same decision for every caller on every action.
32
+ */
33
+ export declare function enforcementDiff(before: DuctConfig, after: DuctConfig): string[];
34
+ /** Keep only the "what the API does" fields of an action (drop policy and chat hints). */
35
+ export declare function capabilityFromAction(action: ActionManifest): CapabilitiesFile["actions"][number];
36
+ export interface SplitResult {
37
+ project: ProjectFile;
38
+ capabilities: CapabilitiesFile;
39
+ policy: PolicyFile;
40
+ shell: ShellFile | null;
41
+ warnings: string[];
42
+ }
43
+ export declare function splitDuctConfig(config: DuctConfig): SplitResult;