@duct-sdk/sdk 0.1.12 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -46,18 +46,45 @@ function loadEnvFileSync(envPath) {
46
46
  // File doesn't exist — that's fine, move on
47
47
  }
48
48
  }
49
+ // Walk up from startDir until we find a directory that looks like the project
50
+ // root (contains duct.config.ts, .git, or package.json). Returns all
51
+ // directories from root down to startDir so that files closer to the user's
52
+ // cwd take priority (loaded last = highest priority among .env files).
53
+ function resolveEnvSearchDirs(startDir) {
54
+ const dirs = [];
55
+ let dir = startDir;
56
+ for (let i = 0; i < 10; i++) {
57
+ dirs.unshift(dir); // prepend so we get root→cwd order
58
+ const isDuctRoot = require("fs").existsSync(require("path").join(dir, "duct.config.ts")) ||
59
+ require("fs").existsSync(require("path").join(dir, "duct.config.js")) ||
60
+ require("fs").existsSync(require("path").join(dir, ".git"));
61
+ if (isDuctRoot) {
62
+ break;
63
+ }
64
+ const parent = require("path").dirname(dir);
65
+ if (parent === dir)
66
+ break; // filesystem root
67
+ dir = parent;
68
+ }
69
+ // Deduplicate while preserving order (root first, cwd last)
70
+ return [...new Set(dirs)];
71
+ }
49
72
  function loadAllEnvFilesSync() {
50
73
  const cwd = process.cwd();
51
74
  const nodeEnv = process.env["NODE_ENV"] ?? "";
52
- // Standard dotenv priority order (lowest → highest priority)
53
- const candidates = [
75
+ const suffixes = [
54
76
  ".env",
55
77
  ".env.local",
56
78
  nodeEnv ? `.env.${nodeEnv}` : null,
57
79
  nodeEnv ? `.env.${nodeEnv}.local` : null,
58
80
  ].filter((f) => Boolean(f));
59
- for (const file of candidates) {
60
- loadEnvFileSync(path.join(cwd, file));
81
+ // Load from each ancestor directory (root → cwd), so keys from directories
82
+ // closer to cwd override those from parent directories, but never override
83
+ // keys already set in the shell environment.
84
+ for (const dir of resolveEnvSearchDirs(cwd)) {
85
+ for (const suffix of suffixes) {
86
+ loadEnvFileSync(path.join(dir, suffix));
87
+ }
61
88
  }
62
89
  }
63
90
  // Load all .env files synchronously at startup (before any commands run)
@@ -297,7 +324,7 @@ program
297
324
  process.exit(1);
298
325
  }
299
326
  });
300
- // Mirror of buildDependsOnPlan() in services/shell-runtime/app/api/chat/route.ts — keep in sync.
327
+ // Topological order for action dependsOn chains (max depth 4).
301
328
  function buildDependsOnOrder(targetId, actions, visited = new Set()) {
302
329
  if (visited.has(targetId) || visited.size > 4)
303
330
  return [];
@@ -430,7 +457,7 @@ program
430
457
  console.log(chalk.gray(` • ${wf.name} (${stepNames})`));
431
458
  }
432
459
  console.log();
433
- // Embed into the manifest so agent-proxy stores them alongside actions
460
+ // Embed into the manifest so Duct stores them alongside actions
434
461
  config = { ...config, precomputedWorkflows };
435
462
  }
436
463
  const pushSpinner = ora("Pushing to Duct cloud...").start();
@@ -461,9 +488,40 @@ program
461
488
  continue;
462
489
  }
463
490
  pushSpinner.fail("Push failed");
