@duct-sdk/sdk 0.1.7 → 0.1.13

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 (58) hide show
  1. package/README.md +3 -3
  2. package/dist/adapters/next/index.d.ts +1 -1
  3. package/dist/adapters/next/shell.d.ts +55 -1
  4. package/dist/adapters/next/shell.js +100 -17
  5. package/dist/adapters/react/index.d.ts +5 -1
  6. package/dist/adapters/react/index.js +2 -0
  7. package/dist/adapters/react/shell.d.ts +61 -1
  8. package/dist/adapters/react/shell.js +110 -16
  9. package/dist/adapters/react/use-page-context.d.ts +32 -0
  10. package/dist/adapters/react/use-page-context.js +99 -0
  11. package/dist/cli/agents/api-agent.d.ts +9 -3
  12. package/dist/cli/agents/api-agent.js +163 -69
  13. package/dist/cli/agents/auth-agent.d.ts +2 -1
  14. package/dist/cli/agents/auth-agent.js +38 -24
  15. package/dist/cli/agents/deeplink-agent.js +71 -49
  16. package/dist/cli/agents/llm.d.ts +1 -1
  17. package/dist/cli/agents/llm.js +48 -15
  18. package/dist/cli/agents/pipeline.d.ts +16 -0
  19. package/dist/cli/agents/pipeline.js +18 -5
  20. package/dist/cli/agents/reviewer-agent.js +46 -46
  21. package/dist/cli/agents/route-agent.d.ts +3 -1
  22. package/dist/cli/agents/route-agent.js +70 -44
  23. package/dist/cli/detectors/topology.d.ts +26 -0
  24. package/dist/cli/detectors/topology.js +310 -0
  25. package/dist/cli/drift.d.ts +11 -0
  26. package/dist/cli/drift.js +147 -2
  27. package/dist/cli/fs/sandbox.d.ts +2 -0
  28. package/dist/cli/fs/sandbox.js +22 -8
  29. package/dist/cli/generators/config.d.ts +13 -0
  30. package/dist/cli/generators/config.js +200 -50
  31. package/dist/cli/generators/receiver.js +728 -601
  32. package/dist/cli/generators/shell.js +532 -490
  33. package/dist/cli/index.js +502 -19
  34. package/dist/cli/init.d.ts +11 -1
  35. package/dist/cli/init.js +367 -31
  36. package/dist/cli/processors/postprocess.d.ts +22 -0
  37. package/dist/cli/processors/postprocess.js +107 -0
  38. package/dist/cli/processors/prisma-parser.d.ts +35 -0
  39. package/dist/cli/processors/prisma-parser.js +117 -0
  40. package/dist/cli/processors/zod-extractor.d.ts +27 -0
  41. package/dist/cli/processors/zod-extractor.js +153 -0
  42. package/dist/cli/prompts/review.d.ts +32 -0
  43. package/dist/cli/prompts/review.js +240 -0
  44. package/dist/cli/selectors/index.d.ts +22 -0
  45. package/dist/cli/selectors/index.js +274 -0
  46. package/dist/core/config.d.ts +18 -18
  47. package/dist/core/endpoints.d.ts +1 -0
  48. package/dist/core/endpoints.js +4 -0
  49. package/dist/core/introspect.d.ts +47 -0
  50. package/dist/core/introspect.js +94 -0
  51. package/dist/core/status.d.ts +39 -0
  52. package/dist/core/status.js +40 -0
  53. package/dist/core/token.d.ts +36 -1
  54. package/dist/core/token.js +43 -2
  55. package/dist/core/types.d.ts +114 -0
  56. package/dist/index.d.ts +9 -2
  57. package/dist/index.js +6 -1
  58. package/package.json +84 -84
package/dist/cli/init.js CHANGED
@@ -12,12 +12,17 @@ import inquirer from "inquirer";
12
12
  import { SandboxFS } from "./fs/sandbox.js";
13
13
  import { detectFramework } from "./detectors/framework.js";
14
14
  import { detectAuth } from "./detectors/auth.js";
15
+ import { discoverTopology } from "./detectors/topology.js";
16
+ import { buildReadList } from "./selectors/index.js";
17
+ import { parsePrismaSchema, buildDataModelFromPrisma } from "./processors/prisma-parser.js";
15
18
  import { runAgentPipeline, DuctPipelineEmitter, } from "./agents/pipeline.js";
