@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
@@ -1 +0,0 @@
1
- export {};
@@ -1,144 +0,0 @@
1
- import { describe, it } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { computeManifestPrivilegeDiff, detectDashboardNetworkReverts } from "./manifest-diff.js";
4
- function baseConfig(overrides = {}) {
5
- return {
6
- shellId: "shell_acme_prod",
7
- product: {
8
- name: "Acme",
9
- description: "Test",
10
- baseUrl: "https://app.acme.com",
11
- },
12
- auth: {
13
- strategy: "session-cookie",
14
- sessionFields: ["id"],
15
- guestAllowed: false,
16
- tokenExpirySeconds: 60,
17
- },
18
- routes: [],
19
- actions: [
20
- {
21
- id: "get_order",
22
- name: "Get Order",
23
- description: "Fetch order",
24
- method: "GET",
25
- path: "/api/orders",
26
- agentAccessible: false,
27
- sideEffects: false,
28
- sensitivityLevel: "high",
29
- params: [],
30
- requiresAuth: true,
31
- },
32
- ],
33
- deeplinks: [],
34
- agentPermissions: {
35
- defaultLevel: "none",
36
- requireUserConsent: true,
37
- allowedCallers: ["shell_partner_a"],
38
- },
39
- intershell_enabled: false,
40
- registry_visibility: "private",
41
- ...overrides,
42
- };
43
- }
44
- describe("computeManifestPrivilegeDiff", () => {
45
- it("treats missing live manifest as first push", () => {
46
- const diff = computeManifestPrivilegeDiff(baseConfig(), null);
47
- assert.equal(diff.isFirstPush, true);
48
- assert.equal(diff.hasPrivilegeIncrease, false);
49
- assert.equal(diff.deltas.length, 0);
50
- });
51
- it("detects agentAccessible flip as privilege increase", () => {
52
- const live = baseConfig();
53
- const candidate = baseConfig({
54
- actions: [
55
- {
56
- ...live.actions[0],
57
- agentAccessible: true,
58
- },
59
- ],
60
- });
61
- const diff = computeManifestPrivilegeDiff(candidate, live);
62
- assert.equal(diff.hasPrivilegeIncrease, true);
63
- assert.ok(diff.deltas.some((d) => d.kind === "agent_accessible_enabled"));
64
- });
65
- it("detects sensitivity downgrade", () => {
66
- const live = baseConfig();
67
- const candidate = baseConfig({
68
- actions: [
69
- {
70
- ...live.actions[0],
71
- sensitivityLevel: "low",
72
- },
73
- ],
74
- });
75
- const diff = computeManifestPrivilegeDiff(candidate, live);
76
- assert.ok(diff.deltas.some((d) => d.kind === "sensitivity_downgrade"));
77
- });
78
- it("detects baseUrl change", () => {
79
- const live = baseConfig();
80
- const candidate = baseConfig({
81
- product: { ...live.product, baseUrl: "https://new.acme.com" },
82
- });
83
- const diff = computeManifestPrivilegeDiff(candidate, live);
84
- assert.ok(diff.deltas.some((d) => d.kind === "base_url_change"));
85
- });
86
- it("detects allowedCallers widening to open", () => {
87
- const live = baseConfig({
88
- agentPermissions: {
89
- defaultLevel: "none",
90
- requireUserConsent: true,
91
- allowedCallers: ["shell_partner_a"],
92
- },
93
- });
94
- const candidate = baseConfig({
95
- agentPermissions: {
96
- defaultLevel: "none",
97
- requireUserConsent: true,
98
- allowedCallers: [],
99
- },
100
- });
101
- const diff = computeManifestPrivilegeDiff(candidate, live);
102
- assert.ok(diff.deltas.some((d) => d.kind === "allowed_callers_widened"));
103
- });
104
- });
105
- describe("detectDashboardNetworkReverts", () => {
106
- it("returns nothing on first push (no live manifest)", () => {
107
- assert.deepEqual(detectDashboardNetworkReverts(null, baseConfig()), []);
108
- });
109
- it("flags intershell going ON (dashboard) → OFF (config) — the drift footgun", () => {
110
- const live = baseConfig({ intershell_enabled: true, registry_visibility: "public" });
111
- const candidate = baseConfig({ intershell_enabled: false, registry_visibility: "public" });
112
- const reverts = detectDashboardNetworkReverts(live, candidate);
113
- assert.equal(reverts.length, 1);
114
- assert.match(reverts[0], /intershell_enabled/);
115
- });
116
- it("flags an omitted intershell (defaults false) against a live-ON dashboard", () => {
117
- // The config schema defaults intershell_enabled to false, so an omitted field reads as off.
118
- const live = baseConfig({ intershell_enabled: true });
119
- const candidate = baseConfig({ intershell_enabled: false });
120
- assert.equal(detectDashboardNetworkReverts(live, candidate).length, 1);
121
- });
122
- it("flags registry_visibility public → private", () => {
123
- const live = baseConfig({ registry_visibility: "public" });
124
- const candidate = baseConfig({ registry_visibility: "private" });
125
- const reverts = detectDashboardNetworkReverts(live, candidate);
126
- assert.equal(reverts.length, 1);
127
- assert.match(reverts[0], /registry_visibility/);
128
- });
129
- it("does not flag the enable direction (OFF → ON is a privilege increase, handled elsewhere)", () => {
130
- const live = baseConfig({ intershell_enabled: false, registry_visibility: "private" });
131
- const candidate = baseConfig({ intershell_enabled: true, registry_visibility: "public" });
132
- assert.deepEqual(detectDashboardNetworkReverts(live, candidate), []);
133
- });
134
- it("does not flag when config matches the dashboard (both ON)", () => {
135
- const live = baseConfig({ intershell_enabled: true, registry_visibility: "public" });
136
- const candidate = baseConfig({ intershell_enabled: true, registry_visibility: "public" });
137
- assert.deepEqual(detectDashboardNetworkReverts(live, candidate), []);
138
- });
139
- it("flags both settings when both would revert", () => {
140
- const live = baseConfig({ intershell_enabled: true, registry_visibility: "public" });
141
- const candidate = baseConfig({ intershell_enabled: false, registry_visibility: "private" });
142
- assert.equal(detectDashboardNetworkReverts(live, candidate).length, 2);
143
- });
144
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,24 +0,0 @@
1
- import { describe, it } from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { parseCurlCommand, parseCurlCollection } from './curl-parser.js';
4
- describe('curl-parser', () => {
5
- it('parses a simple GET curl command', () => {
6
- const req = parseCurlCommand("curl -X GET 'https://api.example.com/v1/orders'");
7
- assert.ok(req);
8
- assert.equal(req.method, 'GET');
9
- assert.equal(req.path, '/v1/orders');
10
- });
11
- it('parses POST with JSON body', () => {
12
- const req = parseCurlCommand('curl -X POST https://api.example.com/v1/orders -d \'{"sku":"ABC"}\'');
13
- assert.ok(req);
14
- assert.equal(req.method, 'POST');
15
- assert.deepEqual(req.body, { sku: 'ABC' });
16
- });
17
- it('parses a shell script with multiple curls', async () => {
18
- const content = `curl -X GET 'https://api.example.com/users'
19
- curl -X DELETE 'https://api.example.com/users/1'`;
20
- const result = await parseCurlCollection(content, 'api.sh');
21
- assert.equal(result.requestCount, 2);
22
- assert.equal(result.actions.length, 2);
23
- });
24
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,154 +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 { 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,22 +0,0 @@
1
- import type { ActionManifest } from "../../core/types.js";
2
- export interface PostProcessOptions {
3
- /**
4
- * When true (--yes / CI mode), auto-enable agentAccessible on GET/HEAD actions
5
- * with confidence ≥ 0.85 and sensitivity not high/critical.
6
- * Side-effect actions are always left as false regardless of this flag.
7
- */
8
- yesMode?: boolean;
9
- }
10
- /**
11
- * Apply deterministic post-processing rules to agent-detected actions.
12
- *
13
- * Rules applied in this order (agents cannot override them):
14
- * 1. POST/PUT/PATCH/DELETE → sideEffects = true
15
- * 2. GET/HEAD → sideEffects = false
16
- * 3. sensitivityLevel derived from method + path/name keywords when agent
17
- * left it as "none" (the default when no rule matched).
18
- * 4. [yesMode only] agentAccessible = true for safe GET/HEAD with confidence ≥ 0.85.
19
- *
20
- * Called in pipeline.ts after Stage 1 (parallel agents) completes.
21
- */
22
- export declare function applyDeterministicRules(actions: ActionManifest[], opts?: PostProcessOptions): ActionManifest[];
@@ -1,107 +0,0 @@
1
- // ============================================================
2
- // @duct/sdk — Deterministic Post-Processing
3
- // Applies method-based sideEffects enforcement and keyword-based
4
- // sensitivityLevel heuristics after the LLM agent stage.
5
- //
6
- // These rules are intentionally non-overridable by agents because
7
- // they derive from verifiable facts (HTTP method) rather than
8
- // LLM interpretation, making them a reliable safety net.
9
- // ============================================================
10
- const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
11
- const READ_METHODS = new Set(["GET", "HEAD"]);
12
- // Path/name/description fragments that imply high sensitivity
13
- const HIGH_SENSITIVITY_PATTERNS = [
14
- /\bpayment\b/i,
15
- /\bbilling\b/i,
16
- /\bcredit.?card\b/i,
17
- /\bbank\b/i,
18
- /\bssn\b/i,
19
- /\bpassword\b/i,
20
- /\bsecret\b/i,
21
- /\b(api.?)?token\b/i,
22
- /\badmin\b/i,
23
- /\bsuperuser\b/i,
24
- /\bpermission\b/i,
25
- /\brole\b/i,
26
- /\bgrant\b/i,
27
- /\brevoke\b/i,
28
- /\bdelete.?account\b/i,
29
- /\bpurge\b/i,
30
- ];
31
- // Path/name/description fragments that imply medium sensitivity
32
- const MEDIUM_SENSITIVITY_PATTERNS = [
33
- /\bprofile\b/i,
34
- /\baccount\b/i,
35
- /\buser\b/i,
36
- /\baddress\b/i,
37
- /\bcontact\b/i,
38
- /\bpersonal\b/i,
39
- /\bprivacy\b/i,
40
- /\bsettings\b/i,
41
- /\bpreferences\b/i,
42
- /\bsubscription\b/i,
43
- /\b(purchase.?order|sales.?order|work.?order)\b/i,
44
- /\bcheckout\b/i,
45
- /\bpurchase\b/i,
46
- ];
47
- function deriveSensitivityLevel(action) {
48
- // Keep agent's value when it already picked something meaningful
49
- if (action.sensitivityLevel && action.sensitivityLevel !== "none") {
50
- return action.sensitivityLevel;
51
- }
52
- const target = `${action.method} ${action.path} ${action.name} ${action.description}`;
53
- for (const pattern of HIGH_SENSITIVITY_PATTERNS) {
54
- if (pattern.test(target))
55
- return "high";
56
- }
57
- for (const pattern of MEDIUM_SENSITIVITY_PATTERNS) {
58
- if (pattern.test(target))
59
- return "medium";
60
- }
61
- // Write methods default to medium when no keyword matched
62
- if (WRITE_METHODS.has(action.method))
63
- return "medium";
64
- return "low";
65
- }
66
- /**
67
- * Apply deterministic post-processing rules to agent-detected actions.
68
- *
69
- * Rules applied in this order (agents cannot override them):
70
- * 1. POST/PUT/PATCH/DELETE → sideEffects = true
71
- * 2. GET/HEAD → sideEffects = false
72
- * 3. sensitivityLevel derived from method + path/name keywords when agent
73
- * left it as "none" (the default when no rule matched).
74
- * 4. [yesMode only] agentAccessible = true for safe GET/HEAD with confidence ≥ 0.85.
75
- *
76
- * Called in pipeline.ts after Stage 1 (parallel agents) completes.
77
- */
78
- export function applyDeterministicRules(actions, opts = {}) {
79
- return actions.map((action) => {
80
- let sideEffects;
81
- if (WRITE_METHODS.has(action.method)) {
82
- sideEffects = true;
83
- }
84
- else if (READ_METHODS.has(action.method)) {
85
- sideEffects = false;
86
- }
87
- else {
88
- sideEffects = action.sideEffects; // preserve agent's value for unknown methods
89
- }
90
- const sensitivityLevel = deriveSensitivityLevel(action);
91
- let { agentAccessible } = action;
92
- if (opts.yesMode) {
93
- // --yes mode: auto-enable for safe read-only actions with sufficient confidence.
94
- // Side-effect actions stay false — they require explicit human review.
95
- const isSafeRead = READ_METHODS.has(action.method) &&
96
- !sideEffects &&
97
- sensitivityLevel !== "high" &&
98
- sensitivityLevel !== "critical";
99
- // Treat missing confidence as 0 (unknown → don't auto-enable)
100
- const meetsConfidence = typeof action.confidence === "number" && action.confidence >= 0.85;
101
- if (isSafeRead && meetsConfidence) {
102
- agentAccessible = true;
103
- }
104
- }
105
- return { ...action, sideEffects, sensitivityLevel, agentAccessible };
106
- });
107
- }
@@ -1,35 +0,0 @@
1
- export interface PrismaField {
2
- name: string;
3
- type: string;
4
- isOptional: boolean;
5
- isId: boolean;
6
- isRelation: boolean;
7
- }
8
- export interface PrismaModel {
9
- name: string;
10
- fields: PrismaField[];
11
- /** Best candidate for a human-readable label field (first non-id String) */
12
- labelField?: string;
13
- }
14
- export interface PrismaParseResult {
15
- models: PrismaModel[];
16
- /** Pre-formatted annotation string for injection into agent prompt */
17
- annotation: string;
18
- }
19
- /**
20
- * Parse Prisma model definitions from a schema.prisma file.
21
- * Uses line-by-line parsing — handles standard Prisma syntax.
22
- */
23
- export declare function parsePrismaSchema(source: string): PrismaParseResult;
24
- /**
25
- * Build dataModel entity candidates from parsed Prisma models.
26
- * Called at push time to auto-populate `dataModel` in duct.config.ts.
27
- */
28
- export declare function buildDataModelFromPrisma(models: PrismaModel[]): Array<{
29
- id: string;
30
- label: string;
31
- discoveryAction: string;
32
- fetchAction: string;
33
- indexKey: string;
34
- labelKey: string;
35
- }>;
@@ -1,117 +0,0 @@
1
- // ============================================================
2
- // @duct/sdk — Prisma Schema Parser
3
- // Parses prisma/schema.prisma model definitions (no LLM).
4
- // Maps each model to a candidate dataModel entity and injects
5
- // field names into the API Agent prompt so it recognises CRUD
6
- // action params (e.g. title: z.string() maps to Post.title).
7
- // ============================================================
8
- // Prisma scalar types we care about for JSON Schema mapping
9
- const PRISMA_SCALAR_TYPES = new Set([
10
- "String", "Int", "Float", "Boolean", "DateTime", "Decimal", "BigInt", "Bytes", "Json",
11
- ]);
12
- /**
13
- * Parse Prisma model definitions from a schema.prisma file.
14
- * Uses line-by-line parsing — handles standard Prisma syntax.
15
- */
16
- export function parsePrismaSchema(source) {
17
- const models = [];
18
- const lines = source.split("\n");
19
- let i = 0;
20
- while (i < lines.length) {
21
- const line = lines[i].trim();
22
- // Match: model ModelName {
23
- const modelMatch = /^model\s+(\w+)\s*\{/.exec(line);
24
- if (!modelMatch) {
25
- i++;
26
- continue;
27
- }
28
- const modelName = modelMatch[1];
29
- const fields = [];
30
- i++;
31
- // Parse fields until closing brace
32
- while (i < lines.length) {
33
- const fieldLine = lines[i].trim();
34
- if (fieldLine === "}" || fieldLine.startsWith("}"))
35
- break;
36
- // Skip comments, blank lines, @@-level attributes
37
- if (!fieldLine || fieldLine.startsWith("//") || fieldLine.startsWith("@@")) {
38
- i++;
39
- continue;
40
- }
41
- // Field pattern: fieldName FieldType [?] [@attributes...]
42
- // e.g.: id String @id @default(cuid())
43
- // e.g.: title String
44
- // e.g.: orders Order[]
45
- const fieldMatch = /^(\w+)\s+(\w+)(\[\])?\s*(\?)?/.exec(fieldLine);
46
- if (!fieldMatch) {
47
- i++;
48
- continue;
49
- }
50
- const fieldName = fieldMatch[1];
51
- const fieldType = fieldMatch[2];
52
- const isArray = Boolean(fieldMatch[3]);
53
- const isOptional = Boolean(fieldMatch[4]);
54
- const isRelation = !PRISMA_SCALAR_TYPES.has(fieldType);
55
- const isId = /@id\b/.test(fieldLine);
56
- // Skip array relations (one-to-many) — not useful as action params
57
- if (isArray && isRelation) {
58
- i++;
59
- continue;
60
- }
61
- fields.push({ name: fieldName, type: fieldType, isOptional, isId, isRelation });
62
- i++;
63
- }
64
- if (fields.length > 0) {
65
- // Find the best labelField: first non-id String field
66
- const labelField = fields.find((f) => f.type === "String" && !f.isId && !f.isRelation)?.name;
67
- models.push({ name: modelName, fields, labelField });
68
- }
69
- i++;
70
- }
71
- return {
72
- models,
73
- annotation: formatPrismaAnnotation(models),
74
- };
75
- }
76
- function formatPrismaAnnotation(models) {
77
- if (models.length === 0)
78
- return "";
79
- const lines = ["// PRISMA_MODELS — use these field names for CRUD action params:"];
80
- for (const model of models) {
81
- lines.push(`// Model "${model.name}":`);
82
- const scalarFields = model.fields.filter((f) => !f.isRelation);
83
- for (const field of scalarFields) {
84
- const tag = field.isId ? " (id)" : field.isOptional ? " (optional)" : " (required)";
85
- lines.push(`// ${field.name}: ${field.type}${tag}`);
86
- }
87
- if (model.labelField) {
88
- lines.push(`// → label field: "${model.labelField}"`);
89
- }
90
- }
91
- return lines.join("\n");
92
- }
93
- /**
94
- * Build dataModel entity candidates from parsed Prisma models.
95
- * Called at push time to auto-populate `dataModel` in duct.config.ts.
96
- */
97
- export function buildDataModelFromPrisma(models) {
98
- return models.map((model) => {
99
- const snakeId = toSnakeCase(model.name);
100
- const idField = model.fields.find((f) => f.isId)?.name ?? "id";
101
- return {
102
- id: snakeId,
103
- label: model.name,
104
- discoveryAction: `list_${snakeId}`,
105
- fetchAction: `get_${snakeId}`,
106
- indexKey: idField,
107
- labelKey: model.labelField ?? idField,
108
- };
109
- });
110
- }
111
- function toSnakeCase(str) {
112
- return str
113
- .replace(/([A-Z])/g, "_$1")
114
- .toLowerCase()
115
- .replace(/^_/, "")
116
- .replace(/_+/g, "_");
117
- }
@@ -1,33 +0,0 @@
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;