464
- console.error(chalk.red(`\n${lastError}`));
465
- console.log(chalk.gray(" Tip: Check DUCT_URL is set and services are running."));
466
- console.log(chalk.gray(" Run npx duct checkup to diagnose connectivity.\n"));
491
+ // Parse the error body and surface the real cause clearly.
492
+ // The proxy may wrap inner service errors as a JSON string inside `message`.
493
+ let outerErr = {};
494
+ let innerErr = {};
495
+ try {
496
+ outerErr = JSON.parse(body);
497
+ }
498
+ catch { /* raw string error */ }
499
+ if (typeof outerErr["message"] === "string") {
500
+ try {
501
+ innerErr = JSON.parse(outerErr["message"]);
502
+ }
503
+ catch { /* not JSON */ }
504
+ }
505
+ const innerCode = (innerErr["error"] ?? outerErr["error"] ?? "");
506
+ const retryAfter = innerErr["retry_after"];
507
+ if (innerCode === "too_many_requests") {
508
+ const wait = retryAfter ? ` Try again in ${retryAfter}s.` : " Try again shortly.";
509
+ console.error(chalk.red("\n Auth service rate-limited: too many failed token validation attempts."));
510
+ console.log(chalk.yellow(` This usually means DUCT_SECRET_KEY was missing or invalid on previous runs.${wait}`));
511
+ console.log(chalk.gray(" 1. Confirm DUCT_SECRET_KEY is set in your .env (at the same level as duct.config.ts)"));
512
+ console.log(chalk.gray(" 2. Run `npx duct login` if your session token is stale"));
513
+ console.log(chalk.gray(" 3. Run `npx duct checkup` to verify env vars are loaded\n"));
514
+ }
515
+ else if (response.status === 401) {
516
+ const hint = outerErr["message"] ?? body;
517
+ console.error(chalk.red(`\n Authentication failed: ${hint}`));
518
+ console.log(chalk.gray(" Run `npx duct login` to refresh your credentials, then retry.\n"));
519
+ }
520
+ else {
521
+ console.error(chalk.red(`\n${lastError}`));
522
+ console.log(chalk.gray(" Tip: Check DUCT_URL is set and services are running."));
523
+ console.log(chalk.gray(" Run npx duct checkup to diagnose connectivity.\n"));
524
+ }
467
525
  process.exit(1);
468
526
  }
469
527
  if (!success) {
@@ -474,6 +532,13 @@ program
474
532
  process.exit(1);
475
533
  }
476
534
  pushSpinner.succeed(`Manifest synced for shell: ${chalk.cyan(shellId)}`);
535
+ // Keep .duct-manifest.json in sync so `duct scan --manifest-diff` always
536
+ // diffs against what was actually last pushed, not just what `duct init` wrote.
537
+ try {
538
+ const snapshotPath = path.resolve(cwd, ".duct-manifest.json");
539
+ await fs.writeFile(snapshotPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
540
+ }
541
+ catch { /* non-fatal — snapshot is a local convenience file */ }
477
542
  console.log(chalk.green("\n ◆ Manifest synced\n"));
478
543
  }