16
- import { generateConfigFile } from "./generators/config.js";
19
+ import { runInteractiveReview } from "./prompts/review.js";
20
+ import { generateConfigFile, generateManualTemplate } from "./generators/config.js";
17
21
  import { generateReceiver, generateTokenRoute, } from "./generators/receiver.js";
18
22
  import { generateShell, generateEnvTemplateForFramework, getEnvTemplateName, } from "./generators/shell.js";
19
- import { getActiveApiBase, getConfiguredDashboard, getManifestApiBases, } from "../core/endpoints.js";
23
+ import { getActiveAuthBase, getConfiguredDashboard, getManifestApiBases, } from "../core/endpoints.js";
20
24
  import { fileURLToPath } from "node:url";
25
+ import { exec } from "child_process";
21
26
  const pkgPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../package.json");
22
27
  const VERSION = JSON.parse(await fs.readFile(pkgPath, "utf-8")).version;
23
28
  // ----------------------------------------------------------------
@@ -33,13 +38,34 @@ async function loadAuth() {
33
38
  return null;
34
39
  }
35
40
  }
36
- /** Fetch the company's provisioned shells from the Duct API. */
37
- async function fetchAccountShells(apiKey, ductApiBase) {
38
- const res = await fetch(`${ductApiBase}/v1/account/shells`, {
39
- headers: { Authorization: `Bearer ${apiKey}` },
40
- });
41
- if (!res.ok)
42
- return [];
41
+ /**
42
+ * Fetch the company's provisioned shells from the Duct auth service.
43
+ *
44
+ * Account/identity endpoints live on the auth service (port 3001 locally,
45
+ * auth.<host> in prod), NOT on the agent-proxy. Calling the wrong service
46
+ * was the root cause of a "No shells provisioned" false negative bug.
47
+ */
48
+ async function fetchAccountShells(apiKey, authBase) {
49
+ const url = `${authBase}/v1/account/shells`;
50
+ let res;
51
+ try {
52
+ res = await fetch(url, {
53
+ headers: { Authorization: `Bearer ${apiKey}` },
54
+ });
55
+ }
56
+ catch (err) {
57
+ const message = err instanceof Error ? err.message : String(err);
58
+ throw new Error(`Could not reach Duct auth service at ${authBase} (${message})`);
59
+ }
60
+ if (res.status === 401 || res.status === 403) {
61
+ throw new Error(`Duct auth rejected your API key (HTTP ${res.status}). ` +
62
+ `Re-run \`npx duct login\` to refresh credentials.`);
63
+ }
64
+ if (!res.ok) {
65
+ const body = await res.text().catch(() => "");
66
+ throw new Error(`Duct auth returned HTTP ${res.status} from ${url}` +
67
+ (body ? ` — ${body.slice(0, 200)}` : ""));
68
+ }
43
69
  const data = await res.json();
44
70
  return data.shells ?? [];
45
71
  }
@@ -85,6 +111,7 @@ function hasAnyLlmCredential() {
85
111
  "OPENAI_API_KEY",
86
112
  "GEMINI_API_KEY",
87
113
  "GROQ_API_KEY",
114
+ "XAI_API_KEY",
88
115
  "OPENROUTER_API_KEY",
89
116
  "DUCT_API_KEY",
90
117
  ];
@@ -103,7 +130,8 @@ async function checkLlmCredentialsAndPrompt(noAgents, yes) {
103
130
  console.log(chalk.gray(" • ANTHROPIC_API_KEY (Anthropic Claude)"));
104
131
  console.log(chalk.gray(" • OPENAI_API_KEY (OpenAI)"));
105
132
  console.log(chalk.gray(" • GEMINI_API_KEY (Google Gemini)"));
106
- console.log(chalk.gray(" • GROQ_API_KEY (Groq)"));
133
+ console.log(chalk.gray(" • GROQ_API_KEY (Groq — groq.com)"));
134
+ console.log(chalk.gray(" • XAI_API_KEY (Grok — xAI / api.x.ai)"));
107
135
  console.log(chalk.gray(" • OPENROUTER_API_KEY (OpenRouter)"));
108
136
  console.log(chalk.gray(" • DUCT_API_KEY (Duct hosted)"));
109
137
  console.log(chalk.gray(" Set LLM_MODEL to the model name you want to use.\n"));
@@ -174,14 +202,40 @@ async function detectLogoUrl(projectRoot) {
174
202
  }
175
203
  return undefined;
176
204
  }
177
- function buildDuctConfigFromPipeline(result, shellId, productName, baseUrl, logoUrl) {
205
+ /**
206
+ * Auto-detect the product industry from package.json dependencies.
207
+ * Returns a best-guess string or undefined when nothing matches.
208
+ */
209
+ function detectIndustryFromDeps(deps) {
210
+ const allDeps = Object.keys(deps).join(" ").toLowerCase();
211
+ if (/stripe|braintree|adyen|plaid|square|paypal|razorpay|lemon/.test(allDeps))
212
+ return "fintech";
213
+ if (/shopify|woocommerce|medusa|saleor|commercetools|stripe.*checkout/.test(allDeps))
214
+ return "ecommerce";
215
+ if (/contentful|sanity|prismic|strapi|payload/.test(allDeps))
216
+ return "cms";
217
+ if (/sendgrid|postmark|mailchimp|resend|nodemailer/.test(allDeps))
218
+ return "email-saas";
219
+ if (/twilio|vonage|messagebird|telnyx/.test(allDeps))
220
+ return "communications";
221
+ if (/aws-sdk|@aws-sdk|firebase|supabase/.test(allDeps))
222
+ return "saas";
223
+ if (/openai|anthropic|langchain|huggingface/.test(allDeps))
224
+ return "ai";
225
+ if (/segment|mixpanel|amplitude|posthog/.test(allDeps))
226
+ return "analytics";
227
+ return undefined;
228
+ }
229
+ function buildDuctConfigFromPipeline(result, shellId, productName, baseUrl, logoUrl, apiBaseUrl, industry, dataModel) {
178
230
  return {
179
231
  shellId,
180
232
  product: {
181
233
  name: productName,
182
234
  description: `${productName} — AI-powered interaction shell`,
183
235
  baseUrl,
236
+ ...(apiBaseUrl ? { apiBaseUrl } : {}),
184
237
  ...(logoUrl ? { logoUrl } : {}),
238
+ ...(industry ? { industry } : {}),
185
239
  },
186
240
  auth: result.auth,
187
241
  routes: result.routes,
@@ -194,6 +248,7 @@ function buildDuctConfigFromPipeline(result, shellId, productName, baseUrl, logo
194
248
  widget: {
195
249
  position: "bottom-right",
196
250
  },
251
+ ...(dataModel && dataModel.entities.length > 0 ? { dataModel } : {}),
197
252
  };
198
253
  }
199
254
  async function writeFile(filePath, content, dryRun) {
@@ -215,6 +270,26 @@ async function fileExists(filePath) {
215
270
  return false;
216
271
  }
217
272
  }
273
+ /**
274
+ * Returns relative paths of files changed in git since HEAD.
275
+ * Combines unstaged changes, staged changes, and untracked files.
276
+ * Returns null if the directory is not a git repo or git is unavailable.
277
+ */
278
+ async function getGitChangedFiles(cwd) {
279
+ return new Promise((resolve) => {
280
+ exec("git diff --name-only HEAD && git ls-files --others --exclude-standard", { cwd, timeout: 10_000 }, (err, stdout) => {
281
+ if (err) {
282
+ resolve(null);
283
+ return;
284
+ }
285
+ const files = stdout
286
+ .split("\n")
287
+ .map((f) => f.trim())
288
+ .filter(Boolean);
289
+ resolve(files.length > 0 ? files : null);
290
+ });
291
+ });
292
+ }
218
293
  function isIgnoredScanDir(name) {
219
294
  return [
220
295
  ".git",
@@ -451,7 +526,10 @@ async function promptMonorepoRoots(frontendRoot, backendRoot) {
451
526
  * This is the main entry point for `npx duct init`.
452
527
  */
453
528
  export async function runInit(opts = {}) {
454
- const { cwd = process.cwd(), noAgents = false, dryRun = false, yes = false, } = opts;
529
+ const { cwd = process.cwd(), dryRun = false, yes = false, noInteractive = false, } = opts;
530
+ // noAgents is mutable: manual mode implies no agents, and LLM credential check can
531
+ // downgrade to no-agents when credentials are missing and user confirms blank template.
532
+ let noAgents = (opts.noAgents ?? false) || (opts.manual ?? false);
455
533
  console.log(chalk.bold(`\n ◆ Duct · v${VERSION}`));
456
534
  console.log(chalk.gray(" Shell infrastructure for humans and agents."));
457
535
  console.log(chalk.gray(" ─────────────────────────────────────────────────────────────\n"));
@@ -506,17 +584,25 @@ export async function runInit(opts = {}) {
506
584
  process.exit(1);
507
585
  }
508
586
  console.log(chalk.gray(` Authenticated as ${auth.email} (${auth.slug})\n`));
509
- // Use saved auth endpoints (or production defaults)
510
- const ductApiBase = getActiveApiBase(auth);
511
- // Fetch company's provisioned shells
512
- const accountShells = await fetchAccountShells(auth.token, ductApiBase);
587
+ // Use saved auth endpoints (or production defaults).
588
+ // Account/identity endpoints live on the auth service, not agent-proxy.
589
+ const ductAuthBase = getActiveAuthBase(auth);
590
+ // Fetch company's provisioned shells from the auth service.
591
+ // (Account/identity endpoints live on auth, not on agent-proxy.)
592
+ let accountShells;
593
+ try {
594
+ accountShells = await fetchAccountShells(auth.token, ductAuthBase);
595
+ }
596
+ catch (err) {
597
+ const message = err instanceof Error ? err.message : String(err);
598
+ console.log(chalk.red(` Failed to list shells: ${message}\n`));
599
+ process.exit(1);
600
+ }
513
601
  // ---- Step 0.5: Check LLM credentials and prompt if missing ----
514
602
  if (!noAgents) {
515
- const shouldRunAgents = await checkLlmCredentialsAndPrompt(noAgents, yes);
516
- if (!shouldRunAgents) {
517
- // User either explicitly requested no agents or confirmed blank template mode
518
- // (in checkLlmCredentialsAndPrompt, if no credentials and not already noAgents,
519
- // we already prompted and the user confirmed or declined)
603
+ const canRunAgents = await checkLlmCredentialsAndPrompt(noAgents, yes);
604
+ if (!canRunAgents) {
605
+ noAgents = true;
520
606
  }
521
607
  }
522
608
  // ---- Step 1: Detect framework ----
@@ -575,25 +661,38 @@ export async function runInit(opts = {}) {
575
661
  console.log(chalk.yellow(" Falling back to Next.js App Router. Re-run init and choose a stack manually if this is incorrect."));
576
662
  }
577
663
  }
578
- // ---- Step 2: Detect auth (fast, no LLM) ----
579
- const authSpinner = ora("Detecting auth system...").start();
664
+ // ---- Step 2: Project structure + auth detection ----
580
665
  const sandboxFs = new SandboxFS(projectRoot);
666
+ const topoSpinner = ora("Scanning project structure...").start();
667
+ const topo = await discoverTopology(projectRoot);
668
+ topoSpinner.succeed(`Detected: ${topo.language}${topo.isMonorepo ? " · monorepo" : ""}`);
669
+ const authSpinner = ora("Detecting auth system...").start();
581
670
  const authDetection = await detectAuth(sandboxFs);
582
671
  authSpinner.succeed(`Auth detected: ${authDisplay(authDetection.system)}`);
583
672
  // ---- Step 3: Gather basic info ----
584
673
  let shellId;
585
674
  let productName;
586
675
  let baseUrl;
587
- // Try to read from existing config if updating
676
+ let apiBaseUrl = opts.apiUrl;
677
+ let industry = opts.industry;
678
+ // ---- Update mode: restrict readList to files changed since last push ----
679
+ // Uses `git diff --name-only HEAD` to find changed files, then filters the
680
+ // full selector output to only those files. The pipeline then only sees
681
+ // what changed — dramatically faster for large codebases.
588
682
  if (opts.update) {
589
683
  const existingConfigPath = path.join(projectRoot, "duct.config.ts");
590
684
  if (await fileExists(existingConfigPath)) {
591
- console.log(chalk.gray(" Updating existing duct.config.ts..."));
685
+ console.log(chalk.gray(" Updating existing duct.config.ts — scanning changed files...\n"));
592
686
  }
593
687
  }
594
688
  const pkg = await sandboxFs.readJSON("package.json");
595
689
  const defaultProductName = pkg?.name?.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()) ??
596
690
  "My App";
691
+ // Auto-detect industry from package.json deps if not provided
692
+ if (!industry && pkg) {
693
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
694
+ industry = detectIndustryFromDeps(allDeps);
695
+ }
597
696
  // ---- Resolve shell ID from Duct account (never user-typed) ----
598
697
  if (!auth) {
599
698
  console.log(chalk.red(" Not logged in.\n"));
@@ -662,12 +761,100 @@ export async function runInit(opts = {}) {
662
761
  ]);
663
762
  productName = answers.productName;
664
763
  baseUrl = answers.baseUrl;
764
+ // --api-url prompt: ask if the API is on a different domain (skip if --api-url already set)
765
+ if (!apiBaseUrl) {
766
+ const { hasSeparateApi } = await inquirer.prompt([
767
+ {
768
+ type: "confirm",
769
+ name: "hasSeparateApi",
770
+ message: "Is your API hosted on a different domain from the frontend?",
771
+ default: false,
772
+ },
773
+ ]);
774
+ if (hasSeparateApi) {
775
+ const { enteredApiUrl } = await inquirer.prompt([
776
+ {
777
+ type: "input",
778
+ name: "enteredApiUrl",
779
+ message: "API base URL (e.g., https://api.example.com):",
780
+ validate: (v) => {
781
+ try {
782
+ new URL(v);
783
+ return true;
784
+ }
785
+ catch {
786
+ return "Must be a valid URL";
787
+ }
788
+ },
789
+ },
790
+ ]);
791
+ apiBaseUrl = enteredApiUrl;
792
+ }
793
+ }
794
+ }
795
+ // ---- Step 3.5: Auto-detect dataModel from Prisma schema (no LLM) ----
796
+ let prismaDataModel;
797
+ const prismaSchemaSource = await sandboxFs.readFile("prisma/schema.prisma");
798
+ if (prismaSchemaSource) {
799
+ const { models } = parsePrismaSchema(prismaSchemaSource);
800
+ const entities = buildDataModelFromPrisma(models);
801
+ if (entities.length > 0) {
802
+ prismaDataModel = { entities };
803
+ console.log(chalk.gray(` Prisma schema detected — auto-populated ${entities.length} dataModel entit${entities.length === 1 ? "y" : "ies"}\n`));
804
+ }
665
805
  }
666
806
  // ---- Step 4: Run agent pipeline ----
667
807
  let pipelineResult;
808
+ // Load --api-spec file content if provided
809
+ let apiSpecContent;
810
+ const apiSpecPath = opts.apiSpec ? path.resolve(cwd, opts.apiSpec) : undefined;
811
+ if (apiSpecPath) {
812
+ try {
813
+ apiSpecContent = await fs.readFile(apiSpecPath, "utf-8");
814
+ console.log(chalk.gray(` Using OpenAPI spec: ${path.relative(cwd, apiSpecPath)} — skipping Route + API agents\n`));
815
+ }
816
+ catch {
817
+ console.log(chalk.yellow(` ⚠ Could not read --api-spec file: ${opts.apiSpec}. Falling back to agent scan.\n`));
818
+ }
819
+ }
820
+ // Build a bounded file list before running agents so each agent
821
+ // receives targeted files as priority context instead of scanning broadly.
822
+ let readList = !noAgents ? await buildReadList(topo, sandboxFs) : undefined;
823
+ // In update mode, further restrict the readList to only files changed since HEAD.
824
+ // This makes re-scans dramatically faster for large codebases.
825
+ if (opts.update && readList) {
826
+ const changedFiles = await getGitChangedFiles(projectRoot);
827
+ if (changedFiles && changedFiles.length > 0) {
828
+ const changedSet = new Set(changedFiles);
829
+ const filter = (files) => files.filter((f) => changedSet.has(f) || changedSet.has(path.relative(projectRoot, f)));
830
+ readList = {
831
+ routeFiles: filter(readList.routeFiles),
832
+ apiFiles: filter(readList.apiFiles),
833
+ authFiles: filter(readList.authFiles),
834
+ };
835
+ const total = readList.routeFiles.length + readList.apiFiles.length + readList.authFiles.length;
836
+ if (total === 0) {
837
+ console.log(chalk.gray(" No changed files match your manifest file types — nothing to re-scan.\n"));
838
+ }
839
+ else {
840
+ console.log(chalk.gray(` --update: scanning ${total} changed file(s) from git diff\n`));
841
+ }
842
+ }
843
+ else {
844
+ console.log(chalk.gray(" --update: no changed files detected (git diff is clean)\n"));
845
+ }
846
+ }
668
847
  if (noAgents) {
669
- console.log(chalk.yellow("\n Skipping agent pipeline (--no-agents)"));
670
- console.log(chalk.gray(" You'll get a blank template to fill in manually.\n"));
848
+ const isManual = Boolean(opts.manual ?? false) || process.argv.includes("--manual");
849
+ if (isManual) {
850
+ console.log(chalk.yellow("\n Running in manual mode — no LLM agents"));
851
+ console.log(chalk.gray(` Detected: ${topo.framework} · ${topo.language} · auth: ${topo.authLib}`));
852
+ console.log(chalk.gray(" Generating pre-filled template. Review and run `duct push` when ready.\n"));
853
+ }
854
+ else {
855
+ console.log(chalk.yellow("\n Skipping agent pipeline (--no-agents)"));
856
+ console.log(chalk.gray(" You'll get a template with detected framework/auth pre-filled.\n"));
857
+ }
671
858
  pipelineResult = {
672
859
  routes: [],
673
860
  actions: [],
@@ -726,8 +913,24 @@ export async function runInit(opts = {}) {
726
913
  });
727
914
  const pipelineSpinner = ora({ text: "Running pipeline...", prefixText: " " }).start();
728
915
  try {
729
- pipelineResult = await runAgentPipeline(sandboxFs, { emitter });
916
+ pipelineResult = await runAgentPipeline(sandboxFs, {
917
+ emitter,
918
+ readList,
919
+ ...(apiSpecContent ? { apiSpecContent, apiSpecPath: opts.apiSpec } : {}),
920
+ postProcess: { yesMode: yes },
921
+ });
730
922
  pipelineSpinner.stop();
923
+ if (pipelineResult.actions.length === 0) {
924
+ const apiFileCount = readList?.apiFiles.length ?? 0;
925
+ console.log(chalk.yellow("\n ⚠ No API actions detected"));
926
+ console.log(chalk.gray(" The agents scanned your project but found no API endpoints."));
927
+ console.log(chalk.gray(" This often means your API files are in a non-standard location."));
928
+ console.log(chalk.gray("\n Suggestions:"));
929
+ console.log(chalk.gray(` • ${apiFileCount} API file(s) were scanned — check they contain handler functions`));
930
+ console.log(chalk.gray(" • Use --manual to fill in actions yourself (no AI needed)"));
931
+ console.log(chalk.gray(" • Ensure your route handlers are in app/api/, pages/api/, routes/, or controllers/"));
932
+ console.log(chalk.gray(" • Check that ANTHROPIC_API_KEY / LLM_MODEL are set correctly for better detection\n"));
933
+ }
731
934
  }
732
935
  catch (err) {
733
936
  pipelineSpinner.fail("Pipeline failed");
@@ -750,6 +953,24 @@ export async function runInit(opts = {}) {
750
953
  console.log(chalk.blue(` • ${suggestion}`));
751
954
  }
752
955
  }
956
+ // ---- Step 5.5: Per-action agent-accessibility review ----
957
+ // Run only when agents produced results (skip for blank template).
958
+ let reviewedPipelineResult = pipelineResult;
959
+ if (!noAgents && pipelineResult.actions.length > 0) {
960
+ const reviewed = await runInteractiveReview(pipelineResult, {
961
+ yes,
962
+ noInteractive,
963
+ cwd: projectRoot,
964
+ });
965
+ // Merge reviewed actions back into the pipeline result for file generation
966
+ reviewedPipelineResult = {
967
+ ...pipelineResult,
968
+ actions: reviewed.actions,
969
+ routes: reviewed.routes,
970
+ deeplinks: reviewed.deeplinks,
971
+ auth: reviewed.auth,
972
+ };
973
+ }
753
974
  // Show what will be generated
754
975
  const outputPaths = getOutputPaths(projectRoot, framework);
755
976
  console.log(chalk.bold("\n Writing files to your project\n"));
@@ -774,10 +995,81 @@ export async function runInit(opts = {}) {
774
995
  return;
775
996
  }
776
997
  }
998
+ // ---- Step 6.5: Incremental merge for --update mode ----
999
+ // If a previous manifest snapshot exists, preserve unchanged items and
1000
+ // only surface new/changed detections. This prevents a full overwrite of
1001
+ // carefully-configured actions that were not in the changed-file set.
1002
+ if (opts.update) {
1003
+ const manifestSnapshotPath = path.join(projectRoot, ".duct-manifest.json");
1004
+ let existingConfig = null;
1005
+ try {
1006
+ const raw = await fs.readFile(manifestSnapshotPath, "utf-8");
1007
+ existingConfig = JSON.parse(raw);
1008
+ }
1009
+ catch { /* no snapshot yet — full write on first run */ }
1010
+ if (existingConfig) {
1011
+ // Build lookup keys for existing items
1012
+ const existingActionKeys = new Map((existingConfig.actions ?? []).map((a) => [`${a.method}:${a.path}`, a]));
1013
+ const existingRouteKeys = new Map((existingConfig.routes ?? []).map((r) => [r.path, r]));
1014
+ const existingDeeplinkKeys = new Map((existingConfig.deeplinks ?? []).map((d) => [d.id, d]));
1015
+ // Merge actions: new detections override by method+path; existing not in new detections are kept
1016
+ const newActionKeys = new Set(reviewedPipelineResult.actions.map((a) => `${a.method}:${a.path}`));
1017
+ const preservedActions = (existingConfig.actions ?? []).filter((a) => !newActionKeys.has(`${a.method}:${a.path}`));
1018
+ // Count what changed for reporting
1019
+ let newCount = 0;
1020
+ let changedCount = 0;
1021
+ for (const a of reviewedPipelineResult.actions) {
1022
+ const key = `${a.method}:${a.path}`;
1023
+ if (!existingActionKeys.has(key))
1024
+ newCount++;
1025
+ else
1026
+ changedCount++;
1027
+ }
1028
+ const mergedActions = [...preservedActions, ...reviewedPipelineResult.actions];
1029
+ // Merge routes: preserve routes not touched by scan; add/update scanned routes
1030
+ const newRouteKeys = new Set(reviewedPipelineResult.routes.map((r) => r.path));
1031
+ const preservedRoutes = (existingConfig.routes ?? []).filter((r) => !newRouteKeys.has(r.path));
1032
+ const mergedRoutes = [...preservedRoutes, ...reviewedPipelineResult.routes];
1033
+ // Merge deeplinks: preserve deeplinks not touched; add/update new ones
1034
+ const newDeeplinkKeys = new Set(reviewedPipelineResult.deeplinks.map((d) => d.id));
1035
+ const preservedDeeplinks = (existingConfig.deeplinks ?? []).filter((d) => !newDeeplinkKeys.has(d.id));
1036
+ const mergedDeeplinks = [...preservedDeeplinks, ...reviewedPipelineResult.deeplinks];
1037
+ // Preserve existing auth if pipeline didn't produce better detections
1038
+ const mergedAuth = reviewedPipelineResult.auth.strategy !== "unknown"
1039
+ ? reviewedPipelineResult.auth
1040
+ : (existingConfig.auth ?? reviewedPipelineResult.auth);
1041
+ reviewedPipelineResult = {
1042
+ ...reviewedPipelineResult,
1043
+ actions: mergedActions,
1044
+ routes: mergedRoutes,
1045
+ deeplinks: mergedDeeplinks,
1046
+ auth: mergedAuth,
1047
+ };
1048
+ const totalDrift = newCount + changedCount;
1049
+ if (totalDrift === 0) {
1050
+ console.log(chalk.green("\n ✓ No drift detected — existing manifest is up to date.\n"));
1051
+ return;
1052
+ }
1053
+ console.log(chalk.bold(`\n Merge results: ${newCount} new action(s), ${changedCount} updated, ${preservedActions.length} preserved\n`));
1054
+ // Suppress unused variable warnings
1055
+ void existingRouteKeys;
1056
+ void existingDeeplinkKeys;
1057
+ }
1058
+ }
777
1059
  // ---- Step 7: Write files ----
778
- const logoUrl = await detectLogoUrl(cwd);
779
- const config = buildDuctConfigFromPipeline(pipelineResult, shellId, productName, baseUrl, logoUrl);
780
- const configContent = generateConfigFile(config);
1060
+ const logoUrl = await detectLogoUrl(projectRoot);
1061
+ const config = buildDuctConfigFromPipeline(reviewedPipelineResult, shellId, productName, baseUrl, logoUrl, apiBaseUrl, industry, prismaDataModel);
1062
+ const isManualMode = Boolean(opts.manual) || process.argv.includes("--manual");
1063
+ const configContent = (noAgents && isManualMode)
1064
+ ? generateManualTemplate({
1065
+ shellId,
1066
+ productName,
1067
+ baseUrl,
1068
+ authStrategy: authDetection.system,
1069
+ framework: topo.framework,
1070
+ logoUrl,
1071
+ })
1072
+ : generateConfigFile(config);
781
1073
  const receiverContent = generateReceiver(config, framework);
782
1074
  const tokenRouteContent = generateTokenRoute(config, framework);
783
1075
  const shellContent = generateShell(config, framework);
@@ -803,7 +1095,51 @@ export async function runInit(opts = {}) {
803
1095
  await writeFile(outputPaths.envTemplatePath, envContent, dryRun);
804
1096
  }
805
1097
  if (!dryRun) {
1098
+ // ---- Write manifest snapshot for future --update runs ----
1099
+ const manifestSnapshotPath = path.join(projectRoot, ".duct-manifest.json");
1100
+ try {
1101
+ await fs.writeFile(manifestSnapshotPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
1102
+ }
1103
+ catch { /* non-fatal */ }
1104
+ // ---- Post-write validation: env var completeness ----
1105
+ const isNextJs = framework.name === "next-app" || framework.name === "next-pages";
1106
+ if (isNextJs) {
1107
+ try {
1108
+ const envContent2 = await fs.readFile(outputPaths.envTemplatePath, "utf-8");
1109
+ if (!envContent2.includes("NEXT_PUBLIC_DUCT_SHELL_ID")) {
1110
+ await fs.appendFile(outputPaths.envTemplatePath, "\n# Client-side shell ID (required for DuctShell component)\nNEXT_PUBLIC_DUCT_SHELL_ID=${DUCT_SHELL_ID}\n", "utf-8");
1111
+ console.log(chalk.gray(" Added NEXT_PUBLIC_DUCT_SHELL_ID to env template.\n"));
1112
+ }
1113
+ }
1114
+ catch { /* non-fatal */ }
1115
+ }
1116
+ // ---- Post-write validation: token endpoint path ----
1117
+ const expectedTokenPath = "/api/duct/token";
1118
+ const configuredTokenPath = reviewedPipelineResult.auth.tokenEndpoint;
1119
+ if (configuredTokenPath && configuredTokenPath !== expectedTokenPath) {
1120
+ console.log(chalk.yellow(` ⚠ Token endpoint mismatch: config says '${configuredTokenPath}' but generated route is at '${expectedTokenPath}'`));
1121
+ console.log(chalk.gray(" Update auth.tokenEndpoint in duct.config.ts if this is intentional.\n"));
1122
+ }
806
1123
  console.log(chalk.green("\n ✓ Files written successfully!\n"));
1124
+ // ---- Post-write validation: receiver route health check ----
1125
+ if (baseUrl) {
1126
+ const receiverUrl = `${baseUrl.replace(/\/$/, "")}/api/duct/receive`;
1127
+ try {
1128
+ const controller = new AbortController();
1129
+ const timer = setTimeout(() => controller.abort(), 3000);
1130
+ const res = await fetch(receiverUrl, { method: "HEAD", signal: controller.signal });
1131
+ clearTimeout(timer);
1132
+ if (res.ok || res.status === 405) {
1133
+ console.log(chalk.green(` ✓ Receiver reachable at /api/duct/receive`));
1134
+ }
1135
+ else {
1136
+ console.log(chalk.gray(` ⚠ Receiver returned ${res.status} at ${receiverUrl} — ensure dev server is running before duct push`));
1137
+ }
1138
+ }
1139
+ catch {
1140
+ console.log(chalk.gray(` ⚠ Could not reach receiver at ${receiverUrl} — start your dev server before running duct push`));
1141
+ }
1142
+ }
807
1143
  const apiKey = process.env["DUCT_API_KEY"];
808
1144
  if (apiKey) {
809
1145
  try {
@@ -0,0 +1,22 @@
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[];
@@ -0,0 +1,107 @@
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
+ /\border\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
+ }