479
544
  catch (err) {
@@ -547,7 +612,7 @@ program
547
612
  console.log(chalk.gray(` Credentials saved to ${DUCT_AUTH_FILE} (mode 600)\n`));
548
613
  console.log(chalk.yellow(` ⚠ Keep this file private — it contains your API key.\n Add ${DUCT_AUTH_FILE} to your global .gitignore.\n`));
549
614
  // Best-effort: fetch and display provisioned shells for this account.
550
- // Account/identity endpoints live on the auth service, NOT agent-proxy.
615
+ // Account/identity endpoints use the auth base URL, not the API base URL.
551
616
  try {
552
617
  const authBase = getActiveAuthBase(auth);
553
618
  const shellsRes = await fetch(`${authBase}/v1/account/shells`, {
@@ -910,6 +975,238 @@ export default defineDuctConfig(${JSON.stringify(manifest, null, 2)});
910
975
  }
911
976
  });
912
977
  // ----------------------------------------------------------------
978
+ // duct rollback — activate a historical push directly on Duct cloud
979
+ // Unlike `duct pull` (which writes duct.config.ts locally), rollback
980
+ // immediately sets the live manifest to the stored snapshot without
981
+ // touching any local files. Run `duct pull <hash>` afterwards if you
982
+ // also want your local config to reflect the change.
983
+ // ----------------------------------------------------------------
984
+ program
985
+ .command("rollback <hash>")
986
+ .description("Set a historical push as the active manifest on Duct cloud (no local file changes)")
987
+ .option("--shell-id <shellId>", "Override shell ID (reads from duct.config.ts by default)")
988
+ .option("--config <path>", "Path to duct.config.ts (used only to read shellId)", "duct.config.ts")
989
+ .option("--yes", "Skip confirmation prompt", false)
990
+ .action(async (hash, opts) => {
991
+ const spinner = ora("Resolving shell…").start();
992
+ try {
993
+ // Load API key
994
+ let apiKey = process.env["DUCT_API_KEY"];
995
+ if (!apiKey) {
996
+ const auth = await readAuth();
997
+ apiKey = auth?.token;
998
+ }
999
+ if (!apiKey) {
1000
+ spinner.fail("Not logged in");
1001
+ console.log(chalk.yellow("\nRun `npx duct login` first.\n"));
1002
+ process.exit(1);
1003
+ }
1004
+ // Resolve shell ID
1005
+ let shellId = opts.shellId;
1006
+ if (!shellId) {
1007
+ const cwd = process.cwd();
1008
+ const configPath = path.resolve(cwd, opts.config);
1009
+ try {
1010
+ const config = await loadDuctConfig(configPath);
1011
+ shellId = config["shellId"];
1012
+ }
1013
+ catch { /* config may not exist */ }
1014
+ }
1015
+ if (!shellId) {
1016
+ spinner.stop();
1017
+ const { id } = await inquirer.prompt([
1018
+ {
1019
+ type: "input",
1020
+ name: "id",
1021
+ message: "Shell ID (shell_...):",
1022
+ validate: (v) => v.startsWith("shell_") || "Must start with shell_",
1023
+ },
1024
+ ]);
1025
+ shellId = id;
1026
+ }
1027
+ spinner.succeed(`Shell: ${chalk.cyan(shellId)}`);
1028
+ if (!opts.yes) {
1029
+ const { confirm } = await inquirer.prompt([
1030
+ {
1031
+ type: "confirm",
1032
+ name: "confirm",
1033
+ message: chalk.yellow(`Activate hash ${chalk.bold(hash)} as the live manifest for ${shellId}?`),
1034
+ default: false,
1035
+ },
1036
+ ]);
1037
+ if (!confirm) {
1038
+ console.log(chalk.gray("\nRollback cancelled.\n"));
1039
+ process.exit(0);
1040
+ }
1041
+ }
1042
+ const activateSpinner = ora(`Activating ${hash}…`).start();
1043
+ const auth = await readAuth();
1044
+ const manifestBases = getManifestApiBases(auth);
1045
+ let success = false;
1046
+ let lastError = "";
1047
+ for (const base of manifestBases) {
1048
+ const res = await fetch(`${base}/v1/shells/${shellId}/manifest/activate/${encodeURIComponent(hash)}`, {
1049
+ method: "POST",
1050
+ headers: { Authorization: `Bearer ${apiKey}` },
1051
+ });
1052
+ if (res.ok) {
1053
+ success = true;
1054
+ break;
1055
+ }
1056
+ const body = await res.text();
1057
+ lastError = `${res.status} at ${base}: ${body}`;
1058
+ if (res.status === 404)
1059
+ continue;
1060
+ break;
1061
+ }
1062
+ if (!success) {
1063
+ activateSpinner.fail(`Rollback failed`);
1064
+ console.error(chalk.red(`\n${lastError || "No manifest API responded"}`));
1065
+ process.exit(1);
1066
+ }
1067
+ activateSpinner.succeed(`Hash ${chalk.cyan(hash)} is now the live manifest for ${chalk.cyan(shellId)}`);
1068
+ console.log(chalk.green("\n ◆ Rollback complete\n"));
1069
+ console.log(chalk.gray(` Tip: Run \`npx duct pull ${hash}\` to also restore duct.config.ts locally.\n`));
1070
+ }
1071
+ catch (err) {
1072
+ spinner.fail("Rollback failed");
1073
+ const message = err instanceof Error ? err.message : String(err);
1074
+ console.error(chalk.red(`\nError: ${message}\n`));
1075
+ process.exit(1);
1076
+ }
1077
+ });
1078
+ // ----------------------------------------------------------------
1079
+ // duct promote --from <source> --to <target>
1080
+ // Copies the live manifest of the source shell to the target shell,
1081
+ // implementing the dev → staging → production promotion workflow.
1082
+ // ----------------------------------------------------------------
1083
+ program
1084
+ .command("promote")
1085
+ .description("Promote the live manifest of one shell to another (e.g. dev → prod)")
1086
+ .requiredOption("--from <shellId>", "Source shell ID to promote from")
1087
+ .requiredOption("--to <shellId>", "Target shell ID to promote to")
1088
+ .option("--yes", "Skip confirmation prompt", false)
1089
+ .action(async (opts) => {
1090
+ const spinner = ora("Authenticating…").start();
1091
+ try {
1092
+ // Load API key
1093
+ let apiKey = process.env["DUCT_API_KEY"];
1094
+ if (!apiKey) {
1095
+ const auth = await readAuth();
1096
+ apiKey = auth?.token;
1097
+ }
1098
+ if (!apiKey) {
1099
+ spinner.fail("Not logged in");
1100
+ console.log(chalk.yellow("\nRun `npx duct login` first.\n"));
1101
+ process.exit(1);
1102
+ }
1103
+ const auth = await readAuth();
1104
+ const manifestBases = getManifestApiBases(auth);
1105
+ // ── Step 1: Fetch source manifest ─────────────────────────
1106
+ spinner.text = `Fetching manifest from ${chalk.cyan(opts.from)}…`;
1107
+ let sourceManifest = null;
1108
+ for (const base of manifestBases) {
1109
+ const res = await fetch(`${base}/v1/shells/${opts.from}/manifest`, {
1110
+ method: "GET",
1111
+ headers: { Authorization: `Bearer ${apiKey}` },
1112
+ });
1113
+ if (res.ok) {
1114
+ const data = (await res.json());
1115
+ sourceManifest = (data.manifest ?? null);
1116
+ if (sourceManifest)
1117
+ break;
1118
+ }
1119
+ if (res.status === 404)
1120
+ continue;
1121
+ const body = await res.text();
1122
+ spinner.fail(`Failed to fetch source manifest`);
1123
+ console.error(chalk.red(`\n ${res.status} at ${base}: ${body}\n`));
1124
+ process.exit(1);
1125
+ }
1126
+ if (!sourceManifest) {
1127
+ spinner.fail(`Shell '${opts.from}' not found or has no manifest`);
1128
+ process.exit(1);
1129
+ }
1130
+ const actionCount = Array.isArray(sourceManifest["actions"])
1131
+ ? sourceManifest["actions"].length
1132
+ : 0;
1133
+ spinner.succeed(`Fetched manifest from ${chalk.cyan(opts.from)} (${actionCount} action${actionCount === 1 ? "" : "s"})`);
1134
+ // ── Step 2: Confirmation ───────────────────────────────────
1135
+ console.log(chalk.dim(`\n Promoting: ${chalk.cyan(opts.from)} → ${chalk.cyan(opts.to)}\n`));
1136
+ if (!opts.yes) {
1137
+ const { confirm } = await inquirer.prompt([
1138
+ {
1139
+ type: "confirm",
1140
+ name: "confirm",
1141
+ message: chalk.yellow(`Push the ${chalk.bold(opts.from)} manifest (${actionCount} actions) to ${chalk.bold(opts.to)}?`),
1142
+ default: false,
1143
+ },
1144
+ ]);
1145
+ if (!confirm) {
1146
+ console.log(chalk.gray("\nPromotion cancelled.\n"));
1147
+ process.exit(0);
1148
+ }
1149
+ }
1150
+ // ── Step 3: Push to target ─────────────────────────────────
1151
+ const pushSpinner = ora(`Pushing to ${chalk.cyan(opts.to)}…`).start();
1152
+ // Rewrite shellId in the manifest to match the target
1153
+ const promotedManifest = {
1154
+ ...sourceManifest,
1155
+ shellId: opts.to,
1156
+ };
1157
+ let pushed = false;
1158
+ let pushError = "";
1159
+ let pushHash = "";
1160
+ let pushChecksum = "";
1161
+ for (const base of manifestBases) {
1162
+ const res = await fetch(`${base}/v1/shells/${opts.to}/manifest`, {
1163
+ method: "PUT",
1164
+ headers: {
1165
+ "Content-Type": "application/json",
1166
+ Authorization: `Bearer ${apiKey}`,
1167
+ },
1168
+ body: JSON.stringify({ config: promotedManifest }),
1169
+ });
1170
+ if (res.ok) {
1171
+ const data = (await res.json());
1172
+ pushed = true;
1173
+ pushHash = data.push_hash ?? "";
1174
+ pushChecksum = (data.config_checksum ?? "").slice(0, 7);
1175
+ break;
1176
+ }
1177
+ const body = await res.text();
1178
+ pushError = `${res.status} at ${base}: ${body}`;
1179
+ if (res.status === 404)
1180
+ continue;
1181
+ break;
1182
+ }
1183
+ if (!pushed) {
1184
+ pushSpinner.fail(`Promote failed`);
1185
+ console.error(chalk.red(`\n${pushError || "No manifest API responded"}\n`));
1186
+ process.exit(1);
1187
+ }
1188
+ pushSpinner.succeed(`Manifest pushed to ${chalk.cyan(opts.to)}`);
1189
+ console.log(chalk.green("\n ◆ Promotion complete\n"));
1190
+ if (pushHash)
1191
+ console.log(chalk.dim(` Hash: ${chalk.cyan(pushHash)}`));
1192
+ if (pushChecksum)
1193
+ console.log(chalk.dim(` Checksum: ${pushChecksum}`));
1194
+ console.log(chalk.dim(`\n Tip: Run \`npx duct scan --shell-id ${opts.to}\` to verify the promoted shell.\n`));
1195
+ // Persist promoted manifest locally as snapshot so --update diffs correctly
1196
+ try {
1197
+ const snapshotPath = path.resolve(process.cwd(), ".duct-manifest.json");
1198
+ await fs.writeFile(snapshotPath, JSON.stringify(promotedManifest, null, 2) + "\n", "utf-8");
1199
+ }
1200
+ catch { /* non-fatal — snapshot is a local convenience */ }
1201
+ }
1202
+ catch (err) {
1203
+ spinner.fail("Promotion failed");
1204
+ const message = err instanceof Error ? err.message : String(err);
1205
+ console.error(chalk.red(`\nError: ${message}\n`));
1206
+ process.exit(1);
1207
+ }
1208
+ });
1209
+ // ----------------------------------------------------------------
913
1210
  // Error handling
914
1211
  // ----------------------------------------------------------------
915
1212
  program.exitOverride();
package/dist/cli/init.js CHANGED
@@ -42,7 +42,7 @@ async function loadAuth() {
42
42
  * Fetch the company's provisioned shells from the Duct auth service.
43
43
  *
44
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
45
+ * auth.<host> in prod), NOT the API host. Calling the wrong base URL
46
46
  * was the root cause of a "No shells provisioned" false negative bug.
47
47
  */
48
48
  async function fetchAccountShells(apiKey, authBase) {
@@ -585,10 +585,9 @@ export async function runInit(opts = {}) {
585
585
  }
586
586
  console.log(chalk.gray(` Authenticated as ${auth.email} (${auth.slug})\n`));
587
587
  // Use saved auth endpoints (or production defaults).
588
- // Account/identity endpoints live on the auth service, not agent-proxy.
588
+ // Account/identity endpoints use the auth base URL.
589
589
  const ductAuthBase = getActiveAuthBase(auth);
590
590
  // Fetch company's provisioned shells from the auth service.
591
- // (Account/identity endpoints live on auth, not on agent-proxy.)
592
591
  let accountShells;
593
592
  try {
594
593
  accountShells = await fetchAccountShells(auth.token, ductAuthBase);
@@ -30,3 +30,28 @@ export interface ReviewedPipelineResult {
30
30
  * - `--no-interactive`: write unresolved decisions to duct-review.json
31
31
  */
32
32
  export declare function runInteractiveReview(pipelineResult: PipelineResult, opts?: ReviewOptions): Promise<ReviewedPipelineResult>;
33
+ export interface InteractiveReviewOptions {
34
+ /** Auto-approve everything (--yes / CI mode) */
35
+ yes: boolean;
36
+ /** Write manifest to duct-review.json instead of prompting (--no-interactive) */
37
+ noInteractive: boolean;
38
+ /** Working directory for writing duct-review.json (defaults to cwd) */
39
+ cwd?: string;
40
+ }
41
+ /**
42
+ * Interactive review for a generated manifest.
43
+ *
44
+ * Decision rules:
45
+ * - `options.yes` → return manifest unchanged, all actions approved
46
+ * - `options.noInteractive` → write to duct-review.json, return manifest unchanged
47
+ * - Otherwise:
48
+ * - GET + confidence ≥ 0.85 → auto-approve (prints "✓ Auto-approved: [id]")
49
+ * - POST / DELETE / PATCH / PUT → always prompt
50
+ * - confidence < 0.85 → prompt regardless of method
51
+ * - Shows evidence: "Detected from: [files]"
52
+ *
53
+ * @param manifest The generated DuctConfig-like manifest (any shape, operates on .actions[])
54
+ * @param options Review mode flags
55
+ * @returns The manifest with only approved actions
56
+ */
57
+ export declare function interactiveReview(manifest: any, options: InteractiveReviewOptions): Promise<any>;
@@ -45,7 +45,9 @@ function requiresPrompt(action) {
45
45
  // ----------------------------------------------------------------
46
46
  async function promptActionDecision(action, rl) {
47
47
  const confidence = action.confidence ?? 0;
48
- const evidence = action.evidence ?? "unknown source";
48
+ const evidence = Array.isArray(action.evidence)
49
+ ? action.evidence.join(", ")
50
+ : (action.evidence ?? "unknown source");
49
51
  const method = methodColor(action.method);
50
52
  const conf = confidenceColor(confidence);
51
53
  const isSideEffect = action.sideEffects ||
@@ -136,7 +138,7 @@ export async function runInteractiveReview(pipelineResult, opts = {}) {
136
138
  method: action.method,
137
139
  path: action.path,
138
140
  confidence: action.confidence ?? 0,
139
- evidence: action.evidence,
141
+ evidence: Array.isArray(action.evidence) ? action.evidence.join(", ") : action.evidence,
140
142
  reason: requiresPrompt(action)
141
143
  ? "Requires human review: side-effect or low confidence"
142
144
  : "Pending",
@@ -238,3 +240,107 @@ export async function runInteractiveReview(pipelineResult, opts = {}) {
238
240
  rejectedActions,
239
241
  };
240
242
  }
243
+ /**
244
+ * Interactive review for a generated manifest.
245
+ *
246
+ * Decision rules:
247
+ * - `options.yes` → return manifest unchanged, all actions approved
248
+ * - `options.noInteractive` → write to duct-review.json, return manifest unchanged
249
+ * - Otherwise:
250
+ * - GET + confidence ≥ 0.85 → auto-approve (prints "✓ Auto-approved: [id]")
251
+ * - POST / DELETE / PATCH / PUT → always prompt
252
+ * - confidence < 0.85 → prompt regardless of method
253
+ * - Shows evidence: "Detected from: [files]"
254
+ *
255
+ * @param manifest The generated DuctConfig-like manifest (any shape, operates on .actions[])
256
+ * @param options Review mode flags
257
+ * @returns The manifest with only approved actions
258
+ */
259
+ export async function interactiveReview(
260
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
261
+ manifest, options
262
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
263
+ ) {
264
+ const { yes, noInteractive, cwd = process.cwd() } = options;
265
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
266
+ const actions = Array.isArray(manifest?.actions) ? manifest.actions : [];
267
+ // ── --yes mode: return unchanged ─────────────────────────────
268
+ if (yes) {
269
+ return manifest;
270
+ }
271
+ // ── --no-interactive: write to duct-review.json ──────────────
272
+ if (noInteractive) {
273
+ const reviewContent = {
274
+ generatedAt: new Date().toISOString(),
275
+ pendingDecisions: actions
276
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
277
+ .filter((a) => {
278
+ const isSideEffect = ["POST", "PUT", "PATCH", "DELETE"].includes(a.method ?? "");
279
+ const lowConfidence = (a.confidence ?? 0) < 0.85;
280
+ return isSideEffect || lowConfidence;
281
+ })
282
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
283
+ .map((a) => ({
284
+ id: a.id,
285
+ method: a.method,
286
+ path: a.path,
287
+ confidence: a.confidence ?? 0,
288
+ evidence: Array.isArray(a.evidence) ? a.evidence.join(", ") : (a.evidence ?? ""),
289
+ reason: ["POST", "PUT", "PATCH", "DELETE"].includes(a.method ?? "")
290
+ ? "Side-effect action requires review"
291
+ : "Low confidence detection",
292
+ })),
293
+ instructions: "Review each entry. Set `approved: true` for actions to include. Re-run `npx duct init` to apply.",
294
+ };
295
+ const reviewFilePath = path.join(cwd, "duct-review.json");
296
+ await fs.writeFile(reviewFilePath, JSON.stringify(reviewContent, null, 2) + "\n", "utf-8");
297
+ console.log(chalk.yellow(`\n [DUCT] --no-interactive: wrote ${reviewContent.pendingDecisions.length} pending decisions to duct-review.json\n`));
298
+ return manifest;
299
+ }
300
+ // ── Interactive mode ─────────────────────────────────────────
301
+ const approved = [];
302
+ const rl = readline.createInterface({
303
+ input: process.stdin,
304
+ output: process.stdout,
305
+ terminal: false,
306
+ });
307
+ for (const action of actions) {
308
+ const method = action.method ?? "GET";
309
+ const confidence = action.confidence ?? 0;
310
+ const isSafeGet = method === "GET" && confidence >= 0.85;
311
+ const isSideEffect = ["POST", "PUT", "PATCH", "DELETE"].includes(method);
312
+ if (isSafeGet) {
313
+ approved.push(action);
314
+ process.stdout.write(chalk.green(` ✓ Auto-approved: `) +
315
+ chalk.cyan(`[${action.id ?? action.path}]`) +
316
+ chalk.gray(` ${method} ${action.path ?? ""} ${Math.round(confidence * 100)}%\n`));
317
+ continue;
318
+ }
319
+ // Must prompt
320
+ const evidenceStr = Array.isArray(action.evidence)
321
+ ? action.evidence.join(", ")
322
+ : (action.evidence ?? "unknown source");
323
+ const reason = isSideEffect
324
+ ? "side-effect action"
325
+ : `confidence ${Math.round(confidence * 100)}% < 85%`;
326
+ process.stdout.write(`\n ${chalk.bold("[DUCT]")} ${methodColor(method)} ${chalk.cyan(action.path ?? "")} — ${reason}\n` +
327
+ ` ${chalk.gray(`Confidence: ${confidenceColor(confidence)}`)}\n` +
328
+ ` ${chalk.gray(`Detected from: ${chalk.dim(evidenceStr)}`)}\n` +
329
+ ` ${chalk.gray(`Include action '${action.id ?? action.path}'` +
330
+ (action.description ? ` (${String(action.description).slice(0, 60)})` : "") +
331
+ `? [y/N]: `)}`);
332
+ const answer = await new Promise((resolve) => {
333
+ rl.once("line", (line) => resolve(line.trim().toLowerCase()));
334
+ });
335
+ if (answer === "y" || answer === "yes") {
336
+ approved.push(action);
337
+ console.log(chalk.green(` ✓ Included: ${action.id ?? action.path}`));
338
+ }
339
+ else {
340
+ console.log(chalk.gray(` — Excluded: ${action.id ?? action.path}`));
341
+ }
342
+ }
343
+ rl.close();
344
+ console.log(chalk.bold(`\n Review complete: ${approved.length}/${actions.length} actions included\n`));
345
+ return { ...manifest, actions: approved };
346
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Select files for Express / Fastify / Koa projects.
3
+ *
4
+ * Priority:
5
+ * 1. Route files: routes/...ts, src/routes/...ts
6
+ * 2. Middleware: middleware/...ts, src/middleware/...ts
7
+ * 3. Entry points: src/index.ts, index.ts, app.ts, server.ts
8
+ *
9
+ * @param projectRoot Absolute project root path
10
+ * @param maxFiles Maximum total files to return (default 30)
11
+ */
12
+ export declare function selectExpressFiles(projectRoot: string, maxFiles?: number): Promise<string[]>;