@contentful/experience-design-system-cli 2.35.1-dev-build-f520d7cb.0 → 2.35.1-dev-build-98f1ba74.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 (24) hide show
  1. package/dist/package.json +1 -1
  2. package/legacy/dist/src/analyze/composition/interchange-schema.d.ts +7 -1
  3. package/legacy/dist/src/analyze/composition/resolve-mapping.d.ts +11 -34
  4. package/legacy/dist/src/analyze/composition/source-call-site-evidence.d.ts +30 -0
  5. package/legacy/dist/src/analyze/extract-command.d.ts +0 -4
  6. package/legacy/dist/src/import/tui/WizardApp.d.ts +1 -7
  7. package/legacy/dist/src/import/tui/run-selection-agent.d.ts +0 -1
  8. package/legacy/dist/src/import/tui/wizard-state-transitions.d.ts +0 -3
  9. package/legacy/dist/src/index.js +646 -1925
  10. package/legacy/dist/src/map-tokens/tui/MapTokensView.d.ts +0 -1
  11. package/legacy/dist/src/session/db.d.ts +4 -73
  12. package/legacy/package.json +1 -1
  13. package/package.json +2 -2
  14. package/legacy/dist/src/analyze/composition/candidate-files.d.ts +0 -34
  15. package/legacy/dist/src/analyze/composition/composition-cache-key.d.ts +0 -18
  16. package/legacy/dist/src/analyze/composition/parse-map-edges.d.ts +0 -16
  17. package/legacy/dist/src/analyze/composition/prompt-loader.d.ts +0 -3
  18. package/legacy/dist/src/analyze/composition/resolve-mapping-cli.d.ts +0 -10
  19. package/legacy/dist/src/lib/prop-bucket-debug.d.ts +0 -3
  20. package/legacy/dist/src/session/cache-keys.d.ts +0 -22
  21. package/legacy/dist/src/session/core/components/hash-component-shape.d.ts +0 -5
  22. package/legacy/dist/src/session/core/components/strip-extraction-provenance.d.ts +0 -2
  23. package/legacy/dist/src/session/core/tokens/hash-token-content.d.ts +0 -1
  24. package/legacy/prompts/composition-edges.md +0 -11
@@ -164,12 +164,11 @@ var init_render_with_goodbye = __esm({
164
164
  function isAgentName(value) {
165
165
  return AGENT_NAMES.includes(value);
166
166
  }
167
- var AGENT_NAMES, DEFAULT_AGENT_NAME, AGENT_BINARIES;
167
+ var AGENT_NAMES, AGENT_BINARIES;
168
168
  var init_agent_names = __esm({
169
169
  "packages/experience-design-system-generation/dist/src/agent-names.js"() {
170
170
  "use strict";
171
171
  AGENT_NAMES = ["claude", "codex", "opencode", "cursor", "copilot"];
172
- DEFAULT_AGENT_NAME = "claude";
173
172
  AGENT_BINARIES = {
174
173
  claude: "claude",
175
174
  codex: "codex",
@@ -181,23 +180,6 @@ var init_agent_names = __esm({
181
180
  });
182
181
 
183
182
  // packages/experience-design-system-generation/dist/src/controller/helpers/validate-generation-request.js
184
- function validateGenerationRequest(request2) {
185
- if (request2 === null || typeof request2 !== "object") {
186
- throw new TypeError("createGenerationEndpoint requires a request object");
187
- }
188
- if (!isAgentName(request2.agent)) {
189
- throw new TypeError(`createGenerationEndpoint requires agent to be a valid agent name, got: ${String(request2.agent)}`);
190
- }
191
- if (typeof request2.timeoutMs !== "number" || request2.timeoutMs <= 0) {
192
- throw new TypeError("createGenerationEndpoint requires timeoutMs to be a positive number");
193
- }
194
- if (request2.promptOptions === null || typeof request2.promptOptions !== "object") {
195
- throw new TypeError("createGenerationEndpoint requires promptOptions to be an object");
196
- }
197
- if (request2.onOutput !== void 0 && typeof request2.onOutput !== "function") {
198
- throw new TypeError("createGenerationEndpoint requires onOutput to be a function when provided");
199
- }
200
- }
201
183
  var init_validate_generation_request = __esm({
202
184
  "packages/experience-design-system-generation/dist/src/controller/helpers/validate-generation-request.js"() {
203
185
  "use strict";
@@ -630,17 +612,6 @@ var init_build_prompt = __esm({
630
612
  });
631
613
 
632
614
  // packages/experience-design-system-generation/dist/src/orchestrator/execute-generation-orchestrator.js
633
- async function executeGenerationOrchestrator(request2) {
634
- const prompt = await buildPrompt(request2.promptOptions);
635
- return request2.invoker.invoke({
636
- agent: request2.agent,
637
- model: request2.model,
638
- bedrock: request2.bedrock,
639
- prompt,
640
- timeoutMs: request2.timeoutMs,
641
- onOutput: request2.onOutput
642
- });
643
- }
644
615
  var init_execute_generation_orchestrator = __esm({
645
616
  "packages/experience-design-system-generation/dist/src/orchestrator/execute-generation-orchestrator.js"() {
646
617
  "use strict";
@@ -741,22 +712,6 @@ var init_describe_agent_failure = __esm({
741
712
  });
742
713
 
743
714
  // packages/experience-design-system-generation/dist/src/services/agent/helpers/extract-sentinel-output.js
744
- function extractSentinelOutput(stdout) {
745
- const START = "<<<EDS_OUTPUT_START>>>";
746
- const END = "<<<EDS_OUTPUT_END>>>";
747
- const startIdx = stdout.indexOf(START);
748
- const endIdx = stdout.indexOf(END);
749
- if (startIdx === -1 || endIdx === -1 || endIdx <= startIdx)
750
- return null;
751
- const secondStart = stdout.indexOf(START, startIdx + START.length);
752
- if (secondStart !== -1 && secondStart < endIdx)
753
- return "multiple";
754
- const afterStart = stdout.indexOf(END, startIdx);
755
- const secondEnd = stdout.indexOf(END, afterStart + END.length);
756
- if (secondEnd !== -1)
757
- return "multiple";
758
- return stdout.slice(startIdx + START.length, endIdx).trim();
759
- }
760
715
  var init_extract_sentinel_output = __esm({
761
716
  "packages/experience-design-system-generation/dist/src/services/agent/helpers/extract-sentinel-output.js"() {
762
717
  "use strict";
@@ -781,7 +736,7 @@ async function runAgent(options) {
781
736
  promptLen: prompt.length,
782
737
  promptHead: prompt.slice(0, 500)
783
738
  });
784
- return new Promise((resolve22) => {
739
+ return new Promise((resolve20) => {
785
740
  const bedrockEnv = bedrock ? BEDROCK_ENV_BY_AGENT[agent] : void 0;
786
741
  const child = spawn(binary, args, {
787
742
  stdio: ["pipe", "pipe", "pipe"],
@@ -830,7 +785,7 @@ async function runAgent(options) {
830
785
  stderrLen: stderr.length,
831
786
  stderrTail: stderr.slice(-1e3)
832
787
  });
833
- resolve22(result);
788
+ resolve20(result);
834
789
  });
835
790
  });
836
791
  }
@@ -847,7 +802,7 @@ var init_run_agent = __esm({
847
802
  // packages/experience-design-system-generation/dist/src/services/agent/helpers/check-claude-auth.js
848
803
  import { spawn as spawn2 } from "node:child_process";
849
804
  function checkClaudeAuth(binary) {
850
- return new Promise((resolve22) => {
805
+ return new Promise((resolve20) => {
851
806
  const child = spawn2(binary, ["auth", "status", "--json"], {
852
807
  stdio: ["ignore", "pipe", "pipe"]
853
808
  });
@@ -857,7 +812,7 @@ function checkClaudeAuth(binary) {
857
812
  if (!done) {
858
813
  done = true;
859
814
  child.kill("SIGTERM");
860
- resolve22("unauthenticated");
815
+ resolve20("unauthenticated");
861
816
  }
862
817
  }, 5e3);
863
818
  child.stdout?.on("data", (chunk) => {
@@ -869,14 +824,14 @@ function checkClaudeAuth(binary) {
869
824
  done = true;
870
825
  clearTimeout(timer);
871
826
  if (code !== 0) {
872
- resolve22("unauthenticated");
827
+ resolve20("unauthenticated");
873
828
  return;
874
829
  }
875
830
  try {
876
831
  const status = JSON.parse(stdout);
877
- resolve22(status.loggedIn ? "ok" : "unauthenticated");
832
+ resolve20(status.loggedIn ? "ok" : "unauthenticated");
878
833
  } catch {
879
- resolve22("unauthenticated");
834
+ resolve20("unauthenticated");
880
835
  }
881
836
  });
882
837
  });
@@ -891,13 +846,13 @@ var init_check_claude_auth = __esm({
891
846
  import { spawn as spawn3 } from "node:child_process";
892
847
  async function checkAgentAuth(agent) {
893
848
  const binary = resolveAgentBinary(agent);
894
- const binaryExists2 = await new Promise((resolve22) => {
849
+ const binaryExists2 = await new Promise((resolve20) => {
895
850
  if (binary.startsWith("/")) {
896
- import("node:fs/promises").then((fs2) => fs2.access(binary).then(() => resolve22(true), () => resolve22(false)));
851
+ import("node:fs/promises").then((fs2) => fs2.access(binary).then(() => resolve20(true), () => resolve20(false)));
897
852
  return;
898
853
  }
899
854
  const child = spawn3(process.platform === "win32" ? "where" : "which", [binary], { stdio: "ignore" });
900
- child.on("close", (code) => resolve22(code === 0));
855
+ child.on("close", (code) => resolve20(code === 0));
901
856
  });
902
857
  if (!binaryExists2)
903
858
  return "not-found";
@@ -934,20 +889,6 @@ var init_local_cli_agent_invoker = __esm({
934
889
  });
935
890
 
936
891
  // packages/experience-design-system-generation/dist/src/controller/create-generation-endpoint.js
937
- function createGenerationEndpoint(options = {}) {
938
- const invoker2 = createLocalCliAgentInvoker({
939
- onDebugEvent: options.onDebugEvent
940
- });
941
- return {
942
- async run(request2) {
943
- validateGenerationRequest(request2);
944
- return executeGenerationOrchestrator({ ...request2, invoker: invoker2 });
945
- },
946
- checkAuth(agent) {
947
- return invoker2.checkAuth(agent);
948
- }
949
- };
950
- }
951
892
  var init_create_generation_endpoint = __esm({
952
893
  "packages/experience-design-system-generation/dist/src/controller/create-generation-endpoint.js"() {
953
894
  "use strict";
@@ -1332,32 +1273,6 @@ var init_progress = __esm({
1332
1273
  });
1333
1274
 
1334
1275
  // packages/experience-design-system-generation/dist/src/index.js
1335
- var src_exports = {};
1336
- __export(src_exports, {
1337
- AGENT_BINARIES: () => AGENT_BINARIES,
1338
- AGENT_NAMES: () => AGENT_NAMES,
1339
- DEFAULT_AGENT_NAME: () => DEFAULT_AGENT_NAME,
1340
- agentSupportsBedrock: () => agentSupportsBedrock,
1341
- buildArgs: () => buildAgentArgs,
1342
- buildPrompt: () => buildPrompt,
1343
- checkAgentAuth: () => checkAgentAuth,
1344
- createGenerationEndpoint: () => createGenerationEndpoint,
1345
- createLocalCliAgentInvoker: () => createLocalCliAgentInvoker,
1346
- describeAgentFailure: () => describeAgentFailure,
1347
- executeGenerationOrchestrator: () => executeGenerationOrchestrator,
1348
- extractSentinelOutput: () => extractSentinelOutput,
1349
- formatCustomPromptBanner: () => formatCustomPromptBanner,
1350
- formatGenerateProgressLine: () => formatGenerateProgressLine,
1351
- isAgentName: () => isAgentName,
1352
- parseMapTokenPropToolCallLines: () => parseMapTokenPropToolCallLines,
1353
- parseSelectToolCallLines: () => parseSelectToolCallLines,
1354
- parseTokenToolCallLines: () => parseTokenToolCallLines,
1355
- parseToolCallLines: () => parsePropToolCallLines,
1356
- resolveAgentModel: () => resolveAgentModel,
1357
- resolveBinary: () => resolveAgentBinary,
1358
- resolveSkillPath: () => resolveSkillPath,
1359
- runAgent: () => runAgent
1360
- });
1361
1276
  var init_src = __esm({
1362
1277
  "packages/experience-design-system-generation/dist/src/index.js"() {
1363
1278
  "use strict";
@@ -8993,6 +8908,31 @@ function preClassifyComponent(component) {
8993
8908
  });
8994
8909
  return { ...component, props };
8995
8910
  }
8911
+ function bucketComponentProps(component) {
8912
+ const customPropNames = [];
8913
+ const domPassthroughPropNames = [];
8914
+ const otherPropNames = [];
8915
+ for (const prop of component.props) {
8916
+ if (!prop.type.trim()) {
8917
+ otherPropNames.push(prop.name);
8918
+ } else if (prop.domAttribute === true) {
8919
+ domPassthroughPropNames.push(prop.name);
8920
+ } else {
8921
+ customPropNames.push(prop.name);
8922
+ }
8923
+ }
8924
+ const sortNames = (names) => names.toSorted((left, right) => left.localeCompare(right));
8925
+ return {
8926
+ component: component.name,
8927
+ source: component.source,
8928
+ customPropNames: sortNames(customPropNames),
8929
+ domPassthroughPropNames: sortNames(domPassthroughPropNames),
8930
+ otherPropNames: sortNames(otherPropNames)
8931
+ };
8932
+ }
8933
+ function bucketComponentsProps(components) {
8934
+ return components.map(bucketComponentProps).toSorted((left, right) => `${left.component}\0${left.source}`.localeCompare(`${right.component}\0${right.source}`));
8935
+ }
8996
8936
  var init_classify_component_props = __esm({
8997
8937
  "packages/experience-design-system-extraction/dist/src/extract/services/classification/classify-component-props.js"() {
8998
8938
  "use strict";
@@ -9415,38 +9355,6 @@ var init_extract_controller = __esm({
9415
9355
  }
9416
9356
  });
9417
9357
 
9418
- // packages/experience-design-system-extraction/dist/src/extract/services/classification/bucket-component-props.js
9419
- function bucketComponentProps(component) {
9420
- const customPropNames = [];
9421
- const domPassthroughPropNames = [];
9422
- const otherPropNames = [];
9423
- for (const prop of component.props) {
9424
- if (!prop.type.trim()) {
9425
- otherPropNames.push(prop.name);
9426
- } else if (prop.domAttribute === true) {
9427
- domPassthroughPropNames.push(prop.name);
9428
- } else {
9429
- customPropNames.push(prop.name);
9430
- }
9431
- }
9432
- const sortNames = (names) => names.toSorted((left, right) => left.localeCompare(right));
9433
- return {
9434
- component: component.name,
9435
- source: component.source,
9436
- customPropNames: sortNames(customPropNames),
9437
- domPassthroughPropNames: sortNames(domPassthroughPropNames),
9438
- otherPropNames: sortNames(otherPropNames)
9439
- };
9440
- }
9441
- function bucketComponentsProps(components) {
9442
- return components.map(bucketComponentProps).toSorted((left, right) => `${left.component}\0${left.source}`.localeCompare(`${right.component}\0${right.source}`));
9443
- }
9444
- var init_bucket_component_props = __esm({
9445
- "packages/experience-design-system-extraction/dist/src/extract/services/classification/bucket-component-props.js"() {
9446
- "use strict";
9447
- }
9448
- });
9449
-
9450
9358
  // packages/experience-design-system-extraction/dist/src/index.js
9451
9359
  var init_src2 = __esm({
9452
9360
  "packages/experience-design-system-extraction/dist/src/index.js"() {
@@ -9462,7 +9370,6 @@ var init_src2 = __esm({
9462
9370
  init_extractor7();
9463
9371
  init_extractor4();
9464
9372
  init_collect_allowed_component_names();
9465
- init_bucket_component_props();
9466
9373
  init_evaluate_extraction_quality();
9467
9374
  init_evaluate_authorability();
9468
9375
  init_evaluate_authorability();
@@ -9475,6 +9382,106 @@ var init_src2 = __esm({
9475
9382
  }
9476
9383
  });
9477
9384
 
9385
+ // packages/experience-design-system-cli-legacy/src/output/format.ts
9386
+ function detectColors() {
9387
+ if (process.env["NO_COLOR"] !== void 0) return false;
9388
+ if (process.env["FORCE_COLOR"] !== void 0) return true;
9389
+ return process.stderr.isTTY === true;
9390
+ }
9391
+ function formatToolCall(obj) {
9392
+ switch (obj["tool"]) {
9393
+ case "classify_component": {
9394
+ const desc = typeof obj["description"] === "string" ? obj["description"] : null;
9395
+ return desc ? ` ${c.dim("\u2192")} ${c.dim(desc)}` : null;
9396
+ }
9397
+ case "classify_prop": {
9398
+ const prop = String(obj["prop"] ?? "");
9399
+ const type = String(obj["cdf_type"] ?? "");
9400
+ const cat = String(obj["cdf_category"] ?? "");
9401
+ return ` ${c.green("+")} ${prop} ${c.dim(`${type} ${cat}`)}`;
9402
+ }
9403
+ case "exclude_prop": {
9404
+ const prop = String(obj["prop"] ?? "");
9405
+ const reason = typeof obj["reason"] === "string" ? obj["reason"] : "";
9406
+ return ` ${c.dim("\u2013")} ${prop} ${c.dim(reason)}`;
9407
+ }
9408
+ case "classify_slot": {
9409
+ const slot = String(obj["slot"] ?? "");
9410
+ const desc = typeof obj["description"] === "string" ? obj["description"] : "";
9411
+ const req = obj["required"] === true ? c.dim(" required") : "";
9412
+ return ` ${c.cyan("\u25C8")} ${slot}${req} ${c.dim(desc)}`;
9413
+ }
9414
+ case "select_component": {
9415
+ const name = String(obj["name"] ?? "");
9416
+ const reason = typeof obj["reason"] === "string" ? obj["reason"] : "";
9417
+ return ` ${c.green("+")} ${name} ${c.dim(reason)}`;
9418
+ }
9419
+ case "reject_component": {
9420
+ const name = String(obj["name"] ?? "");
9421
+ const reason = typeof obj["reason"] === "string" ? obj["reason"] : "";
9422
+ return ` ${c.dim("\u2013")} ${name} ${c.dim(reason)}`;
9423
+ }
9424
+ default:
9425
+ return null;
9426
+ }
9427
+ }
9428
+ var col, c, OutputFormatter;
9429
+ var init_format = __esm({
9430
+ "packages/experience-design-system-cli-legacy/src/output/format.ts"() {
9431
+ "use strict";
9432
+ col = detectColors();
9433
+ c = {
9434
+ green: (s) => col ? `\x1B[32m${s}\x1B[0m` : s,
9435
+ red: (s) => col ? `\x1B[31m${s}\x1B[0m` : s,
9436
+ cyan: (s) => col ? `\x1B[36m${s}\x1B[0m` : s,
9437
+ yellow: (s) => col ? `\x1B[33m${s}\x1B[0m` : s,
9438
+ dim: (s) => col ? `\x1B[2m${s}\x1B[0m` : s,
9439
+ bold: (s) => col ? `\x1B[1m${s}\x1B[0m` : s
9440
+ };
9441
+ OutputFormatter = class {
9442
+ _buf = "";
9443
+ _verbose;
9444
+ _write;
9445
+ constructor(verbose, write2 = (s) => process.stderr.write(s)) {
9446
+ this._verbose = verbose;
9447
+ this._write = write2;
9448
+ }
9449
+ push(chunk) {
9450
+ this._buf += chunk;
9451
+ const nl = this._buf.lastIndexOf("\n");
9452
+ if (nl === -1) return;
9453
+ const complete = this._buf.slice(0, nl + 1);
9454
+ this._buf = this._buf.slice(nl + 1);
9455
+ for (const line of complete.split("\n")) {
9456
+ this._processLine(line);
9457
+ }
9458
+ }
9459
+ flush() {
9460
+ if (this._buf.trim()) this._processLine(this._buf);
9461
+ this._buf = "";
9462
+ }
9463
+ _processLine(line) {
9464
+ const trimmed = line.trim();
9465
+ if (!trimmed) return;
9466
+ if (trimmed.startsWith("{")) {
9467
+ try {
9468
+ const obj = JSON.parse(trimmed);
9469
+ if (typeof obj["tool"] === "string") {
9470
+ const formatted = formatToolCall(obj);
9471
+ if (formatted !== null) this._write(formatted + "\n");
9472
+ return;
9473
+ }
9474
+ } catch {
9475
+ }
9476
+ }
9477
+ if (this._verbose) {
9478
+ this._write(c.dim(" " + trimmed) + "\n");
9479
+ }
9480
+ }
9481
+ };
9482
+ }
9483
+ });
9484
+
9478
9485
  // packages/experience-design-system-cli-legacy/src/lib/debug-logger.ts
9479
9486
  import { mkdirSync, appendFileSync } from "node:fs";
9480
9487
  import { join as join11, dirname as dirname13 } from "node:path";
@@ -9638,213 +9645,85 @@ var init_debug_logger = __esm({
9638
9645
  }
9639
9646
  });
9640
9647
 
9641
- // packages/experience-design-system-cli-legacy/src/lib/prop-bucket-debug.ts
9642
- function logPropBuckets(stage, assignments) {
9643
- const logger = getDebugLogger();
9644
- if (logger.enabled) {
9645
- for (const assignment of assignments) {
9646
- logger.event("analyze", `prop-buckets.${stage}`, { ...assignment });
9647
- }
9648
+ // packages/experience-design-system-cli-legacy/src/lib/agent-output.ts
9649
+ async function invokeAgentWithOutput(invoker2, options, verbose) {
9650
+ let output = "";
9651
+ const formatter = new OutputFormatter(verbose, (chunk) => {
9652
+ output += chunk;
9653
+ });
9654
+ const result = await invoker2.invoke({
9655
+ ...options,
9656
+ onOutput: (chunk) => formatter.push(chunk)
9657
+ });
9658
+ formatter.flush();
9659
+ return { result, output };
9660
+ }
9661
+ var init_agent_output = __esm({
9662
+ "packages/experience-design-system-cli-legacy/src/lib/agent-output.ts"() {
9663
+ "use strict";
9664
+ init_format();
9648
9665
  }
9649
- return JSON.stringify(assignments.length === 1 && stage === "generate" ? assignments[0] : assignments);
9666
+ });
9667
+
9668
+ // packages/experience-design-system-cli-legacy/src/tui/CommandCompletionView.tsx
9669
+ import { Box, Text as Text2 } from "ink";
9670
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
9671
+ function CommandCompletionView({
9672
+ title,
9673
+ rows,
9674
+ command,
9675
+ instruction
9676
+ }) {
9677
+ return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", padding: 1, children: [
9678
+ /* @__PURE__ */ jsxs(Text2, { color: "green", children: [
9679
+ "\u2713 ",
9680
+ title,
9681
+ " complete"
9682
+ ] }),
9683
+ /* @__PURE__ */ jsx2(Box, { flexDirection: "column", marginTop: 1, children: rows.map((row) => /* @__PURE__ */ jsxs(Text2, { children: [
9684
+ /* @__PURE__ */ jsxs(Text2, { dimColor: true, children: [
9685
+ row.label,
9686
+ " "
9687
+ ] }),
9688
+ /* @__PURE__ */ jsx2(Text2, { children: row.value })
9689
+ ] }, row.label)) }),
9690
+ /* @__PURE__ */ jsxs(Box, { marginTop: 1, children: [
9691
+ /* @__PURE__ */ jsx2(Text2, { dimColor: true, children: "Run " }),
9692
+ /* @__PURE__ */ jsx2(Text2, { children: command }),
9693
+ /* @__PURE__ */ jsxs(Text2, { dimColor: true, children: [
9694
+ " ",
9695
+ instruction
9696
+ ] })
9697
+ ] })
9698
+ ] });
9650
9699
  }
9651
- var init_prop_bucket_debug = __esm({
9652
- "packages/experience-design-system-cli-legacy/src/lib/prop-bucket-debug.ts"() {
9700
+ var init_CommandCompletionView = __esm({
9701
+ "packages/experience-design-system-cli-legacy/src/tui/CommandCompletionView.tsx"() {
9653
9702
  "use strict";
9654
- init_debug_logger();
9655
9703
  }
9656
9704
  });
9657
9705
 
9658
- // packages/experience-design-system-cli-legacy/src/output/format.ts
9659
- function detectColors() {
9660
- if (process.env["NO_COLOR"] !== void 0) return false;
9661
- if (process.env["FORCE_COLOR"] !== void 0) return true;
9662
- return process.stderr.isTTY === true;
9663
- }
9664
- function formatToolCall(obj) {
9665
- switch (obj["tool"]) {
9666
- case "classify_component": {
9667
- const desc = typeof obj["description"] === "string" ? obj["description"] : null;
9668
- return desc ? ` ${c.dim("\u2192")} ${c.dim(desc)}` : null;
9669
- }
9670
- case "classify_prop": {
9671
- const prop = String(obj["prop"] ?? "");
9672
- const type = String(obj["cdf_type"] ?? "");
9673
- const cat = String(obj["cdf_category"] ?? "");
9674
- return ` ${c.green("+")} ${prop} ${c.dim(`${type} ${cat}`)}`;
9675
- }
9676
- case "exclude_prop": {
9677
- const prop = String(obj["prop"] ?? "");
9678
- const reason = typeof obj["reason"] === "string" ? obj["reason"] : "";
9679
- return ` ${c.dim("\u2013")} ${prop} ${c.dim(reason)}`;
9680
- }
9681
- case "classify_slot": {
9682
- const slot = String(obj["slot"] ?? "");
9683
- const desc = typeof obj["description"] === "string" ? obj["description"] : "";
9684
- const req = obj["required"] === true ? c.dim(" required") : "";
9685
- return ` ${c.cyan("\u25C8")} ${slot}${req} ${c.dim(desc)}`;
9686
- }
9687
- case "select_component": {
9688
- const name = String(obj["name"] ?? "");
9689
- const reason = typeof obj["reason"] === "string" ? obj["reason"] : "";
9690
- return ` ${c.green("+")} ${name} ${c.dim(reason)}`;
9691
- }
9692
- case "reject_component": {
9693
- const name = String(obj["name"] ?? "");
9694
- const reason = typeof obj["reason"] === "string" ? obj["reason"] : "";
9695
- return ` ${c.dim("\u2013")} ${name} ${c.dim(reason)}`;
9696
- }
9697
- default:
9698
- return null;
9699
- }
9700
- }
9701
- var col, c, OutputFormatter;
9702
- var init_format = __esm({
9703
- "packages/experience-design-system-cli-legacy/src/output/format.ts"() {
9704
- "use strict";
9705
- col = detectColors();
9706
- c = {
9707
- green: (s) => col ? `\x1B[32m${s}\x1B[0m` : s,
9708
- red: (s) => col ? `\x1B[31m${s}\x1B[0m` : s,
9709
- cyan: (s) => col ? `\x1B[36m${s}\x1B[0m` : s,
9710
- yellow: (s) => col ? `\x1B[33m${s}\x1B[0m` : s,
9711
- dim: (s) => col ? `\x1B[2m${s}\x1B[0m` : s,
9712
- bold: (s) => col ? `\x1B[1m${s}\x1B[0m` : s
9713
- };
9714
- OutputFormatter = class {
9715
- _buf = "";
9716
- _verbose;
9717
- _write;
9718
- constructor(verbose, write2 = (s) => process.stderr.write(s)) {
9719
- this._verbose = verbose;
9720
- this._write = write2;
9721
- }
9722
- push(chunk) {
9723
- this._buf += chunk;
9724
- const nl = this._buf.lastIndexOf("\n");
9725
- if (nl === -1) return;
9726
- const complete = this._buf.slice(0, nl + 1);
9727
- this._buf = this._buf.slice(nl + 1);
9728
- for (const line of complete.split("\n")) {
9729
- this._processLine(line);
9730
- }
9731
- }
9732
- flush() {
9733
- if (this._buf.trim()) this._processLine(this._buf);
9734
- this._buf = "";
9735
- }
9736
- _processLine(line) {
9737
- const trimmed = line.trim();
9738
- if (!trimmed) return;
9739
- if (trimmed.startsWith("{")) {
9740
- try {
9741
- const obj = JSON.parse(trimmed);
9742
- if (typeof obj["tool"] === "string") {
9743
- const formatted = formatToolCall(obj);
9744
- if (formatted !== null) this._write(formatted + "\n");
9745
- return;
9746
- }
9747
- } catch {
9748
- }
9749
- }
9750
- if (this._verbose) {
9751
- this._write(c.dim(" " + trimmed) + "\n");
9752
- }
9753
- }
9754
- };
9755
- }
9756
- });
9757
-
9758
- // packages/experience-design-system-cli-legacy/src/session/core/components/strip-extraction-provenance.ts
9759
- function stripPropProvenance(prop) {
9760
- const { domAttribute: _domAttribute, ...authorableProp } = prop;
9761
- return authorableProp;
9762
- }
9763
- var init_strip_extraction_provenance = __esm({
9764
- "packages/experience-design-system-cli-legacy/src/session/core/components/strip-extraction-provenance.ts"() {
9765
- "use strict";
9766
- }
9767
- });
9768
-
9769
- // packages/experience-design-system-cli-legacy/src/lib/agent-output.ts
9770
- async function invokeAgentWithOutput(invoker2, options, verbose) {
9771
- let output = "";
9772
- const formatter = new OutputFormatter(verbose, (chunk) => {
9773
- output += chunk;
9774
- });
9775
- const result = await invoker2.invoke({
9776
- ...options,
9777
- onOutput: (chunk) => formatter.push(chunk)
9778
- });
9779
- formatter.flush();
9780
- return { result, output };
9781
- }
9782
- var init_agent_output = __esm({
9783
- "packages/experience-design-system-cli-legacy/src/lib/agent-output.ts"() {
9784
- "use strict";
9785
- init_format();
9786
- }
9787
- });
9788
-
9789
- // packages/experience-design-system-cli-legacy/src/tui/CommandCompletionView.tsx
9790
- import { Box, Text as Text2 } from "ink";
9791
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
9792
- function CommandCompletionView({
9793
- title,
9794
- rows,
9795
- command,
9796
- instruction
9797
- }) {
9798
- return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", padding: 1, children: [
9799
- /* @__PURE__ */ jsxs(Text2, { color: "green", children: [
9800
- "\u2713 ",
9801
- title,
9802
- " complete"
9803
- ] }),
9804
- /* @__PURE__ */ jsx2(Box, { flexDirection: "column", marginTop: 1, children: rows.map((row) => /* @__PURE__ */ jsxs(Text2, { children: [
9805
- /* @__PURE__ */ jsxs(Text2, { dimColor: true, children: [
9806
- row.label,
9807
- " "
9808
- ] }),
9809
- /* @__PURE__ */ jsx2(Text2, { children: row.value })
9810
- ] }, row.label)) }),
9811
- /* @__PURE__ */ jsxs(Box, { marginTop: 1, children: [
9812
- /* @__PURE__ */ jsx2(Text2, { dimColor: true, children: "Run " }),
9813
- /* @__PURE__ */ jsx2(Text2, { children: command }),
9814
- /* @__PURE__ */ jsxs(Text2, { dimColor: true, children: [
9815
- " ",
9816
- instruction
9817
- ] })
9818
- ] })
9819
- ] });
9820
- }
9821
- var init_CommandCompletionView = __esm({
9822
- "packages/experience-design-system-cli-legacy/src/tui/CommandCompletionView.tsx"() {
9823
- "use strict";
9824
- }
9825
- });
9826
-
9827
- // packages/experience-design-system-cli-legacy/src/generate/tui/GenerateView.tsx
9828
- import React2 from "react";
9829
- import { jsx as jsx3 } from "react/jsx-runtime";
9830
- function GenerateView({ result, onExit }) {
9831
- React2.useEffect(() => {
9832
- const timer = setTimeout(onExit, 100);
9833
- return () => clearTimeout(timer);
9834
- }, [onExit]);
9835
- return /* @__PURE__ */ jsx3(
9836
- CommandCompletionView,
9837
- {
9838
- title: "generate",
9839
- rows: [
9840
- { label: "skill", value: result.skill },
9841
- { label: "agent", value: result.agent },
9842
- { label: "session", value: result.sessionId }
9843
- ],
9844
- command: `experience-design-system-cli print ${result.skill}`,
9845
- instruction: "to write the output file."
9846
- }
9847
- );
9706
+ // packages/experience-design-system-cli-legacy/src/generate/tui/GenerateView.tsx
9707
+ import React2 from "react";
9708
+ import { jsx as jsx3 } from "react/jsx-runtime";
9709
+ function GenerateView({ result, onExit }) {
9710
+ React2.useEffect(() => {
9711
+ const timer = setTimeout(onExit, 100);
9712
+ return () => clearTimeout(timer);
9713
+ }, [onExit]);
9714
+ return /* @__PURE__ */ jsx3(
9715
+ CommandCompletionView,
9716
+ {
9717
+ title: "generate",
9718
+ rows: [
9719
+ { label: "skill", value: result.skill },
9720
+ { label: "agent", value: result.agent },
9721
+ { label: "session", value: result.sessionId }
9722
+ ],
9723
+ command: `experience-design-system-cli print ${result.skill}`,
9724
+ instruction: "to write the output file."
9725
+ }
9726
+ );
9848
9727
  }
9849
9728
  var init_GenerateView = __esm({
9850
9729
  "packages/experience-design-system-cli-legacy/src/generate/tui/GenerateView.tsx"() {
@@ -10393,41 +10272,6 @@ var init_read3 = __esm({
10393
10272
  }
10394
10273
  });
10395
10274
 
10396
- // packages/experience-design-system-cli-legacy/src/session/core/components/hash-component-shape.ts
10397
- import { createHash as createHash2 } from "node:crypto";
10398
- function hashComponentShape(component) {
10399
- const payload = {
10400
- framework: component.framework,
10401
- name: component.name,
10402
- source: component.source,
10403
- props: component.props.map((p) => ({
10404
- name: p.name,
10405
- type: p.type
10406
- })),
10407
- slots: component.slots.map((s) => ({
10408
- name: s.name,
10409
- isDefault: s.isDefault
10410
- }))
10411
- };
10412
- return createHash2("sha256").update(JSON.stringify(payload)).digest("hex");
10413
- }
10414
- var init_hash_component_shape = __esm({
10415
- "packages/experience-design-system-cli-legacy/src/session/core/components/hash-component-shape.ts"() {
10416
- "use strict";
10417
- }
10418
- });
10419
-
10420
- // packages/experience-design-system-cli-legacy/src/session/core/tokens/hash-token-content.ts
10421
- import { createHash as createHash3 } from "node:crypto";
10422
- function hashTokenContent(rawTokenContent) {
10423
- return createHash3("sha256").update(rawTokenContent.trim()).digest("hex");
10424
- }
10425
- var init_hash_token_content = __esm({
10426
- "packages/experience-design-system-cli-legacy/src/session/core/tokens/hash-token-content.ts"() {
10427
- "use strict";
10428
- }
10429
- });
10430
-
10431
10275
  // packages/experience-design-system-cli-legacy/src/session/repositories/tokens/write.ts
10432
10276
  function deleteRawTokensForSession(db, sessionId2) {
10433
10277
  db.prepare("DELETE FROM raw_token_groups WHERE session_id = ?").run(sessionId2);
@@ -10591,47 +10435,17 @@ var init_replace_raw_prop_token_paths = __esm({
10591
10435
  }
10592
10436
  });
10593
10437
 
10594
- // packages/experience-design-system-cli-legacy/src/session/cache-keys.ts
10595
- var cache_keys_exports = {};
10596
- __export(cache_keys_exports, {
10597
- hashContent: () => hashContent,
10598
- hashFile: () => hashFile,
10599
- hashPromptForSkill: () => hashPromptForSkill
10600
- });
10601
- import { createHash as createHash4 } from "node:crypto";
10602
- import { readFile as readFile7 } from "node:fs/promises";
10603
- import { resolve as resolve8 } from "node:path";
10604
- function hashContent(content) {
10605
- return createHash4("sha256").update(content).digest("hex");
10606
- }
10607
- async function hashFile(filePath) {
10608
- const content = await readFile7(filePath, "utf8");
10609
- return hashContent(content);
10610
- }
10611
- async function hashPromptForSkill(skill, agent, model, skillPathOverride, extraInputs = [], skillContentOverride) {
10612
- const promptHash = skillContentOverride ? hashContent(skillContentOverride) : skillPathOverride ? await hashFile(resolve8(skillPathOverride)) : await hashFile(resolveSkillPath(skill));
10613
- const extraSegment = extraInputs.length > 0 ? `|${extraInputs.join("|")}` : "";
10614
- return hashContent(`${promptHash}|${agent}|${model ?? ""}${extraSegment}`);
10615
- }
10616
- var init_cache_keys = __esm({
10617
- "packages/experience-design-system-cli-legacy/src/session/cache-keys.ts"() {
10618
- "use strict";
10619
- init_src();
10620
- }
10621
- });
10622
-
10623
10438
  // packages/experience-design-system-cli-legacy/src/session/db.ts
10624
10439
  import { DatabaseSync } from "node:sqlite";
10625
10440
  import { mkdirSync as mkdirSync2, readFileSync as readFileSync5 } from "node:fs";
10626
- import { readFile as readFile8 } from "node:fs/promises";
10627
- import { createHash as createHash5 } from "node:crypto";
10441
+ import { readFile as readFile7 } from "node:fs/promises";
10628
10442
  import { homedir as homedir3 } from "node:os";
10629
- import { dirname as dirname14, resolve as resolve9 } from "node:path";
10443
+ import { dirname as dirname14, resolve as resolve8 } from "node:path";
10630
10444
  function getPipelineDbPath() {
10631
10445
  if (process.env.EDS_PIPELINE_DB_PATH) {
10632
- return resolve9(process.env.EDS_PIPELINE_DB_PATH);
10446
+ return resolve8(process.env.EDS_PIPELINE_DB_PATH);
10633
10447
  }
10634
- return resolve9(homedir3(), ".contentful", "experience-design-system-cli", "pipeline.db");
10448
+ return resolve8(homedir3(), ".contentful", "experience-design-system-cli", "pipeline.db");
10635
10449
  }
10636
10450
  function openPipelineDb(dbPath) {
10637
10451
  const path = dbPath ?? getPipelineDbPath();
@@ -10765,134 +10579,8 @@ function applyDbMigrations(db) {
10765
10579
  if (!rawSlotColsForRationale.some((c2) => c2.name === "rationale")) {
10766
10580
  db.exec("ALTER TABLE raw_slots ADD COLUMN rationale TEXT");
10767
10581
  }
10768
- const hasExtractCache = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='extract_cache'`).all();
10769
- if (hasExtractCache.length === 0) {
10770
- db.exec(`
10771
- CREATE TABLE extract_cache (
10772
- file_path TEXT NOT NULL,
10773
- file_hash TEXT NOT NULL,
10774
- cli_version TEXT NOT NULL,
10775
- created_at TEXT NOT NULL,
10776
- updated_at TEXT NOT NULL,
10777
- components_json TEXT NOT NULL,
10778
- PRIMARY KEY (file_hash, cli_version)
10779
- );
10780
- CREATE INDEX idx_extract_cache_file ON extract_cache(file_path);
10781
- `);
10782
- }
10783
- const hasSelectCache = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='select_cache'`).all();
10784
- if (hasSelectCache.length === 0) {
10785
- db.exec(`
10786
- CREATE TABLE select_cache (
10787
- component_hash TEXT NOT NULL,
10788
- prompt_hash TEXT NOT NULL,
10789
- cli_version TEXT NOT NULL,
10790
- decision TEXT NOT NULL CHECK (decision IN ('accepted','rejected')),
10791
- reason TEXT,
10792
- created_at TEXT NOT NULL,
10793
- updated_at TEXT NOT NULL,
10794
- PRIMARY KEY (component_hash, prompt_hash, cli_version)
10795
- );
10796
- `);
10797
- }
10798
- const tables = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='generation_cache'`).all();
10799
- if (tables.length === 0) {
10800
- db.exec(`
10801
- CREATE TABLE generation_cache (
10802
- input_hash TEXT NOT NULL,
10803
- entity_type TEXT NOT NULL CHECK (entity_type IN ('component', 'token_set', 'token_mapping')),
10804
- entity_id TEXT NOT NULL,
10805
- source_session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
10806
- human_edited INTEGER NOT NULL DEFAULT 0 CHECK (human_edited IN (0, 1)),
10807
- created_at TEXT NOT NULL,
10808
- updated_at TEXT NOT NULL,
10809
- PRIMARY KEY (input_hash, entity_type, entity_id)
10810
- );
10811
- CREATE INDEX idx_generation_cache_entity ON generation_cache(entity_type, entity_id);
10812
- CREATE INDEX idx_generation_cache_session ON generation_cache(source_session_id);
10813
- `);
10814
- }
10815
- const genCacheCols = db.prepare(`PRAGMA table_info(generation_cache)`).all();
10816
- const hasPromptHash = genCacheCols.some((c2) => c2.name === "prompt_hash");
10817
- const oldPkCols = genCacheCols.filter((c2) => c2.pk > 0).map((c2) => c2.name);
10818
- const promptHashInPk = oldPkCols.includes("prompt_hash");
10819
- if (!hasPromptHash) {
10820
- db.exec(`ALTER TABLE generation_cache ADD COLUMN prompt_hash TEXT NOT NULL DEFAULT ''`);
10821
- }
10822
- if (!promptHashInPk) {
10823
- db.exec("BEGIN");
10824
- try {
10825
- db.exec(`
10826
- CREATE TABLE generation_cache__new (
10827
- input_hash TEXT NOT NULL,
10828
- entity_type TEXT NOT NULL CHECK (entity_type IN ('component', 'token_set', 'token_mapping')),
10829
- entity_id TEXT NOT NULL,
10830
- source_session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
10831
- human_edited INTEGER NOT NULL DEFAULT 0 CHECK (human_edited IN (0, 1)),
10832
- created_at TEXT NOT NULL,
10833
- updated_at TEXT NOT NULL,
10834
- prompt_hash TEXT NOT NULL DEFAULT '',
10835
- PRIMARY KEY (input_hash, prompt_hash, entity_type, entity_id)
10836
- );
10837
- INSERT INTO generation_cache__new
10838
- (input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash)
10839
- SELECT input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash
10840
- FROM generation_cache;
10841
- DROP TABLE generation_cache;
10842
- ALTER TABLE generation_cache__new RENAME TO generation_cache;
10843
- CREATE INDEX IF NOT EXISTS idx_generation_cache_entity ON generation_cache(entity_type, entity_id);
10844
- CREATE INDEX IF NOT EXISTS idx_generation_cache_session ON generation_cache(source_session_id);
10845
- `);
10846
- db.exec("COMMIT");
10847
- } catch (e) {
10848
- db.exec("ROLLBACK");
10849
- throw e;
10850
- }
10851
- }
10852
- const genCacheTableSql = db.prepare(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'generation_cache'`).get();
10853
- const hasTokenMappingEntityType = genCacheTableSql?.sql.includes("'token_mapping'") ?? true;
10854
- if (!hasTokenMappingEntityType) {
10855
- db.exec("BEGIN");
10856
- try {
10857
- db.exec(`
10858
- CREATE TABLE generation_cache__new2 (
10859
- input_hash TEXT NOT NULL,
10860
- entity_type TEXT NOT NULL CHECK (entity_type IN ('component', 'token_set', 'token_mapping')),
10861
- entity_id TEXT NOT NULL,
10862
- source_session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
10863
- human_edited INTEGER NOT NULL DEFAULT 0 CHECK (human_edited IN (0, 1)),
10864
- created_at TEXT NOT NULL,
10865
- updated_at TEXT NOT NULL,
10866
- prompt_hash TEXT NOT NULL DEFAULT '',
10867
- PRIMARY KEY (input_hash, prompt_hash, entity_type, entity_id)
10868
- );
10869
- INSERT INTO generation_cache__new2
10870
- (input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash)
10871
- SELECT input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash
10872
- FROM generation_cache;
10873
- DROP TABLE generation_cache;
10874
- ALTER TABLE generation_cache__new2 RENAME TO generation_cache;
10875
- CREATE INDEX IF NOT EXISTS idx_generation_cache_entity ON generation_cache(entity_type, entity_id);
10876
- CREATE INDEX IF NOT EXISTS idx_generation_cache_session ON generation_cache(source_session_id);
10877
- `);
10878
- db.exec("COMMIT");
10879
- } catch (e) {
10880
- db.exec("ROLLBACK");
10881
- throw e;
10882
- }
10883
- }
10884
- const hasCompositionCache = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='composition_cache'`).all();
10885
- if (hasCompositionCache.length === 0) {
10886
- db.exec(`
10887
- CREATE TABLE composition_cache (
10888
- input_hash TEXT NOT NULL,
10889
- cli_version TEXT NOT NULL,
10890
- agent_output TEXT NOT NULL,
10891
- created_at TEXT NOT NULL,
10892
- updated_at TEXT NOT NULL,
10893
- PRIMARY KEY (input_hash, cli_version)
10894
- );
10895
- `);
10582
+ for (const table of REMOVED_CACHE_TABLES) {
10583
+ db.exec(`DROP TABLE IF EXISTS ${table}`);
10896
10584
  }
10897
10585
  }
10898
10586
  function loadComponentReviewMetadata(db, sessionId2, componentName) {
@@ -11149,6 +10837,10 @@ function updateStep(db, stepId, status, outputs, error) {
11149
10837
  throw e;
11150
10838
  }
11151
10839
  }
10840
+ function stripPropProvenance(prop) {
10841
+ const { domAttribute: _domAttribute, ...authorableProp } = prop;
10842
+ return authorableProp;
10843
+ }
11152
10844
  function storeRawComponents(db, sessionId2, components, options) {
11153
10845
  const now = (/* @__PURE__ */ new Date()).toISOString();
11154
10846
  const insertComp = db.prepare(
@@ -11428,16 +11120,16 @@ function extractRelativeImportPaths(sourceText) {
11428
11120
  return [...specifiers];
11429
11121
  }
11430
11122
  async function resolveRelativeImport(specifier, fromDir) {
11431
- const basePath = resolve9(fromDir, specifier);
11123
+ const basePath = resolve8(fromDir, specifier);
11432
11124
  const candidates = [
11433
11125
  basePath,
11434
11126
  ...rewrittenSourcePaths(basePath),
11435
11127
  ...SIBLING_FILE_EXTENSIONS.map((ext) => `${basePath}${ext}`),
11436
- ...SIBLING_FILE_EXTENSIONS.map((ext) => resolve9(basePath, `index${ext}`))
11128
+ ...SIBLING_FILE_EXTENSIONS.map((ext) => resolve8(basePath, `index${ext}`))
11437
11129
  ];
11438
11130
  for (const candidate of candidates) {
11439
11131
  try {
11440
- await readFile8(candidate, "utf8");
11132
+ await readFile7(candidate, "utf8");
11441
11133
  return candidate;
11442
11134
  } catch {
11443
11135
  }
@@ -11453,7 +11145,7 @@ async function resolveImportSpecifiers(sourceText, fromDir) {
11453
11145
  return resolvedPaths;
11454
11146
  }
11455
11147
  async function loadSiblingFiles(sourceText, sourcePath, propNames, candidateTypeNames = []) {
11456
- const visited = /* @__PURE__ */ new Set([resolve9(sourcePath)]);
11148
+ const visited = /* @__PURE__ */ new Set([resolve8(sourcePath)]);
11457
11149
  const discovered = [];
11458
11150
  let frontier = [{ text: sourceText, dir: dirname14(sourcePath) }];
11459
11151
  for (let hop = 0; hop < MAX_SIBLING_DEPTH && discovered.length < MAX_SIBLING_CANDIDATES_EXPLORED; hop++) {
@@ -11467,7 +11159,7 @@ async function loadSiblingFiles(sourceText, sourcePath, propNames, candidateType
11467
11159
  if (discovered.length >= MAX_SIBLING_CANDIDATES_EXPLORED) break;
11468
11160
  let content;
11469
11161
  try {
11470
- content = await readFile8(resolvedPath, "utf8");
11162
+ content = await readFile7(resolvedPath, "utf8");
11471
11163
  } catch {
11472
11164
  continue;
11473
11165
  }
@@ -11504,7 +11196,7 @@ async function loadComponentSourceRef(name, sourcePath, propNames = [], propType
11504
11196
  let truncatedSiblingCount = 0;
11505
11197
  const usesNotShown = /* @__PURE__ */ new Set();
11506
11198
  try {
11507
- const rawText = await readFile8(sourcePath, "utf8");
11199
+ const rawText = await readFile7(sourcePath, "utf8");
11508
11200
  let siblingUsesNotShown;
11509
11201
  let declaredTypeNames;
11510
11202
  ({
@@ -11940,108 +11632,6 @@ function backfillUnclassifiedProps(db, sessionId2) {
11940
11632
  ).run(sessionId2, sessionId2);
11941
11633
  return Number(withCategory.changes) + Number(withoutCategory.changes);
11942
11634
  }
11943
- function computeMapTokensInputHash(db, sessionId2, componentSourceRefs = []) {
11944
- const props = db.prepare(
11945
- `SELECT rc.name AS component_name, rp.name AS prop_name, rp.cdf_token_kind, rp.default_value
11946
- FROM raw_props rp
11947
- JOIN raw_components rc ON rc.session_id = rp.session_id AND rc.component_id = rp.component_id
11948
- WHERE rp.session_id = ? AND rp.cdf_type = 'token' AND rp.cdf_category = 'design'
11949
- ORDER BY rc.name, rp.name`
11950
- ).all(sessionId2);
11951
- const tokens = db.prepare(`SELECT path, type FROM raw_tokens WHERE session_id = ? ORDER BY path`).all(sessionId2);
11952
- const defaultMappings = db.prepare("SELECT raw_name, path, source FROM raw_token_name_paths WHERE session_id = ? ORDER BY raw_name").all(sessionId2);
11953
- const payload = {
11954
- props: props.map((p) => ({
11955
- component: p.component_name,
11956
- prop: p.prop_name,
11957
- tokenKind: p.cdf_token_kind,
11958
- rawDefault: p.default_value
11959
- })),
11960
- tokens,
11961
- defaultMappings,
11962
- // The agent's evidence, not just its inputs: a comment or allowlist edit
11963
- // in a source file (or a sibling it reads) changes the correct answer
11964
- // without touching props or tokens, so it must invalidate the cache too.
11965
- sourceRefs: [...componentSourceRefs].sort((a, b) => a.component.localeCompare(b.component)).map((ref) => ({
11966
- component: ref.component,
11967
- content: ref.content,
11968
- siblingFiles: (ref.siblingFiles ?? []).map((s) => ({ path: s.path, content: s.content })).sort((a, b) => a.path.localeCompare(b.path)),
11969
- usesNotShown: [...ref.usesNotShown ?? []].sort()
11970
- }))
11971
- };
11972
- return createHash5("sha256").update(JSON.stringify(payload)).digest("hex");
11973
- }
11974
- function lookupCache(db, inputHash, entityType, entityId, promptHash = "") {
11975
- const row = db.prepare(
11976
- `SELECT input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash
11977
- FROM generation_cache
11978
- WHERE input_hash = ? AND entity_type = ? AND entity_id = ? AND prompt_hash = ?`
11979
- ).get(inputHash, entityType, entityId, promptHash);
11980
- if (!row) return null;
11981
- return {
11982
- inputHash: row.input_hash,
11983
- entityType: row.entity_type,
11984
- entityId: row.entity_id,
11985
- sourceSessionId: row.source_session_id,
11986
- humanEdited: row.human_edited === 1,
11987
- promptHash: row.prompt_hash,
11988
- createdAt: row.created_at,
11989
- updatedAt: row.updated_at
11990
- };
11991
- }
11992
- function lookupCacheByEntity(db, entityType, entityId) {
11993
- const row = db.prepare(
11994
- `SELECT input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash
11995
- FROM generation_cache
11996
- WHERE entity_type = ? AND entity_id = ?
11997
- ORDER BY updated_at DESC LIMIT 1`
11998
- ).get(entityType, entityId);
11999
- if (!row) return null;
12000
- return {
12001
- inputHash: row.input_hash,
12002
- entityType: row.entity_type,
12003
- entityId: row.entity_id,
12004
- sourceSessionId: row.source_session_id,
12005
- humanEdited: row.human_edited === 1,
12006
- promptHash: row.prompt_hash,
12007
- createdAt: row.created_at,
12008
- updatedAt: row.updated_at
12009
- };
12010
- }
12011
- function storeCache(db, inputHash, entityType, entityId, sourceSessionId, humanEdited, promptHash = "") {
12012
- storeCaches(db, [{ inputHash, entityType, entityId, sourceSessionId, humanEdited, promptHash }]);
12013
- }
12014
- function storeCaches(db, entries) {
12015
- if (entries.length === 0) return;
12016
- const now = (/* @__PURE__ */ new Date()).toISOString();
12017
- const insert = db.prepare(
12018
- `INSERT INTO generation_cache (input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash)
12019
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
12020
- ON CONFLICT(input_hash, prompt_hash, entity_type, entity_id) DO UPDATE SET
12021
- source_session_id = excluded.source_session_id,
12022
- human_edited = CASE WHEN generation_cache.human_edited = 1 THEN 1 ELSE excluded.human_edited END,
12023
- updated_at = excluded.updated_at`
12024
- );
12025
- db.exec("BEGIN");
12026
- try {
12027
- for (const entry of entries) {
12028
- insert.run(
12029
- entry.inputHash,
12030
- entry.entityType,
12031
- entry.entityId,
12032
- entry.sourceSessionId,
12033
- entry.humanEdited ? 1 : 0,
12034
- now,
12035
- now,
12036
- entry.promptHash ?? ""
12037
- );
12038
- }
12039
- db.exec("COMMIT");
12040
- } catch (e) {
12041
- db.exec("ROLLBACK");
12042
- throw e;
12043
- }
12044
- }
12045
11635
  function storeScannedFiles(db, sessionId2, filePaths) {
12046
11636
  db.exec("BEGIN");
12047
11637
  try {
@@ -12124,105 +11714,7 @@ function filterUnknownSlotAllowedComponents(db, sessionId2, allowedComponentName
12124
11714
  }
12125
11715
  return unknown;
12126
11716
  }
12127
- function copyComponentFromCache(db, sourceSessionId, targetSessionId, componentId, manageTransaction = true, options = {}) {
12128
- const now = (/* @__PURE__ */ new Date()).toISOString();
12129
- if (manageTransaction) db.exec("BEGIN");
12130
- try {
12131
- const srcComp = db.prepare(
12132
- `SELECT description, status, component_description_rationale, props_rationale, slots_rationale
12133
- FROM raw_components WHERE session_id = ? AND component_id = ?`
12134
- ).get(sourceSessionId, componentId);
12135
- if (srcComp) {
12136
- db.prepare(
12137
- `UPDATE raw_components
12138
- SET description = ?, status = ?, component_description_rationale = ?, props_rationale = ?, slots_rationale = ?, extracted_at = ?
12139
- WHERE session_id = ? AND component_id = ?`
12140
- ).run(
12141
- srcComp.description,
12142
- srcComp.status,
12143
- srcComp.component_description_rationale,
12144
- srcComp.props_rationale,
12145
- srcComp.slots_rationale,
12146
- now,
12147
- targetSessionId,
12148
- componentId
12149
- );
12150
- }
12151
- const srcProps = db.prepare(
12152
- `SELECT name, cdf_type, cdf_category, cdf_token_kind, required, description, default_value, rationale
12153
- FROM raw_props WHERE session_id = ? AND component_id = ?`
12154
- ).all(sourceSessionId, componentId);
12155
- for (const p of srcProps) {
12156
- db.prepare(
12157
- `UPDATE raw_props SET cdf_type = ?, cdf_category = ?, cdf_token_kind = ?, required = ?, description = ?, default_value = ?, rationale = ?
12158
- WHERE session_id = ? AND component_id = ? AND name = ?`
12159
- ).run(
12160
- p.cdf_type,
12161
- p.cdf_category,
12162
- p.cdf_token_kind,
12163
- p.required,
12164
- p.description,
12165
- p.default_value,
12166
- p.rationale,
12167
- targetSessionId,
12168
- componentId,
12169
- p.name
12170
- );
12171
- }
12172
- db.prepare(`DELETE FROM raw_prop_allowed_values WHERE session_id = ? AND component_id = ?`).run(
12173
- targetSessionId,
12174
- componentId
12175
- );
12176
- const srcAV = db.prepare(
12177
- `SELECT prop_name, position, value FROM raw_prop_allowed_values WHERE session_id = ? AND component_id = ?`
12178
- ).all(sourceSessionId, componentId);
12179
- const insertAV = db.prepare(
12180
- `INSERT INTO raw_prop_allowed_values (session_id, component_id, prop_name, position, value) VALUES (?, ?, ?, ?, ?)`
12181
- );
12182
- for (const av of srcAV) {
12183
- insertAV.run(targetSessionId, componentId, av.prop_name, av.position, av.value);
12184
- }
12185
- const srcSlots = db.prepare(`SELECT name, required, description, rationale FROM raw_slots WHERE session_id = ? AND component_id = ?`).all(sourceSessionId, componentId);
12186
- for (const s of srcSlots) {
12187
- db.prepare(
12188
- `UPDATE raw_slots SET required = ?, description = ?, rationale = ? WHERE session_id = ? AND component_id = ? AND name = ?`
12189
- ).run(s.required, s.description, s.rationale, targetSessionId, componentId, s.name);
12190
- }
12191
- db.prepare(`DELETE FROM raw_slot_allowed_components WHERE session_id = ? AND component_id = ?`).run(
12192
- targetSessionId,
12193
- componentId
12194
- );
12195
- const srcSAC = db.prepare(
12196
- `SELECT slot_name, position, allowed_component FROM raw_slot_allowed_components WHERE session_id = ? AND component_id = ?`
12197
- ).all(sourceSessionId, componentId);
12198
- const insertSAC = db.prepare(
12199
- `INSERT INTO raw_slot_allowed_components (session_id, component_id, slot_name, allowed_component, position) VALUES (?, ?, ?, ?, ?)`
12200
- );
12201
- const allowedSAC = options.allowedComponentNames ? srcSAC.filter((sac) => options.allowedComponentNames.has(sac.allowed_component)) : srcSAC;
12202
- for (const sac of allowedSAC) {
12203
- insertSAC.run(targetSessionId, componentId, sac.slot_name, sac.allowed_component, sac.position);
12204
- }
12205
- db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, targetSessionId);
12206
- if (manageTransaction) db.exec("COMMIT");
12207
- } catch (e) {
12208
- if (manageTransaction) db.exec("ROLLBACK");
12209
- throw e;
12210
- }
12211
- }
12212
- function copyComponentsFromCache(db, entries, options = {}) {
12213
- if (entries.length === 0) return;
12214
- db.exec("BEGIN");
12215
- try {
12216
- for (const entry of entries) {
12217
- copyComponentFromCache(db, entry.sourceSessionId, entry.targetSessionId, entry.componentId, false, options);
12218
- }
12219
- db.exec("COMMIT");
12220
- } catch (e) {
12221
- db.exec("ROLLBACK");
12222
- throw e;
12223
- }
12224
- }
12225
- function copyTokensFromCache(db, sourceSessionId, targetSessionId) {
11717
+ function copyTokensBetweenSessions(db, sourceSessionId, targetSessionId) {
12226
11718
  const now = (/* @__PURE__ */ new Date()).toISOString();
12227
11719
  db.exec("BEGIN");
12228
11720
  try {
@@ -12243,153 +11735,7 @@ function copyTokensFromCache(db, sourceSessionId, targetSessionId) {
12243
11735
  throw e;
12244
11736
  }
12245
11737
  }
12246
- function copyMapTokensFromCache(db, sourceSessionId, targetSessionId) {
12247
- const now = (/* @__PURE__ */ new Date()).toISOString();
12248
- let copiedCount = 0;
12249
- db.exec("BEGIN");
12250
- try {
12251
- const sourceRows = db.prepare(
12252
- `SELECT rc.name AS component_name, rptp.prop_name, rptp.source, rptp.position, rptp.path
12253
- FROM raw_prop_token_paths rptp
12254
- JOIN raw_components rc ON rc.session_id = rptp.session_id AND rc.component_id = rptp.component_id
12255
- WHERE rptp.session_id = ?
12256
- ORDER BY rc.name, rptp.prop_name, rptp.position`
12257
- ).all(sourceSessionId);
12258
- const targetComponents = db.prepare(`SELECT component_id, name FROM raw_components WHERE session_id = ?`).all(targetSessionId);
12259
- const targetIdByName = new Map(targetComponents.map((c2) => [c2.name, c2.component_id]));
12260
- const targetProps = new Set(
12261
- db.prepare(`SELECT component_id, name FROM raw_props WHERE session_id = ?`).all(targetSessionId).map((p) => `${p.component_id}::${p.name}`)
12262
- );
12263
- const insertPath = db.prepare(
12264
- `INSERT INTO raw_prop_token_paths (session_id, component_id, prop_name, source, position, path)
12265
- VALUES (?, ?, ?, ?, ?, ?)`
12266
- );
12267
- const clearedProps = /* @__PURE__ */ new Set();
12268
- const copiedProps = /* @__PURE__ */ new Set();
12269
- for (const row of sourceRows) {
12270
- const targetComponentId = targetIdByName.get(row.component_name);
12271
- if (!targetComponentId) continue;
12272
- if (!targetProps.has(`${targetComponentId}::${row.prop_name}`)) continue;
12273
- const propKey = `${targetComponentId}::${row.prop_name}`;
12274
- if (!clearedProps.has(propKey)) {
12275
- clearedProps.add(propKey);
12276
- db.prepare(`DELETE FROM raw_prop_token_paths WHERE session_id = ? AND component_id = ? AND prop_name = ?`).run(
12277
- targetSessionId,
12278
- targetComponentId,
12279
- row.prop_name
12280
- );
12281
- }
12282
- insertPath.run(targetSessionId, targetComponentId, row.prop_name, row.source, row.position, row.path);
12283
- copiedProps.add(propKey);
12284
- }
12285
- copiedCount = copiedProps.size;
12286
- db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, targetSessionId);
12287
- db.exec("COMMIT");
12288
- } catch (e) {
12289
- db.exec("ROLLBACK");
12290
- throw e;
12291
- }
12292
- return copiedCount;
12293
- }
12294
- async function getCliCacheVersion() {
12295
- if (_cliCacheVersionCache) return _cliCacheVersionCache;
12296
- try {
12297
- const { hashContent: hashContent2 } = await Promise.resolve().then(() => (init_cache_keys(), cache_keys_exports));
12298
- const { resolveSkillPath: resolveSkillPath2 } = await Promise.resolve().then(() => (init_src(), src_exports));
12299
- const skills = ["components", "tokens", "select"];
12300
- const parts = [];
12301
- for (const s of skills) {
12302
- try {
12303
- const p = resolveSkillPath2(s);
12304
- parts.push(readFileSync5(p, "utf8"));
12305
- } catch {
12306
- parts.push(`<missing:${s}>`);
12307
- }
12308
- }
12309
- _cliCacheVersionCache = hashContent2(parts.join("\n---\n"));
12310
- return _cliCacheVersionCache;
12311
- } catch {
12312
- _cliCacheVersionCache = "fallback";
12313
- return _cliCacheVersionCache;
12314
- }
12315
- }
12316
- function storeExtractCache(db, filePath, fileHash, cliVersion2, components) {
12317
- const now = (/* @__PURE__ */ new Date()).toISOString();
12318
- const componentsJson = JSON.stringify(components);
12319
- db.prepare(
12320
- `INSERT INTO extract_cache (file_path, file_hash, cli_version, created_at, updated_at, components_json)
12321
- VALUES (?, ?, ?, ?, ?, ?)
12322
- ON CONFLICT(file_hash, cli_version) DO UPDATE SET
12323
- file_path = excluded.file_path,
12324
- updated_at = excluded.updated_at,
12325
- components_json = excluded.components_json`
12326
- ).run(filePath, fileHash, cliVersion2, now, now, componentsJson);
12327
- }
12328
- function lookupExtractCache(db, fileHash, cliVersion2) {
12329
- const row = db.prepare(
12330
- `SELECT file_path, file_hash, cli_version, created_at, updated_at, components_json
12331
- FROM extract_cache
12332
- WHERE file_hash = ? AND cli_version = ?`
12333
- ).get(fileHash, cliVersion2);
12334
- if (!row) return null;
12335
- let components = [];
12336
- try {
12337
- components = JSON.parse(row.components_json);
12338
- } catch {
12339
- return null;
12340
- }
12341
- return {
12342
- filePath: row.file_path,
12343
- fileHash: row.file_hash,
12344
- cliVersion: row.cli_version,
12345
- createdAt: row.created_at,
12346
- updatedAt: row.updated_at,
12347
- components
12348
- };
12349
- }
12350
- function storeCompositionCache(db, inputHash, cliVersion2, agentOutput) {
12351
- const now = (/* @__PURE__ */ new Date()).toISOString();
12352
- db.prepare(
12353
- `INSERT INTO composition_cache (input_hash, cli_version, agent_output, created_at, updated_at)
12354
- VALUES (?, ?, ?, ?, ?)
12355
- ON CONFLICT(input_hash, cli_version) DO UPDATE SET
12356
- agent_output = excluded.agent_output,
12357
- updated_at = excluded.updated_at`
12358
- ).run(inputHash, cliVersion2, agentOutput, now, now);
12359
- }
12360
- function lookupCompositionCache(db, inputHash, cliVersion2) {
12361
- const row = db.prepare(`SELECT agent_output FROM composition_cache WHERE input_hash = ? AND cli_version = ?`).get(inputHash, cliVersion2);
12362
- return row ? row.agent_output : null;
12363
- }
12364
- function storeSelectCache(db, componentHash, promptHash, cliVersion2, decision, reason) {
12365
- const now = (/* @__PURE__ */ new Date()).toISOString();
12366
- db.prepare(
12367
- `INSERT INTO select_cache (component_hash, prompt_hash, cli_version, decision, reason, created_at, updated_at)
12368
- VALUES (?, ?, ?, ?, ?, ?, ?)
12369
- ON CONFLICT(component_hash, prompt_hash, cli_version) DO UPDATE SET
12370
- decision = excluded.decision,
12371
- reason = excluded.reason,
12372
- updated_at = excluded.updated_at`
12373
- ).run(componentHash, promptHash, cliVersion2, decision, reason, now, now);
12374
- }
12375
- function lookupSelectCache(db, componentHash, promptHash, cliVersion2) {
12376
- const row = db.prepare(
12377
- `SELECT component_hash, prompt_hash, cli_version, decision, reason, created_at, updated_at
12378
- FROM select_cache
12379
- WHERE component_hash = ? AND prompt_hash = ? AND cli_version = ?`
12380
- ).get(componentHash, promptHash, cliVersion2);
12381
- if (!row) return null;
12382
- return {
12383
- componentHash: row.component_hash,
12384
- promptHash: row.prompt_hash,
12385
- cliVersion: row.cli_version,
12386
- decision: row.decision,
12387
- reason: row.reason,
12388
- createdAt: row.created_at,
12389
- updatedAt: row.updated_at
12390
- };
12391
- }
12392
- var SCHEMA, MAX_COMPONENT_SOURCE_CHARS, MAX_SIBLING_FILES, MAX_SIBLING_SNIPPET_CHARS, MAX_TYPE_DECLARING_SIBLING_CHARS, MAX_ENLARGED_SIBLINGS, MAX_SIBLING_DEPTH, MAX_SIBLING_CANDIDATES_EXPLORED, RELATIVE_IMPORT_PATTERN, SIBLING_FILE_EXTENSIONS, TS_ESM_EXTENSION_REWRITES, IDENTIFIER_PATTERN, _cliCacheVersionCache;
11738
+ var SCHEMA, REMOVED_CACHE_TABLES, MAX_COMPONENT_SOURCE_CHARS, MAX_SIBLING_FILES, MAX_SIBLING_SNIPPET_CHARS, MAX_TYPE_DECLARING_SIBLING_CHARS, MAX_ENLARGED_SIBLINGS, MAX_SIBLING_DEPTH, MAX_SIBLING_CANDIDATES_EXPLORED, RELATIVE_IMPORT_PATTERN, SIBLING_FILE_EXTENSIONS, TS_ESM_EXTENSION_REWRITES, IDENTIFIER_PATTERN;
12393
11739
  var init_db = __esm({
12394
11740
  "packages/experience-design-system-cli-legacy/src/session/db.ts"() {
12395
11741
  "use strict";
@@ -12403,8 +11749,6 @@ var init_db = __esm({
12403
11749
  init_write2();
12404
11750
  init_session_resolver();
12405
11751
  init_read3();
12406
- init_hash_component_shape();
12407
- init_hash_token_content();
12408
11752
  init_read3();
12409
11753
  init_store_dtcg_tokens();
12410
11754
  init_apply_tool_calls();
@@ -12528,17 +11872,6 @@ CREATE TABLE IF NOT EXISTS raw_tokens (
12528
11872
  FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
12529
11873
  );
12530
11874
 
12531
- CREATE TABLE IF NOT EXISTS generation_cache (
12532
- input_hash TEXT NOT NULL,
12533
- entity_type TEXT NOT NULL CHECK (entity_type IN ('component', 'token_set', 'token_mapping')),
12534
- entity_id TEXT NOT NULL,
12535
- source_session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
12536
- human_edited INTEGER NOT NULL DEFAULT 0 CHECK (human_edited IN (0, 1)),
12537
- created_at TEXT NOT NULL,
12538
- updated_at TEXT NOT NULL,
12539
- PRIMARY KEY (input_hash, entity_type, entity_id)
12540
- );
12541
-
12542
11875
  CREATE TABLE IF NOT EXISTS scanned_files (
12543
11876
  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
12544
11877
  path TEXT NOT NULL,
@@ -12584,10 +11917,9 @@ CREATE INDEX IF NOT EXISTS idx_raw_props_session ON raw_props(session_id,
12584
11917
  CREATE INDEX IF NOT EXISTS idx_raw_slots_session ON raw_slots(session_id, component_id);
12585
11918
  CREATE INDEX IF NOT EXISTS idx_raw_tokens_session ON raw_tokens(session_id);
12586
11919
  CREATE INDEX IF NOT EXISTS idx_raw_token_groups_session ON raw_token_groups(session_id);
12587
- CREATE INDEX IF NOT EXISTS idx_generation_cache_entity ON generation_cache(entity_type, entity_id);
12588
- CREATE INDEX IF NOT EXISTS idx_generation_cache_session ON generation_cache(source_session_id);
12589
11920
  CREATE INDEX IF NOT EXISTS idx_scanned_files_session ON scanned_files(session_id);
12590
11921
  `;
11922
+ REMOVED_CACHE_TABLES = ["generation_cache", "extract_cache", "composition_cache", "select_cache"];
12591
11923
  MAX_COMPONENT_SOURCE_CHARS = 8e3;
12592
11924
  MAX_SIBLING_FILES = 5;
12593
11925
  MAX_SIBLING_SNIPPET_CHARS = 1200;
@@ -12604,16 +11936,15 @@ CREATE INDEX IF NOT EXISTS idx_scanned_files_session ON scanned_files(session
12604
11936
  [".cjs", [".cts", ".cjs"]]
12605
11937
  ];
12606
11938
  IDENTIFIER_PATTERN = /[A-Za-z_$][A-Za-z0-9_$]*/g;
12607
- _cliCacheVersionCache = null;
12608
11939
  }
12609
11940
  });
12610
11941
 
12611
11942
  // packages/experience-design-system-cli-legacy/src/helpers/read-existing-contentful-entities-from-session.ts
12612
- import { readFile as readFile9 } from "node:fs/promises";
11943
+ import { readFile as readFile8 } from "node:fs/promises";
12613
11944
  async function readExistingContentfulEntitiesFromSession(path) {
12614
11945
  if (!path) return void 0;
12615
11946
  try {
12616
- const raw = await readFile9(path, "utf8");
11947
+ const raw = await readFile8(path, "utf8");
12617
11948
  const parsed = JSON.parse(raw);
12618
11949
  if (!Array.isArray(parsed.components) || !Array.isArray(parsed.tokens)) return void 0;
12619
11950
  return parsed;
@@ -12737,21 +12068,21 @@ var init_resolve_session_id = __esm({
12737
12068
  });
12738
12069
 
12739
12070
  // packages/experience-design-system-cli-legacy/src/analyze/select/persistence.ts
12740
- import { access, appendFile, mkdir as mkdir2, readFile as readFile10, writeFile as writeFile2 } from "node:fs/promises";
12071
+ import { access, appendFile, mkdir as mkdir2, readFile as readFile9, writeFile as writeFile2 } from "node:fs/promises";
12741
12072
  import { homedir as homedir4 } from "node:os";
12742
- import { resolve as resolve10 } from "node:path";
12073
+ import { resolve as resolve9 } from "node:path";
12743
12074
  function getRefineArtifactsRoot() {
12744
12075
  if (process.env.EDS_REVIEW_ARTIFACTS_DIR) {
12745
- return resolve10(process.env.EDS_REVIEW_ARTIFACTS_DIR);
12076
+ return resolve9(process.env.EDS_REVIEW_ARTIFACTS_DIR);
12746
12077
  }
12747
- return resolve10(homedir4(), ".contentful", "experience-design-system-cli", "reviews");
12078
+ return resolve9(homedir4(), ".contentful", "experience-design-system-cli", "reviews");
12748
12079
  }
12749
12080
  async function getRefineSessionPaths(sessionId2, artifactsRoot) {
12750
- const sessionDir = resolve10(artifactsRoot, sessionId2);
12081
+ const sessionDir = resolve9(artifactsRoot, sessionId2);
12751
12082
  return {
12752
12083
  sessionDir,
12753
- eventsPath: resolve10(sessionDir, "events.jsonl"),
12754
- statePath: resolve10(sessionDir, "current-review-state.json")
12084
+ eventsPath: resolve9(sessionDir, "events.jsonl"),
12085
+ statePath: resolve9(sessionDir, "current-review-state.json")
12755
12086
  };
12756
12087
  }
12757
12088
  async function saveReviewState(statePath, session) {
@@ -12762,7 +12093,7 @@ async function ensureRefineSession(sessionId2, artifactsRoot, initialSnapshot) {
12762
12093
  await mkdir2(paths.sessionDir, { recursive: true });
12763
12094
  try {
12764
12095
  await access(paths.statePath);
12765
- const savedState = await readFile10(paths.statePath, "utf8");
12096
+ const savedState = await readFile9(paths.statePath, "utf8");
12766
12097
  return JSON.parse(savedState);
12767
12098
  } catch {
12768
12099
  await writeFile2(paths.statePath, JSON.stringify(initialSnapshot, null, 2), "utf8");
@@ -13247,8 +12578,8 @@ var init_path_exists = __esm({
13247
12578
  });
13248
12579
 
13249
12580
  // packages/experience-design-system-cli-legacy/src/lib/prompt-overrides.ts
13250
- import { readFile as readFile11 } from "node:fs/promises";
13251
- import { resolve as resolve11 } from "node:path";
12581
+ import { readFile as readFile10 } from "node:fs/promises";
12582
+ import { resolve as resolve10 } from "node:path";
13252
12583
  function looksLikePath(value) {
13253
12584
  if (value.includes("/") || value.includes("\\")) return true;
13254
12585
  if (value.startsWith("~")) return true;
@@ -13280,9 +12611,9 @@ function parsePromptOverrides(inputs) {
13280
12611
  }
13281
12612
  async function resolvePromptOverride(override) {
13282
12613
  if (override.kind === "text") return override.value;
13283
- const abs = resolve11(override.value);
12614
+ const abs = resolve10(override.value);
13284
12615
  try {
13285
- return await readFile11(abs, "utf8");
12616
+ return await readFile10(abs, "utf8");
13286
12617
  } catch {
13287
12618
  throw new Error(`--prompt: could not read prompt file: ${abs}`);
13288
12619
  }
@@ -13297,21 +12628,21 @@ var init_prompt_overrides = __esm({
13297
12628
 
13298
12629
  // packages/experience-design-system-cli-legacy/src/generate/command.ts
13299
12630
  import { createElement } from "react";
13300
- import { readFile as readFile12, readdir, stat } from "node:fs/promises";
13301
- import { join as join14, resolve as resolve12 } from "node:path";
12631
+ import { readFile as readFile11, readdir, stat } from "node:fs/promises";
12632
+ import { join as join14, resolve as resolve11 } from "node:path";
13302
12633
  async function assertFileExists(flag, p) {
13303
12634
  if (!await pathExists(p)) die(`Error: file not found: ${p} (from ${flag})`);
13304
12635
  }
13305
12636
  async function readFileInline(path) {
13306
12637
  if (!path) return void 0;
13307
- const resolved = resolve12(path);
12638
+ const resolved = resolve11(path);
13308
12639
  let s;
13309
12640
  try {
13310
12641
  s = await stat(resolved);
13311
12642
  } catch {
13312
12643
  return void 0;
13313
12644
  }
13314
- if (!s.isDirectory()) return readFile12(resolved, "utf8");
12645
+ if (!s.isDirectory()) return readFile11(resolved, "utf8");
13315
12646
  const files = [];
13316
12647
  async function walk(dir) {
13317
12648
  let entries;
@@ -13337,7 +12668,7 @@ async function readFileInline(path) {
13337
12668
  }
13338
12669
  await walk(resolved);
13339
12670
  if (files.length === 0) return void 0;
13340
- const parts = await Promise.all(files.map((f) => readFile12(f, "utf8").catch(() => "")));
12671
+ const parts = await Promise.all(files.map((f) => readFile11(f, "utf8").catch(() => "")));
13341
12672
  return parts.filter(Boolean).join("\n\n");
13342
12673
  }
13343
12674
  function printFallbackInstructions(options) {
@@ -13359,26 +12690,6 @@ function printFallbackInstructions(options) {
13359
12690
  lines.push(` Re-run the generate command with the agent available, or use --dry-run to inspect the prompt.`);
13360
12691
  process.stderr.write(lines.join("\n") + "\n");
13361
12692
  }
13362
- function generatePropBuckets(component) {
13363
- return logPropBuckets("generate", [bucketComponentProps(component)]);
13364
- }
13365
- function createCachedComponentResult(componentName, warnings = []) {
13366
- return {
13367
- componentName,
13368
- classified: 0,
13369
- excluded: 0,
13370
- slots: 0,
13371
- warnings,
13372
- failed: false,
13373
- cached: true,
13374
- renamedSlotsCount: 0
13375
- };
13376
- }
13377
- function writeCachedComponentStatus(position, componentName, pinned) {
13378
- const status = pinned ? c.cyan("pinned (human-edited)") : c.green("cached");
13379
- process.stderr.write(` ${position} ${c.bold(componentName)} ${status}
13380
- `);
13381
- }
13382
12693
  async function showGenerateView(result) {
13383
12694
  if (process.stdout.isTTY) {
13384
12695
  const { waitUntilExit } = renderWithGoodbye(
@@ -13399,29 +12710,6 @@ session=${result.sessionId}
13399
12710
  );
13400
12711
  await exitWithAnalytics(0);
13401
12712
  }
13402
- function normalizeComponentForCache(component) {
13403
- const slots = component.slots.map((slot, index, allSlots) => ({
13404
- ...slot,
13405
- name: slot.name.trim() || (allSlots.length === 1 ? "children" : `slot_${index}`)
13406
- }));
13407
- return { ...component, slots };
13408
- }
13409
- function lookupComponentCache(db, component, promptHash) {
13410
- const normalized = normalizeComponentForCache(component);
13411
- const inputHash = hashComponentShape(normalized);
13412
- const cached = lookupCache(db, inputHash, "component", component.component_id, promptHash);
13413
- if (cached) return cached;
13414
- const legacyInputHash = hashComponentShape(component);
13415
- return legacyInputHash === inputHash ? null : lookupCache(db, legacyInputHash, "component", component.component_id, promptHash);
13416
- }
13417
- function resolveComponentCache(db, component, promptHash, allowedComponentNames2) {
13418
- const cached = lookupComponentCache(db, component, promptHash);
13419
- if (cached && findUnknownSlotAllowedComponents(db, cached.sourceSessionId, allowedComponentNames2, component.component_id).length === 0) {
13420
- return { entry: cached, humanEdited: cached.humanEdited };
13421
- }
13422
- const pinned = lookupCacheByEntity(db, "component", component.component_id);
13423
- return pinned?.humanEdited && findUnknownSlotAllowedComponents(db, pinned.sourceSessionId, allowedComponentNames2, component.component_id).length === 0 ? { entry: pinned, humanEdited: true } : null;
13424
- }
13425
12713
  async function runOneComponent(options, component, index, total) {
13426
12714
  const {
13427
12715
  agent,
@@ -13431,13 +12719,10 @@ async function runOneComponent(options, component, index, total) {
13431
12719
  tokensInline,
13432
12720
  tokenMapInline,
13433
12721
  verbose,
13434
- noCache,
13435
12722
  skillPathOverride,
13436
12723
  skillContentOverride,
13437
- promptHash,
13438
12724
  existingContentfulEntities,
13439
12725
  existingTokensInline,
13440
- precomputedCachedNames,
13441
12726
  allowedComponentNames: allowedComponentNames2
13442
12727
  } = options;
13443
12728
  const pos = c.dim(`[${index + 1}/${total}]`);
@@ -13462,40 +12747,8 @@ async function runOneComponent(options, component, index, total) {
13462
12747
  allowedComponents: slot.allowedComponents.filter((name) => allowedComponentNames2.has(name))
13463
12748
  };
13464
12749
  });
13465
- const cacheComponent = normalizeComponentForCache(component);
13466
- if (!noCache && precomputedCachedNames.has(component.name)) {
13467
- writeCachedComponentStatus(pos, component.name, false);
13468
- return createCachedComponentResult(component.name);
13469
- }
13470
- if (!noCache) {
13471
- const inputHash = hashComponentShape(cacheComponent);
13472
- const resolution = resolveComponentCache(db, component, promptHash, allowedComponentNames2);
13473
- if (resolution && !resolution.humanEdited) {
13474
- copyComponentFromCache(db, resolution.entry.sourceSessionId, sessionId2, component.component_id, true, {
13475
- allowedComponentNames: allowedComponentNames2
13476
- });
13477
- storeCache(
13478
- db,
13479
- inputHash,
13480
- "component",
13481
- component.component_id,
13482
- resolution.entry.sourceSessionId,
13483
- resolution.entry.humanEdited,
13484
- promptHash
13485
- );
13486
- writeCachedComponentStatus(pos, component.name, false);
13487
- return createCachedComponentResult(component.name);
13488
- }
13489
- if (resolution?.humanEdited) {
13490
- copyComponentFromCache(db, resolution.entry.sourceSessionId, sessionId2, component.component_id, true, {
13491
- allowedComponentNames: allowedComponentNames2
13492
- });
13493
- writeCachedComponentStatus(pos, component.name, true);
13494
- return createCachedComponentResult(`${component.name}`, [
13495
- `${component.name}: source changed but human edits preserved`
13496
- ]);
13497
- }
13498
- }
12750
+ const componentBuckets = bucketComponentProps(component);
12751
+ getDebugLogger().event("analyze", "prop-buckets.generate", { ...componentBuckets });
13499
12752
  const rawComponentsInline = JSON.stringify(
13500
12753
  [
13501
12754
  {
@@ -13520,7 +12773,7 @@ async function runOneComponent(options, component, index, total) {
13520
12773
  skill: "components",
13521
12774
  mode: "autonomous",
13522
12775
  rawComponentsInline,
13523
- propBucketsInline: generatePropBuckets(component),
12776
+ propBucketsInline: JSON.stringify(componentBuckets),
13524
12777
  tokensInline,
13525
12778
  tokenMapInline,
13526
12779
  outDir: process.cwd(),
@@ -13568,10 +12821,6 @@ ${outputBuf}`);
13568
12821
  const applied = applyToolCalls(db, sessionId2, component.component_id, component.name, calls, warnings, {
13569
12822
  allowedComponentNames: allowedComponentNames2
13570
12823
  });
13571
- if (!noCache) {
13572
- const inputHash = hashComponentShape(cacheComponent);
13573
- storeCache(db, inputHash, "component", component.component_id, sessionId2, false, promptHash);
13574
- }
13575
12824
  return {
13576
12825
  componentName: component.name,
13577
12826
  classified: applied.classified,
@@ -13623,7 +12872,7 @@ async function loadAcceptedNames(sessionId2) {
13623
12872
  try {
13624
12873
  const artifactsRoot = getRefineArtifactsRoot();
13625
12874
  const paths = await getRefineSessionPaths(sessionId2, artifactsRoot);
13626
- const raw = await readFile12(paths.statePath, "utf8");
12875
+ const raw = await readFile11(paths.statePath, "utf8");
13627
12876
  const snapshot = JSON.parse(raw);
13628
12877
  const accepted = snapshot.components.filter((c2) => c2.status === "accepted").map((c2) => c2.name);
13629
12878
  if (accepted.length === 0) return null;
@@ -13632,15 +12881,6 @@ async function loadAcceptedNames(sessionId2) {
13632
12881
  return null;
13633
12882
  }
13634
12883
  }
13635
- function parsePrecomputedCachedNames(value) {
13636
- if (!value) return /* @__PURE__ */ new Set();
13637
- try {
13638
- const parsed = JSON.parse(value);
13639
- return new Set(Array.isArray(parsed) ? parsed.filter((name) => typeof name === "string") : []);
13640
- } catch {
13641
- return /* @__PURE__ */ new Set();
13642
- }
13643
- }
13644
12884
  async function runGenerateSkill(skill, opts, verbose = false) {
13645
12885
  const savedCreds = await readExperiencesCredentials();
13646
12886
  const agentName = opts.agent ?? savedCreds.agent;
@@ -13669,8 +12909,8 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13669
12909
  }
13670
12910
  const generatePromptPath = generatePrompt === void 0 ? configuredGeneratePromptPath : void 0;
13671
12911
  if (generatePromptPath) {
13672
- if (!await pathExists(resolve12(generatePromptPath))) {
13673
- die(`Error: custom prompt path not found: ${resolve12(generatePromptPath)}`);
12912
+ if (!await pathExists(resolve11(generatePromptPath))) {
12913
+ die(`Error: custom prompt path not found: ${resolve11(generatePromptPath)}`);
13674
12914
  }
13675
12915
  if (!generatePromptPath.toLowerCase().endsWith(".md")) {
13676
12916
  process.stderr.write(
@@ -13678,7 +12918,7 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13678
12918
  `
13679
12919
  );
13680
12920
  }
13681
- process.stderr.write(formatCustomPromptBanner("components", resolve12(generatePromptPath)));
12921
+ process.stderr.write(formatCustomPromptBanner("components", resolve11(generatePromptPath)));
13682
12922
  }
13683
12923
  if (skill === "tokens" && !opts.rawTokens) {
13684
12924
  die("Error: --raw-tokens is required when using generate tokens");
@@ -13694,7 +12934,7 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13694
12934
  let existingContentfulEntities;
13695
12935
  let existingTokensInline;
13696
12936
  if (opts.existingEntitiesPath) {
13697
- existingContentfulEntities = await readExistingContentfulEntitiesFromSession(resolve12(opts.existingEntitiesPath));
12937
+ existingContentfulEntities = await readExistingContentfulEntitiesFromSession(resolve11(opts.existingEntitiesPath));
13698
12938
  if (existingContentfulEntities) {
13699
12939
  existingTokensInline = JSON.stringify(summarizeForMapTokens(existingContentfulEntities));
13700
12940
  } else {
@@ -13787,13 +13027,15 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13787
13027
  sampleComponent.props.map((p) => p.type)
13788
13028
  ) : void 0;
13789
13029
  const dryRunExistingComponentsInline = skill === "components" && existingContentfulEntities && sampleComponent ? JSON.stringify(summarizeForGenerateAgent(existingContentfulEntities, sampleComponent.name)) : void 0;
13030
+ const sampleBuckets = sampleComponent ? bucketComponentProps(sampleComponent) : void 0;
13031
+ if (sampleBuckets) getDebugLogger().event("analyze", "prop-buckets.generate", { ...sampleBuckets });
13790
13032
  const prompt = await buildPrompt({
13791
13033
  skill,
13792
13034
  mode: "autonomous",
13793
13035
  rawComponentsInline: sampleInline ?? rawTokensInline,
13794
- propBucketsInline: sampleComponent ? generatePropBuckets(sampleComponent) : void 0,
13036
+ propBucketsInline: sampleBuckets ? JSON.stringify(sampleBuckets) : void 0,
13795
13037
  rawTokensInline: skill === "tokens" ? rawTokensInline : void 0,
13796
- rawTokensFilename: opts.rawTokens ? resolve12(opts.rawTokens).split("/").pop() : void 0,
13038
+ rawTokensFilename: opts.rawTokens ? resolve11(opts.rawTokens).split("/").pop() : void 0,
13797
13039
  tokensInline,
13798
13040
  tokenMapInline,
13799
13041
  outDir: process.cwd(),
@@ -13819,64 +13061,7 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13819
13061
  if (skill === "components" && allComponents && sessionId2) {
13820
13062
  const db = openPipelineDb();
13821
13063
  let componentResults;
13822
- const precomputedCachedNames = parsePrecomputedCachedNames(opts.cachedComponents);
13823
13064
  try {
13824
- const existingContentfulEntitiesHashInputs = [];
13825
- if (existingTokensInline) existingContentfulEntitiesHashInputs.push(hashContent(existingTokensInline));
13826
- const promptHash = await hashPromptForSkill(
13827
- "components",
13828
- agent,
13829
- model,
13830
- generatePromptPath,
13831
- existingContentfulEntitiesHashInputs,
13832
- generatePrompt
13833
- );
13834
- if (opts.cacheStatus) {
13835
- const cacheEnabled = opts.cache !== false && process.env.EDS_NO_CACHE !== "1";
13836
- const cachedComponents = cacheEnabled ? allComponents.flatMap((component) => {
13837
- const resolution = resolveComponentCache(db, component, promptHash, allowedComponentNames2);
13838
- return resolution ? [{ component, resolution }] : [];
13839
- }) : [];
13840
- if (cacheEnabled && opts.restoreCache) {
13841
- const restorations = [];
13842
- const rekeyed = [];
13843
- const componentStatus = db.prepare(
13844
- "SELECT status FROM raw_components WHERE session_id = ? AND component_id = ?"
13845
- );
13846
- for (const { component, resolution } of cachedComponents) {
13847
- const current = componentStatus.get(sessionId2, component.component_id);
13848
- if (current?.status === "generated") continue;
13849
- renameEmptySlots(db, sessionId2, component.component_id, component.name, component.slots.length);
13850
- restorations.push({
13851
- sourceSessionId: resolution.entry.sourceSessionId,
13852
- targetSessionId: sessionId2,
13853
- componentId: component.component_id
13854
- });
13855
- rekeyed.push({ component, cached: resolution.entry });
13856
- }
13857
- copyComponentsFromCache(db, restorations, { allowedComponentNames: allowedComponentNames2 });
13858
- storeCaches(
13859
- db,
13860
- rekeyed.map(({ component, cached }) => ({
13861
- inputHash: hashComponentShape(normalizeComponentForCache(component)),
13862
- entityType: "component",
13863
- entityId: component.component_id,
13864
- sourceSessionId: cached.sourceSessionId,
13865
- humanEdited: cached.humanEdited,
13866
- promptHash
13867
- }))
13868
- );
13869
- }
13870
- const fullyCached = cacheEnabled && cachedComponents.length === allComponents.length;
13871
- process.stdout.write(`cache-status=${fullyCached ? "hit" : "miss"}
13872
- `);
13873
- process.stdout.write(
13874
- `cache-components=${JSON.stringify(cachedComponents.map(({ component }) => component.name))}
13875
- `
13876
- );
13877
- await exitWithAnalytics(0);
13878
- return;
13879
- }
13880
13065
  componentResults = await runAllComponents(
13881
13066
  {
13882
13067
  agent,
@@ -13886,13 +13071,10 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13886
13071
  tokensInline,
13887
13072
  tokenMapInline,
13888
13073
  verbose,
13889
- noCache: opts.cache === false || process.env.EDS_NO_CACHE === "1",
13890
13074
  skillPathOverride: generatePromptPath,
13891
13075
  skillContentOverride: generatePrompt,
13892
- promptHash,
13893
13076
  existingContentfulEntities,
13894
13077
  existingTokensInline,
13895
- precomputedCachedNames,
13896
13078
  allowedComponentNames: allowedComponentNames2
13897
13079
  },
13898
13080
  allComponents
@@ -13901,8 +13083,7 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13901
13083
  db.close();
13902
13084
  }
13903
13085
  const failed = componentResults.filter((r) => r.failed);
13904
- const cachedResults = componentResults.filter((r) => r.cached);
13905
- const generated = componentResults.filter((r) => !r.failed && !r.cached);
13086
+ const generated = componentResults.filter((r) => !r.failed);
13906
13087
  const allWarnings = componentResults.flatMap((r) => r.warnings.map((w) => ` ${r.componentName}: ${w}`));
13907
13088
  if (allWarnings.length > 0) {
13908
13089
  process.stderr.write(c.yellow("Warnings:") + "\n" + allWarnings.join("\n") + "\n");
@@ -13918,21 +13099,17 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13918
13099
  const totalExcluded = generated.reduce((s, r) => s + r.excluded, 0);
13919
13100
  const totalRenamedSlots = componentResults.reduce((s, r) => s + r.renamedSlotsCount, 0);
13920
13101
  const allOk = failed.length === 0;
13921
- const cachedNote = cachedResults.length > 0 ? c.dim(` (${cachedResults.length} cached)`) : "";
13922
13102
  process.stderr.write(
13923
- (allOk ? c.green("\u2713") : c.yellow("\u26A0")) + ` ${generated.length + cachedResults.length}/${componentResults.length} components` + cachedNote + c.dim(` ${totalClassified} classified, ${totalExcluded} unattached`) + "\n"
13103
+ (allOk ? c.green("\u2713") : c.yellow("\u26A0")) + ` ${generated.length}/${componentResults.length} components` + c.dim(` ${totalClassified} classified, ${totalExcluded} unattached`) + "\n"
13924
13104
  );
13925
13105
  process.stdout.write(`renamed-slots: ${totalRenamedSlots}
13926
13106
  `);
13927
- if (generated.length === 0 && cachedResults.length === 0) {
13107
+ if (generated.length === 0) {
13928
13108
  die(
13929
13109
  `Error: all ${componentResults.length} component(s) failed to generate \u2014 see the per-component errors above.`
13930
13110
  );
13931
13111
  }
13932
13112
  } else if (skill === "tokens") {
13933
- const noCache = opts.cache === false || process.env.EDS_NO_CACHE === "1";
13934
- const tokenInputContent = rawTokensInline ?? "";
13935
- const tokenInputHash = hashTokenContent(tokenInputContent);
13936
13113
  const db = openPipelineDb();
13937
13114
  try {
13938
13115
  let resolvedSessionId = opts.session;
@@ -13959,26 +13136,11 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13959
13136
  }
13960
13137
  sessionId2 = resolvedSessionId;
13961
13138
  await bindAnalyticsSessionId(resolvedSessionId);
13962
- const tokenPromptHash = await hashPromptForSkill("tokens", agent, model);
13963
- if (!noCache) {
13964
- const tokenCached = lookupCache(db, tokenInputHash, "token_set", "__tokens__", tokenPromptHash);
13965
- if (tokenCached) {
13966
- copyTokensFromCache(db, tokenCached.sourceSessionId, resolvedSessionId);
13967
- sessionId2 = resolvedSessionId;
13968
- process.stderr.write(
13969
- `Done: tokens reused from cache ${c.dim(`(source: ${tokenCached.sourceSessionId.slice(0, 12)})`)}
13970
- `
13971
- );
13972
- db.close();
13973
- await showGenerateView({ skill, agent, sessionId: sessionId2 ?? "" });
13974
- return;
13975
- }
13976
- }
13977
13139
  const prompt = await buildPrompt({
13978
13140
  skill,
13979
13141
  mode: "autonomous",
13980
13142
  rawTokensInline,
13981
- rawTokensFilename: opts.rawTokens ? resolve12(opts.rawTokens).split("/").pop() : void 0,
13143
+ rawTokensFilename: opts.rawTokens ? resolve11(opts.rawTokens).split("/").pop() : void 0,
13982
13144
  tokensInline,
13983
13145
  tokenMapInline,
13984
13146
  outDir: process.cwd()
@@ -14015,9 +13177,6 @@ ${tokenWarnings.map((w) => ` ${w}`).join("\n")}
14015
13177
  `);
14016
13178
  }
14017
13179
  applyTokenToolCalls(db, resolvedSessionId, tokenCalls, []);
14018
- if (!noCache) {
14019
- storeCache(db, tokenInputHash, "token_set", "__tokens__", resolvedSessionId, false, tokenPromptHash);
14020
- }
14021
13180
  sessionId2 = resolvedSessionId;
14022
13181
  const groupCount = tokenCalls.filter((tc) => tc.tool === "set_group").length;
14023
13182
  process.stderr.write(`Done: ${tokenCount} tokens, ${groupCount} groups stored
@@ -14029,10 +13188,7 @@ ${tokenWarnings.map((w) => ` ${w}`).join("\n")}
14029
13188
  await showGenerateView({ skill, agent, sessionId: sessionId2 ?? "" });
14030
13189
  }
14031
13190
  function addAgentFlags(cmd) {
14032
- return addAgentModelOptions(cmd).option("--verbose", "Show full agent output including reasoning text").option("--dry-run", "Print the prompt without invoking the agent").option(
14033
- "--no-cache",
14034
- "Bypass ALL fine-grained caches (extract, select, generate) and force AI re-run. Cache keys now factor in prompt content \u2014 changing the prompt file via --generate-prompt-path or --select-prompt-path will already bust the corresponding stage. Use --no-cache to force a full re-run."
14035
- );
13191
+ return addAgentModelOptions(cmd).option("--verbose", "Show full agent output including reasoning text").option("--dry-run", "Print the prompt without invoking the agent");
14036
13192
  }
14037
13193
  function registerInternalGenerateCommand(program) {
14038
13194
  const generate = program.command("__generate", { hidden: true }).description("Internal import pipeline generation command");
@@ -14048,12 +13204,6 @@ function registerInternalGenerateCommand(program) {
14048
13204
  "--existing-entities-path <path>",
14049
13205
  "Path to the .existing-entities.json file written after CMA credentials are supplied. When present, per-component prompts include a summary of the target space so classifications can align to existing prop names/tokens. Missing/malformed files are treated as no-op."
14050
13206
  );
14051
- componentsCmd.option("--cache-status", "Check whether all selected component definitions are cached");
14052
- componentsCmd.option("--restore-cache", "Restore cached component definitions into the current session");
14053
- componentsCmd.option(
14054
- "--cached-components <json>",
14055
- "Component names already restored by a prior cache-status lookup; skip per-component cache lookup"
14056
- );
14057
13207
  addAgentFlags(componentsCmd).action(async (opts) => {
14058
13208
  await runGenerateSkill("components", opts, opts.verbose ?? false);
14059
13209
  });
@@ -14074,14 +13224,11 @@ var init_command = __esm({
14074
13224
  init_render_with_goodbye();
14075
13225
  init_src();
14076
13226
  init_src2();
14077
- init_prop_bucket_debug();
14078
13227
  init_format();
14079
- init_strip_extraction_provenance();
14080
13228
  init_debug_logger();
14081
13229
  init_agent_output();
14082
13230
  init_GenerateView();
14083
13231
  init_db();
14084
- init_cache_keys();
14085
13232
  init_read_existing_contentful_entities_from_session();
14086
13233
  init_summarize_existing_contentful_entities();
14087
13234
  init_resolve_session_id();
@@ -14797,7 +13944,7 @@ var init_user_agent = __esm({
14797
13944
  // packages/experience-design-system-cli-legacy/src/apply/api-client.ts
14798
13945
  import { parseCDFComponents } from "@contentful/experience-design-system-types";
14799
13946
  function defaultSleep(delayMs) {
14800
- return new Promise((resolve22) => setTimeout(resolve22, delayMs));
13947
+ return new Promise((resolve20) => setTimeout(resolve20, delayMs));
14801
13948
  }
14802
13949
  function isTransientStatus(status) {
14803
13950
  return status >= 500 && status <= 599;
@@ -15187,7 +14334,7 @@ ${trimmed}`;
15187
14334
  const progress = maxAttempts > 1 ? attempt / (maxAttempts - 1) : 0;
15188
14335
  const baseDelay = intervalMs + (maxIntervalMs - intervalMs) * progress;
15189
14336
  const jitter = Math.random() * baseDelay * 0.15;
15190
- await new Promise((resolve22) => setTimeout(resolve22, baseDelay + jitter));
14337
+ await new Promise((resolve20) => setTimeout(resolve20, baseDelay + jitter));
15191
14338
  }
15192
14339
  }
15193
14340
  throw new Error(`Operation ${operationId} timed out after ${maxAttempts} attempts`);
@@ -15997,7 +15144,7 @@ var init_terminal_capabilities = __esm({
15997
15144
 
15998
15145
  // packages/experience-design-system-cli-legacy/src/apply/command.ts
15999
15146
  import { createElement as createElement2 } from "react";
16000
- import { readFile as readFile13, readdir as readdir2, stat as stat2 } from "node:fs/promises";
15147
+ import { readFile as readFile12, readdir as readdir2, stat as stat2 } from "node:fs/promises";
16001
15148
  import { join as join16 } from "node:path";
16002
15149
  import {
16003
15150
  validateCDF,
@@ -16018,7 +15165,7 @@ function dieWithApiError(error) {
16018
15165
  async function readJsonFile(flag, p) {
16019
15166
  let text;
16020
15167
  try {
16021
- text = await readFile13(p, "utf8");
15168
+ text = await readFile12(p, "utf8");
16022
15169
  } catch {
16023
15170
  return await die2(`Error: file not found: ${p} (from ${flag})`);
16024
15171
  }
@@ -16072,7 +15219,7 @@ async function readTokensFromPath(flag, p) {
16072
15219
  for (const file of files.sort()) {
16073
15220
  let text;
16074
15221
  try {
16075
- text = await readFile13(file, "utf8");
15222
+ text = await readFile12(file, "utf8");
16076
15223
  } catch {
16077
15224
  continue;
16078
15225
  }
@@ -16441,11 +15588,11 @@ var init_command2 = __esm({
16441
15588
  });
16442
15589
 
16443
15590
  // packages/experience-design-system-cli-legacy/src/print/validate/validators/read-json-file.ts
16444
- import { readFile as readFile14 } from "node:fs/promises";
15591
+ import { readFile as readFile13 } from "node:fs/promises";
16445
15592
  async function readJsonFile2(filePath) {
16446
15593
  let content;
16447
15594
  try {
16448
- content = await readFile14(filePath, "utf-8");
15595
+ content = await readFile13(filePath, "utf-8");
16449
15596
  } catch (err) {
16450
15597
  return {
16451
15598
  ok: false,
@@ -16856,7 +16003,7 @@ var init_ValidateView = __esm({
16856
16003
  // packages/experience-design-system-cli-legacy/src/print/command.ts
16857
16004
  import { createElement as createElement3 } from "react";
16858
16005
  import { access as access3, mkdir as mkdir3, stat as stat3, writeFile as writeFile3 } from "node:fs/promises";
16859
- import { basename as basename5, resolve as resolve13 } from "node:path";
16006
+ import { basename as basename5, resolve as resolve12 } from "node:path";
16860
16007
  import { CDF_SCHEMA_URL } from "@contentful/experience-design-system-types";
16861
16008
  async function die3(message) {
16862
16009
  process.stderr.write(`${message}
@@ -16923,7 +16070,7 @@ function registerPrintCommand(program) {
16923
16070
  "--allow-empty",
16924
16071
  "Write an empty-but-present CDF file when no components are accepted (a subsequent push then removes ALL components from the target space). Without this, an empty accepted set is an error."
16925
16072
  ).action(async (opts) => {
16926
- const outPath = resolve13(opts.out);
16073
+ const outPath = resolve12(opts.out);
16927
16074
  await assertOutIsNotDirectory(outPath);
16928
16075
  const sessionId2 = await resolveSession(opts.session, "generate components");
16929
16076
  await bindAnalyticsSessionId(sessionId2);
@@ -16971,7 +16118,7 @@ function registerPrintCommand(program) {
16971
16118
  `
16972
16119
  );
16973
16120
  }
16974
- await mkdir3(resolve13(outPath, ".."), { recursive: true });
16121
+ await mkdir3(resolve12(outPath, ".."), { recursive: true });
16975
16122
  await writeFile3(outPath, `${JSON.stringify(cdfObj, null, 2)}
16976
16123
  `);
16977
16124
  process.stdout.write(
@@ -16980,7 +16127,7 @@ function registerPrintCommand(program) {
16980
16127
  );
16981
16128
  });
16982
16129
  print.command("tokens").description("Write generated tokens to a DTCG JSON file").option("--session <id>", "Session ID to print from (default: most recent generate tokens session)").option("--out <path>", "Output file path", "tokens.json").action(async (opts) => {
16983
- const outPath = resolve13(opts.out);
16130
+ const outPath = resolve12(opts.out);
16984
16131
  await assertOutIsNotDirectory(outPath);
16985
16132
  const sessionId2 = await resolveSession(opts.session, "generate tokens");
16986
16133
  await bindAnalyticsSessionId(sessionId2);
@@ -16995,7 +16142,7 @@ function registerPrintCommand(program) {
16995
16142
  await die3(`Error: no generated tokens in session '${sessionId2}'. Run generate tokens first.`);
16996
16143
  }
16997
16144
  const tree = rebuildDTCGTree(result.groups, result.tokens);
16998
- await mkdir3(resolve13(outPath, ".."), { recursive: true });
16145
+ await mkdir3(resolve12(outPath, ".."), { recursive: true });
16999
16146
  await writeFile3(outPath, `${JSON.stringify(tree, null, 2)}
17000
16147
  `);
17001
16148
  process.stdout.write(
@@ -17144,7 +16291,7 @@ function MapTokensView({ result, onExit }) {
17144
16291
  const timer = setTimeout(onExit, 100);
17145
16292
  return () => clearTimeout(timer);
17146
16293
  }, [onExit]);
17147
- const summary = result.cached ? "reused from cache" : `${result.applied} mapping${result.applied === 1 ? "" : "s"} applied`;
16294
+ const summary = `${result.applied} mapping${result.applied === 1 ? "" : "s"} applied`;
17148
16295
  return /* @__PURE__ */ jsx8(
17149
16296
  CommandCompletionView,
17150
16297
  {
@@ -17278,8 +16425,8 @@ var init_resolve_defaults = __esm({
17278
16425
 
17279
16426
  // packages/experience-design-system-cli-legacy/src/map-tokens/command.ts
17280
16427
  import { createElement as createElement4 } from "react";
17281
- import { readFile as readFile15 } from "node:fs/promises";
17282
- import { resolve as resolve14 } from "node:path";
16428
+ import { readFile as readFile14 } from "node:fs/promises";
16429
+ import { resolve as resolve13 } from "node:path";
17283
16430
  async function renderResult(result) {
17284
16431
  if (process.stdout.isTTY) {
17285
16432
  const { waitUntilExit } = renderWithGoodbye(
@@ -17287,12 +16434,13 @@ async function renderResult(result) {
17287
16434
  );
17288
16435
  await waitUntilExit();
17289
16436
  } else {
17290
- const summary = result.cached ? "cached" : `${result.applied} mapping(s) applied`;
17291
- process.stdout.write(`map tokens complete
16437
+ process.stdout.write(
16438
+ `map tokens complete
17292
16439
  agent: ${result.agent}
17293
16440
  session=${result.sessionId}
17294
- ${summary}
17295
- `);
16441
+ ${result.applied} mapping(s) applied
16442
+ `
16443
+ );
17296
16444
  await exitWithAnalytics(0);
17297
16445
  }
17298
16446
  }
@@ -17314,7 +16462,7 @@ async function runMapTokens(opts) {
17314
16462
  let mapPromptPath;
17315
16463
  if (mapPromptOverride?.kind === "text") mapPromptText = mapPromptOverride.value;
17316
16464
  if (mapPromptOverride?.kind === "path") {
17317
- mapPromptPath = resolve14(mapPromptOverride.value);
16465
+ mapPromptPath = resolve13(mapPromptOverride.value);
17318
16466
  try {
17319
16467
  await resolvePromptOverride(mapPromptOverride);
17320
16468
  } catch (error) {
@@ -17334,7 +16482,7 @@ async function runMapTokens(opts) {
17334
16482
  const knownTokenPaths = new Set(tokenLeaves.map((t) => t.path));
17335
16483
  const tokenMapDiagnostics = [];
17336
16484
  if (opts.tokenMap) {
17337
- const fileMappings = JSON.parse(await readFile15(opts.tokenMap, "utf8"));
16485
+ const fileMappings = JSON.parse(await readFile14(opts.tokenMap, "utf8"));
17338
16486
  const validMappings = {};
17339
16487
  for (const [rawName, path] of Object.entries(fileMappings)) {
17340
16488
  if (knownTokenPaths.has(path)) {
@@ -17412,7 +16560,7 @@ ${defaultDiagnostics.map((diagnostic) => ` ${diagnostic}`).join("\n")}
17412
16560
  let existingTokensInline;
17413
16561
  if (opts.existingEntitiesPath) {
17414
16562
  const existingContentfulEntities = await readExistingContentfulEntitiesFromSession(
17415
- resolve14(opts.existingEntitiesPath)
16563
+ resolve13(opts.existingEntitiesPath)
17416
16564
  );
17417
16565
  if (existingContentfulEntities) {
17418
16566
  existingTokensInline = JSON.stringify(summarizeForMapTokens(existingContentfulEntities));
@@ -17447,30 +16595,10 @@ ${defaultDiagnostics.map((diagnostic) => ` ${diagnostic}`).join("\n")}
17447
16595
  skipAgent: "true"
17448
16596
  });
17449
16597
  updateStep(db, stepId2, "complete", { applied: "0", skipAgent: "true" });
17450
- await renderResult({ agent: resultAgent, sessionId: sessionId2, applied: 0, cached: false });
16598
+ await renderResult({ agent: resultAgent, sessionId: sessionId2, applied: 0 });
17451
16599
  return;
17452
16600
  }
17453
16601
  const agent = configuredAgent;
17454
- const noCache = opts.cache === false || process.env.EDS_NO_CACHE === "1";
17455
- const promptHash = await hashPromptForSkill(
17456
- "map-tokens",
17457
- agent,
17458
- model,
17459
- void 0,
17460
- existingTokensInline ? [hashContent(existingTokensInline)] : [],
17461
- mapPromptText
17462
- );
17463
- const inputHash = computeMapTokensInputHash(db, sessionId2, componentSourceRefs);
17464
- if (!noCache) {
17465
- const cached = lookupCache(db, inputHash, "token_mapping", "__map_tokens__", promptHash);
17466
- if (cached) {
17467
- const appliedFromCache = copyMapTokensFromCache(db, cached.sourceSessionId, sessionId2);
17468
- const stepId2 = createStep(db, sessionId2, "map tokens", { agent, model: model ?? "" });
17469
- updateStep(db, stepId2, "complete", { cached: "true", applied: String(appliedFromCache) });
17470
- await renderResult({ agent, sessionId: sessionId2, applied: appliedFromCache, cached: true });
17471
- return;
17472
- }
17473
- }
17474
16602
  const binary = resolveAgentBinary(agent);
17475
16603
  if (!await assertBinaryInPath(binary)) {
17476
16604
  die(
@@ -17490,23 +16618,20 @@ Install it, choose another agent with --agent, or use --print-prompt to run the
17490
16618
  }
17491
16619
  const { calls, warnings: parseWarnings } = parseMapTokenPropToolCallLines(result.stdout);
17492
16620
  const { applied, warnings } = applyMapTokenPropCalls(db, sessionId2, calls, parseWarnings);
17493
- if (!noCache) {
17494
- storeCache(db, inputHash, "token_mapping", "__map_tokens__", sessionId2, false, promptHash);
17495
- }
17496
16621
  updateStep(db, stepId, "complete", { applied: String(applied), warnings: String(warnings.length) });
17497
16622
  if (warnings.length > 0) {
17498
16623
  process.stderr.write(`Warnings:
17499
16624
  ${warnings.map((w) => ` ${w}`).join("\n")}
17500
16625
  `);
17501
16626
  }
17502
- await renderResult({ agent, sessionId: sessionId2, applied, cached: false });
16627
+ await renderResult({ agent, sessionId: sessionId2, applied });
17503
16628
  } finally {
17504
16629
  db.close();
17505
16630
  }
17506
16631
  }
17507
16632
  function registerMapTokensCommand(program) {
17508
16633
  const map = program.command("map", { hidden: true }).description("Suggest token restrictions for generated design-token props");
17509
- const tokensCmd = map.command("tokens").description("Invoke a coding agent to suggest $token.allowed for design-category token props").option("--session <id>", "Session ID from generate components (defaults to most recent)").option("--print-prompt", "Print the prompt without invoking the agent").option("--skip-agent", "Resolve token defaults without agentic $token.allowed inference").option("--no-cache", "Bypass the map-tokens cache and force a re-run").option(
16634
+ const tokensCmd = map.command("tokens").description("Invoke a coding agent to suggest $token.allowed for design-category token props").option("--session <id>", "Session ID from generate components (defaults to most recent)").option("--print-prompt", "Print the prompt without invoking the agent").option("--skip-agent", "Resolve token defaults without agentic $token.allowed inference").option(
17510
16635
  "--prompt <stage=value>",
17511
16636
  "Override a stage prompt (repeatable). Used here for the map-tokens stage.",
17512
16637
  (v, acc) => [...acc, v],
@@ -17526,7 +16651,6 @@ var init_command4 = __esm({
17526
16651
  init_render_with_goodbye();
17527
16652
  init_src();
17528
16653
  init_db();
17529
- init_cache_keys();
17530
16654
  init_read_existing_contentful_entities_from_session();
17531
16655
  init_summarize_existing_contentful_entities();
17532
16656
  init_command3();
@@ -17543,7 +16667,7 @@ var init_command4 = __esm({
17543
16667
  });
17544
16668
 
17545
16669
  // packages/experience-design-system-cli-legacy/src/import/path-utils.ts
17546
- import { resolve as resolve15 } from "node:path";
16670
+ import { resolve as resolve14 } from "node:path";
17547
16671
  import { homedir as homedir5 } from "node:os";
17548
16672
  function expandTilde(input) {
17549
16673
  if (input === "~" || input.startsWith("~/") || input.startsWith("~\\")) {
@@ -17557,7 +16681,7 @@ function normalizePath(input) {
17557
16681
  p = p.slice(1, -1);
17558
16682
  }
17559
16683
  p = expandTilde(p);
17560
- return resolve15(p);
16684
+ return resolve14(p);
17561
16685
  }
17562
16686
  var init_path_utils = __esm({
17563
16687
  "packages/experience-design-system-cli-legacy/src/import/path-utils.ts"() {
@@ -17782,7 +16906,7 @@ var init_save_path_resolver = __esm({
17782
16906
  });
17783
16907
 
17784
16908
  // packages/experience-design-system-cli-legacy/src/runs/store.ts
17785
- import { readFile as readFile16, writeFile as writeFile4, mkdir as mkdir4, rename } from "node:fs/promises";
16909
+ import { readFile as readFile15, writeFile as writeFile4, mkdir as mkdir4, rename } from "node:fs/promises";
17786
16910
  import { join as join20 } from "node:path";
17787
16911
  import { homedir as homedir6 } from "node:os";
17788
16912
  import { randomBytes as randomBytes2 } from "node:crypto";
@@ -17822,7 +16946,7 @@ function migrateRecord(rec) {
17822
16946
  }
17823
16947
  async function readFileMaybe() {
17824
16948
  try {
17825
- const raw = await readFile16(RUNS_PATH, "utf8");
16949
+ const raw = await readFile15(RUNS_PATH, "utf8");
17826
16950
  const parsed = JSON.parse(raw);
17827
16951
  if (!READABLE_VERSIONS.has(parsed.version)) {
17828
16952
  throw new Error(
@@ -17886,15 +17010,15 @@ var init_store = __esm({
17886
17010
  });
17887
17011
 
17888
17012
  // packages/experience-design-system-cli-legacy/src/runs/fingerprint.ts
17889
- import { createHash as createHash6 } from "node:crypto";
17890
- import { readFile as readFile17, stat as stat4 } from "node:fs/promises";
17891
- import { resolve as resolve16 } from "node:path";
17013
+ import { createHash as createHash2 } from "node:crypto";
17014
+ import { readFile as readFile16, stat as stat4 } from "node:fs/promises";
17015
+ import { resolve as resolve15 } from "node:path";
17892
17016
  function rowField(row, key) {
17893
17017
  const v = row[key];
17894
17018
  return typeof v === "string" ? v : null;
17895
17019
  }
17896
17020
  function sha256Hex(buf) {
17897
- return createHash6("sha256").update(buf).digest("hex");
17021
+ return createHash2("sha256").update(buf).digest("hex");
17898
17022
  }
17899
17023
  async function buildSourceFingerprint(opts) {
17900
17024
  const rows = opts.db.prepare("SELECT name, source_path FROM raw_components WHERE session_id = ?").all(opts.extractSessionId);
@@ -17904,7 +17028,7 @@ async function buildSourceFingerprint(opts) {
17904
17028
  const sourcePath = rowField(row, "source_path");
17905
17029
  const name = rowField(row, "name");
17906
17030
  if (!sourcePath) continue;
17907
- const abs = resolve16(sourcePath);
17031
+ const abs = resolve15(sourcePath);
17908
17032
  if (seen.has(abs)) continue;
17909
17033
  seen.add(abs);
17910
17034
  try {
@@ -17919,10 +17043,10 @@ async function buildSourceFingerprint(opts) {
17919
17043
  let rawTokensMtime = null;
17920
17044
  let rawTokensContentHash = null;
17921
17045
  if (opts.rawTokensPath) {
17922
- const abs = resolve16(opts.rawTokensPath);
17046
+ const abs = resolve15(opts.rawTokensPath);
17923
17047
  rawTokensPath = abs;
17924
17048
  try {
17925
- const [st, buf] = await Promise.all([stat4(abs), readFile17(abs)]);
17049
+ const [st, buf] = await Promise.all([stat4(abs), readFile16(abs)]);
17926
17050
  rawTokensMtime = st.mtime.toISOString();
17927
17051
  rawTokensContentHash = sha256Hex(buf);
17928
17052
  } catch {
@@ -19677,11 +18801,11 @@ var init_slot_graph = __esm({
19677
18801
  });
19678
18802
 
19679
18803
  // packages/experience-design-system-cli-legacy/src/analyze/select/parser.ts
19680
- import { createHash as createHash7 } from "node:crypto";
18804
+ import { createHash as createHash3 } from "node:crypto";
19681
18805
  import { access as access5 } from "node:fs/promises";
19682
- import { isAbsolute, relative, resolve as resolve17 } from "node:path";
18806
+ import { isAbsolute, relative, resolve as resolve16 } from "node:path";
19683
18807
  function createComponentId(name, resolvedSourcePath) {
19684
- const sourceHash = createHash7("sha256").update(`${name}:${resolvedSourcePath}`).digest("hex").slice(0, 12);
18808
+ const sourceHash = createHash3("sha256").update(`${name}:${resolvedSourcePath}`).digest("hex").slice(0, 12);
19685
18809
  return `${name}-${sourceHash}`;
19686
18810
  }
19687
18811
  async function resolveComponentSourcePath(source, reviewRoot) {
@@ -19693,7 +18817,7 @@ async function resolveComponentSourcePath(source, reviewRoot) {
19693
18817
  throw new Error(`Unable to access component source at ${source}`);
19694
18818
  }
19695
18819
  }
19696
- const candidate = resolve17(reviewRoot, source);
18820
+ const candidate = resolve16(reviewRoot, source);
19697
18821
  const relativeToRoot = relative(reviewRoot, candidate);
19698
18822
  if (relativeToRoot.startsWith("..") || relativeToRoot === ".." || isAbsolute(relativeToRoot)) {
19699
18823
  throw new Error(
@@ -19708,7 +18832,7 @@ async function resolveComponentSourcePath(source, reviewRoot) {
19708
18832
  }
19709
18833
  }
19710
18834
  async function loadReviewInput(components, options = {}) {
19711
- const reviewRoot = resolve17(options.reviewRoot ?? process.cwd());
18835
+ const reviewRoot = resolve16(options.reviewRoot ?? process.cwd());
19712
18836
  const records = await Promise.all(
19713
18837
  components.map(async (component) => {
19714
18838
  let resolvedSourcePath;
@@ -19739,7 +18863,7 @@ var init_parser = __esm({
19739
18863
  });
19740
18864
 
19741
18865
  // packages/experience-design-system-cli-legacy/src/analyze/select/command.ts
19742
- import { access as access6, readFile as readFile18 } from "node:fs/promises";
18866
+ import { access as access6, readFile as readFile17 } from "node:fs/promises";
19743
18867
  async function loadAndValidateForReview(sessionId2, projectRoot) {
19744
18868
  const db = openPipelineDb();
19745
18869
  let rawComponents;
@@ -19757,7 +18881,7 @@ async function patchReviewStateWithValidationErrors(sessionId2, errors, opts = {
19757
18881
  let snapshot;
19758
18882
  try {
19759
18883
  await access6(paths.statePath);
19760
- snapshot = JSON.parse(await readFile18(paths.statePath, "utf8"));
18884
+ snapshot = JSON.parse(await readFile17(paths.statePath, "utf8"));
19761
18885
  } catch {
19762
18886
  snapshot = await loadAndValidateForReview(sessionId2, void 0);
19763
18887
  snapshot = await ensureRefineSession(sessionId2, artifactsRoot, snapshot);
@@ -19808,7 +18932,7 @@ async function rejectComponentsByName(sessionId2, names, opts = {}) {
19808
18932
  const nameSet = new Set(names);
19809
18933
  let snapshot;
19810
18934
  try {
19811
- snapshot = JSON.parse(await readFile18(paths.statePath, "utf8"));
18935
+ snapshot = JSON.parse(await readFile17(paths.statePath, "utf8"));
19812
18936
  } catch {
19813
18937
  return;
19814
18938
  }
@@ -19907,9 +19031,9 @@ function spawnGenerateChild(opts) {
19907
19031
  stderr += chunk;
19908
19032
  opts.onStderr?.(chunk);
19909
19033
  });
19910
- const donePromise = new Promise((resolve22) => {
19034
+ const donePromise = new Promise((resolve20) => {
19911
19035
  child.on("close", (code, signal) => {
19912
- resolve22({
19036
+ resolve20({
19913
19037
  exitCode: code ?? 0,
19914
19038
  signal: signal ?? null,
19915
19039
  stdout,
@@ -19917,7 +19041,7 @@ function spawnGenerateChild(opts) {
19917
19041
  });
19918
19042
  });
19919
19043
  child.on("error", (err) => {
19920
- resolve22({
19044
+ resolve20({
19921
19045
  exitCode: 1,
19922
19046
  signal: null,
19923
19047
  stdout,
@@ -28055,9 +27179,6 @@ function shouldGenerateAfterCredentialsValidated(opts) {
28055
27179
  function shouldSkipFinalReviewAfterCredentials(state) {
28056
27180
  return state.finalReviewPassed && state.generateSessionId != null;
28057
27181
  }
28058
- function resolveNoCacheForGenerate(opts) {
28059
- return opts.cliNoCache;
28060
- }
28061
27182
  function shouldBypassPreview(state) {
28062
27183
  return state.credentialsSkipped === true;
28063
27184
  }
@@ -28084,66 +27205,43 @@ var init_wizard_state_transitions = __esm({
28084
27205
  async function runSelectionAgent(options) {
28085
27206
  const db = openPipelineDb();
28086
27207
  let components;
28087
- const cachedDecisions = /* @__PURE__ */ new Map();
28088
- const cliVersion2 = await getCliCacheVersion();
28089
- const promptHash = await hashPromptForSkill(
28090
- "select",
28091
- options.agent,
28092
- options.model,
28093
- options.promptPath,
28094
- [SELECT_PAYLOAD_FORMAT],
28095
- options.promptText
28096
- );
28097
27208
  try {
28098
27209
  components = loadRawComponents(db, options.sessionId);
28099
- if (!options.noCache) {
28100
- for (const component of components) {
28101
- const componentHash = hashComponentShape(component);
28102
- const cached = lookupSelectCache(db, componentHash, promptHash, cliVersion2);
28103
- if (cached) {
28104
- cachedDecisions.set(component.name, {
28105
- decision: cached.decision,
28106
- reason: cached.reason
28107
- });
28108
- }
28109
- }
28110
- }
28111
27210
  } finally {
28112
27211
  db.close();
28113
27212
  }
28114
27213
  if (components.length === 0) return;
28115
- const componentsToRun = components.filter((component) => !cachedDecisions.has(component.name));
28116
- let calls = [];
28117
- if (componentsToRun.length > 0) {
28118
- const invoker2 = createLocalCliAgentInvoker({
28119
- onDebugEvent: (name, payload) => getDebugLogger().event("agent", name, payload)
28120
- });
28121
- const prompt = await buildPrompt({
28122
- skill: "select",
28123
- mode: "autonomous",
28124
- rawComponentsInline: JSON.stringify(
28125
- componentsToRun.map((component) => ({ ...component, props: component.props.map(stripPropProvenance) })),
28126
- null,
28127
- 2
28128
- ),
28129
- propBucketsInline: logPropBuckets("select", bucketComponentsProps(componentsToRun)),
28130
- outDir: process.cwd(),
28131
- ...options.promptText !== void 0 ? { skillContentOverride: options.promptText } : {},
28132
- ...options.promptText === void 0 && options.promptPath ? { skillPathOverride: options.promptPath } : {}
28133
- });
28134
- const { result } = await invokeAgentWithOutput(
28135
- invoker2,
28136
- { agent: options.agent, model: options.model, prompt, timeoutMs: DEFAULT_TIMEOUT_MS4 },
28137
- false
28138
- );
28139
- if (result.timedOut) throw new Error("selection agent timed out");
28140
- if (result.exitCode !== 0) throw new Error(`selection agent exited with code ${result.exitCode}`);
28141
- const parsed = parseSelectToolCallLines(result.stdout);
28142
- for (const warning of parsed.warnings) process.stderr.write(`Warning: selection agent: ${warning}
28143
- `);
28144
- calls = parsed.calls;
27214
+ const invoker2 = createLocalCliAgentInvoker({
27215
+ onDebugEvent: (name, payload) => getDebugLogger().event("agent", name, payload)
27216
+ });
27217
+ const selectBuckets = bucketComponentsProps(components);
27218
+ for (const assignment of selectBuckets) {
27219
+ getDebugLogger().event("analyze", "prop-buckets.select", { ...assignment });
28145
27220
  }
28146
- const byName = new Map(calls.map((call) => [call.name, call]));
27221
+ const prompt = await buildPrompt({
27222
+ skill: "select",
27223
+ mode: "autonomous",
27224
+ rawComponentsInline: JSON.stringify(
27225
+ components.map((component) => ({ ...component, props: component.props.map(stripPropProvenance) })),
27226
+ null,
27227
+ 2
27228
+ ),
27229
+ propBucketsInline: JSON.stringify(selectBuckets),
27230
+ outDir: process.cwd(),
27231
+ ...options.promptText !== void 0 ? { skillContentOverride: options.promptText } : {},
27232
+ ...options.promptText === void 0 && options.promptPath ? { skillPathOverride: options.promptPath } : {}
27233
+ });
27234
+ const { result } = await invokeAgentWithOutput(
27235
+ invoker2,
27236
+ { agent: options.agent, model: options.model, prompt, timeoutMs: DEFAULT_TIMEOUT_MS4 },
27237
+ false
27238
+ );
27239
+ if (result.timedOut) throw new Error("selection agent timed out");
27240
+ if (result.exitCode !== 0) throw new Error(`selection agent exited with code ${result.exitCode}`);
27241
+ const parsed = parseSelectToolCallLines(result.stdout);
27242
+ for (const warning of parsed.warnings) process.stderr.write(`Warning: selection agent: ${warning}
27243
+ `);
27244
+ const byName = new Map(parsed.calls.map((call) => [call.name, call]));
28147
27245
  const writeDb = openPipelineDb();
28148
27246
  try {
28149
27247
  writeDb.exec("BEGIN");
@@ -28151,27 +27249,15 @@ async function runSelectionAgent(options) {
28151
27249
  `UPDATE raw_components SET status = ?, reject_reason = ? WHERE session_id = ? AND component_id = ?`
28152
27250
  );
28153
27251
  for (const component of components) {
28154
- const cached = cachedDecisions.get(component.name);
28155
27252
  const call = byName.get(component.name);
28156
- if (!cached && !call) continue;
28157
- const rejected = cached ? cached.decision === "rejected" : call.tool === "reject_component";
28158
- const reason = cached ? cached.reason : call.reason ?? null;
27253
+ if (!call) continue;
27254
+ const rejected = call.tool === "reject_component";
28159
27255
  update.run(
28160
27256
  rejected ? "rejected" : "accepted",
28161
- rejected ? reason : null,
27257
+ rejected ? call.reason ?? null : null,
28162
27258
  options.sessionId,
28163
27259
  component.component_id
28164
27260
  );
28165
- if (!cached) {
28166
- storeSelectCache(
28167
- writeDb,
28168
- hashComponentShape(component),
28169
- promptHash,
28170
- cliVersion2,
28171
- rejected ? "rejected" : "accepted",
28172
- rejected ? reason : null
28173
- );
28174
- }
28175
27261
  }
28176
27262
  writeDb.exec("COMMIT");
28177
27263
  } catch (error) {
@@ -28181,19 +27267,15 @@ async function runSelectionAgent(options) {
28181
27267
  writeDb.close();
28182
27268
  }
28183
27269
  }
28184
- var SELECT_PAYLOAD_FORMAT, DEFAULT_TIMEOUT_MS4;
27270
+ var DEFAULT_TIMEOUT_MS4;
28185
27271
  var init_run_selection_agent = __esm({
28186
27272
  "packages/experience-design-system-cli-legacy/src/import/tui/run-selection-agent.ts"() {
28187
27273
  "use strict";
28188
27274
  init_src2();
28189
- init_prop_bucket_debug();
28190
- init_strip_extraction_provenance();
28191
27275
  init_src();
28192
27276
  init_debug_logger();
28193
27277
  init_agent_output();
28194
27278
  init_db();
28195
- init_cache_keys();
28196
- SELECT_PAYLOAD_FORMAT = "prop-buckets-v1";
28197
27279
  DEFAULT_TIMEOUT_MS4 = Number(process.env.EDS_AGENT_TIMEOUT_MS ?? 5 * 60 * 1e3);
28198
27280
  }
28199
27281
  });
@@ -28212,7 +27294,7 @@ __export(WizardApp_exports, {
28212
27294
  });
28213
27295
  import { useEffect as useEffect15, useRef as useRef10, useState as useState23 } from "react";
28214
27296
  import { Box as Box42, Text as Text46 } from "ink";
28215
- import { join as join23, resolve as resolve18 } from "node:path";
27297
+ import { join as join23, resolve as resolve17 } from "node:path";
28216
27298
  import { appendFileSync as appendFileSync2, writeFileSync } from "node:fs";
28217
27299
  import { access as access7, stat as stat5, writeFile as writeFile6 } from "node:fs/promises";
28218
27300
  import { tmpdir } from "node:os";
@@ -28225,28 +27307,21 @@ function buildGenerateComponentsArgs(opts) {
28225
27307
  if (opts.tokensPath) args.push("--tokens", opts.tokensPath);
28226
27308
  if (opts.model) args.push("--model", opts.model);
28227
27309
  if (opts.bedrock) args.push("--bedrock");
28228
- if (opts.noCache) args.push("--no-cache");
28229
27310
  if (opts.generatePromptPath) args.push("--generate-prompt-path", opts.generatePromptPath);
28230
27311
  for (const prompt of opts.promptOverrides ?? []) args.push("--prompt", prompt);
28231
27312
  if (opts.existingEntitiesPath) args.push("--existing-entities-path", opts.existingEntitiesPath);
28232
- if (opts.restoreCache) args.push("--restore-cache");
28233
- if (opts.cachedComponents && opts.cachedComponents.length > 0) {
28234
- args.push("--cached-components", JSON.stringify(opts.cachedComponents));
28235
- }
28236
27313
  return args;
28237
27314
  }
28238
27315
  function buildGenerateTokensArgs(opts) {
28239
27316
  const args = [findCliPath(), "__generate", "tokens", "--agent", opts.agent, "--raw-tokens", opts.rawTokensPath];
28240
27317
  if (opts.model) args.push("--model", opts.model);
28241
27318
  if (opts.bedrock) args.push("--bedrock");
28242
- if (opts.noCache) args.push("--no-cache");
28243
27319
  for (const prompt of opts.promptOverrides ?? []) args.push("--prompt", prompt);
28244
27320
  return args;
28245
27321
  }
28246
27322
  function buildMapTokensArgs(opts) {
28247
27323
  const args = ["map", "tokens", "--session", opts.sessionId, "--agent", opts.agent];
28248
27324
  if (opts.model) args.push("--model", opts.model);
28249
- if (opts.noCache) args.push("--no-cache");
28250
27325
  if (opts.skipAgent) args.push("--skip-agent");
28251
27326
  for (const prompt of opts.promptOverrides ?? []) args.push("--prompt", prompt);
28252
27327
  if (opts.existingEntitiesPath) args.push("--existing-entities-path", opts.existingEntitiesPath);
@@ -28338,7 +27413,6 @@ function WizardApp({
28338
27413
  initialProjectPath,
28339
27414
  host,
28340
27415
  promptOverrides,
28341
- noCache = false,
28342
27416
  livePreview = true,
28343
27417
  generatePromptPath,
28344
27418
  skipMapTokens = false,
@@ -28363,7 +27437,6 @@ function WizardApp({
28363
27437
  });
28364
27438
  const allowEmptyDeleteAllRef = useRef10(false);
28365
27439
  const generateChildRef = useRef10(null);
28366
- const generationCachePreflightRef = useRef10(null);
28367
27440
  const selectionToReviewStartedAtRef = useRef10(null);
28368
27441
  const credentialsValidationIdRef = useRef10(0);
28369
27442
  const pendingCredentialValidationRef = useRef10(null);
@@ -28378,9 +27451,8 @@ function WizardApp({
28378
27451
  const existingEntitiesPromiseRef = useRef10(null);
28379
27452
  const generatePromiseRef = useRef10(null);
28380
27453
  const rawTokensEntryReady = !!initialRawTokensPath;
28381
- const effectiveNoCache = resolveNoCacheForGenerate({ cliNoCache: noCache });
28382
27454
  const initialStepResolved = rawTokensEntryReady ? initialProjectPath ? "path-validation" : "credentials" : initialProjectPath ? "token-input" : "welcome";
28383
- const initialOutDir = initialProjectPath ? join23(resolve18(initialProjectPath), ".contentful") : "";
27455
+ const initialOutDir = initialProjectPath ? join23(resolve17(initialProjectPath), ".contentful") : "";
28384
27456
  const [state, setState] = useState23({
28385
27457
  step: initialStepResolved,
28386
27458
  agent: initialAgent ?? "claude",
@@ -28556,14 +27628,13 @@ If you are using AWS Bedrock, run:
28556
27628
  if (!deferStep) update({ step: nextStep });
28557
27629
  return true;
28558
27630
  };
28559
- const runGenerateTokens = async (rawTokensPath, outDir, forceRegenerate = false) => {
27631
+ const runGenerateTokens = async (rawTokensPath, outDir) => {
28560
27632
  update({ tokenGenerationStatus: "running" });
28561
27633
  const tokenArgs = buildGenerateTokensArgs({
28562
27634
  rawTokensPath,
28563
27635
  agent: state.agent,
28564
27636
  ...state.agentModel ? { model: state.agentModel } : {},
28565
27637
  ...state.bedrock ? { bedrock: true } : {},
28566
- noCache: effectiveNoCache || forceRegenerate,
28567
27638
  promptOverrides
28568
27639
  });
28569
27640
  const result = await runSpawnedCli(tokenArgs);
@@ -28612,7 +27683,6 @@ If you are using AWS Bedrock, run:
28612
27683
  const timer = startWizardTimer("token-mapping", {
28613
27684
  sessionId: sessionId2,
28614
27685
  silent,
28615
- noCache: effectiveNoCache,
28616
27686
  skipAgent: skipMapTokens
28617
27687
  });
28618
27688
  let mappablePropCount = 0;
@@ -28621,7 +27691,7 @@ If you are using AWS Bedrock, run:
28621
27691
  const db = openPipelineDb();
28622
27692
  try {
28623
27693
  if (state.tokenSessionId && state.tokenSessionId !== sessionId2) {
28624
- copyTokensFromCache(db, state.tokenSessionId, sessionId2);
27694
+ copyTokensBetweenSessions(db, state.tokenSessionId, sessionId2);
28625
27695
  } else if (!state.tokenSessionId && state.tokensPath) {
28626
27696
  const tokens = await readTokensFromPath("tokens", state.tokensPath);
28627
27697
  storeDtcgTokens(db, sessionId2, [], tokens);
@@ -28661,7 +27731,6 @@ If you are using AWS Bedrock, run:
28661
27731
  sessionId: sessionId2,
28662
27732
  agent: state.agent,
28663
27733
  ...state.agentModel ? { model: state.agentModel } : {},
28664
- noCache: effectiveNoCache,
28665
27734
  skipAgent: skipMapTokens,
28666
27735
  promptOverrides,
28667
27736
  ...state.existingEntitiesPath ? { existingEntitiesPath: state.existingEntitiesPath } : {}
@@ -28741,7 +27810,7 @@ If you are using AWS Bedrock, run:
28741
27810
  return promise;
28742
27811
  };
28743
27812
  const runExtract = async (projectPath, showProgress = true) => {
28744
- const outDir = join23(resolve18(projectPath), ".contentful");
27813
+ const outDir = join23(resolve17(projectPath), ".contentful");
28745
27814
  const existingEntitiesExpected = !state.credentialsSkipped && Boolean(state.spaceId && state.environmentId && state.cmaToken && projectPath);
28746
27815
  update({
28747
27816
  ...showProgress ? { step: "extracting" } : {},
@@ -28756,10 +27825,6 @@ If you are using AWS Bedrock, run:
28756
27825
  });
28757
27826
  const existingEntitiesPromise = startExistingEntitiesFetch(projectPath, outDir);
28758
27827
  const extractArgs = [findCliPath(), "__extract", "--project", projectPath];
28759
- if (effectiveNoCache) extractArgs.push("--composition-refresh", "--no-cache");
28760
- for (const p of promptOverrides ?? []) extractArgs.push("--prompt", p);
28761
- if (state.agent) extractArgs.push("--agent", state.agent);
28762
- if (state.bedrock) extractArgs.push("--bedrock");
28763
27828
  let selectionPromptText;
28764
27829
  let selectionPromptPath;
28765
27830
  try {
@@ -28768,7 +27833,7 @@ If you are using AWS Bedrock, run:
28768
27833
  const selectOverride = overrides.get("select");
28769
27834
  if (selectOverride?.kind === "text") selectionPromptText = selectOverride.value;
28770
27835
  if (selectOverride?.kind === "path") {
28771
- selectionPromptPath = resolve18(selectOverride.value);
27836
+ selectionPromptPath = resolve17(selectOverride.value);
28772
27837
  await resolvePromptOverride(selectOverride);
28773
27838
  }
28774
27839
  } catch (error) {
@@ -28792,8 +27857,7 @@ If you are using AWS Bedrock, run:
28792
27857
  agent: state.agent,
28793
27858
  ...state.agentModel ? { model: state.agentModel } : {},
28794
27859
  ...selectionPromptText !== void 0 ? { promptText: selectionPromptText } : {},
28795
- ...selectionPromptPath ? { promptPath: selectionPromptPath } : {},
28796
- noCache: effectiveNoCache
27860
+ ...selectionPromptPath ? { promptPath: selectionPromptPath } : {}
28797
27861
  });
28798
27862
  })().catch((error) => {
28799
27863
  selectionError = error;
@@ -28928,146 +27992,27 @@ Make sure this path contains TypeScript/React/Vue component files (.tsx, .ts, .v
28928
27992
  child.kill("SIGTERM");
28929
27993
  } catch {
28930
27994
  }
28931
- }
28932
- generateChildRef.current = null;
28933
- generatePromiseRef.current = null;
28934
- setState((prev) => ({
28935
- ...prev,
28936
- generatePrefetchStatus: "idle",
28937
- generatePrefetchError: null,
28938
- generateProgress: null
28939
- }));
28940
- };
28941
- const buildGenerateOptions = (extractSessionId, tokensPath, generatePromptPath2, cachedComponents) => ({
28942
- sessionId: extractSessionId,
28943
- tokensPath,
28944
- agent: state.agent,
28945
- ...state.agentModel ? { model: state.agentModel } : {},
28946
- ...state.bedrock ? { bedrock: true } : {},
28947
- noCache: effectiveNoCache,
28948
- ...state.existingEntitiesPath ? { existingEntitiesPath: state.existingEntitiesPath } : {},
28949
- ...generatePromptPath2 ? { generatePromptPath: generatePromptPath2 } : {},
28950
- promptOverrides,
28951
- ...cachedComponents && cachedComponents.length > 0 ? { cachedComponents } : {}
28952
- });
28953
- const buildGenerateArgs = (extractSessionId, tokensPath, generatePromptPath2, cachedComponents) => buildGenerateProcessArgs(buildGenerateOptions(extractSessionId, tokensPath, generatePromptPath2, cachedComponents));
28954
- const buildGenerateCliArgs = (extractSessionId, tokensPath, generatePromptPath2, cachedComponents) => buildGenerateComponentsArgs(
28955
- buildGenerateOptions(extractSessionId, tokensPath, generatePromptPath2, cachedComponents)
28956
- );
28957
- const checkGenerateCache = async (extractSessionId, tokensPath) => {
28958
- const timer = startWizardTimer("generation-cache-status", {
28959
- sessionId: extractSessionId,
28960
- noCache: effectiveNoCache
28961
- });
28962
- if (effectiveNoCache) {
28963
- finishWizardTimer("generation-cache-status", timer, { status: "skipped" });
28964
- return false;
28965
- }
28966
- const result = await runCli([...buildGenerateCliArgs(extractSessionId, tokensPath), "--cache-status"]);
28967
- const hit = result.exitCode === 0 && /^cache-status=hit$/m.test(result.stdout);
28968
- finishWizardTimer("generation-cache-status", timer, {
28969
- status: hit ? "hit" : "miss",
28970
- exitCode: result.exitCode,
28971
- ...result.exitCode !== 0 ? { stderrTail: result.stderr.trim().slice(-500) } : {}
28972
- });
28973
- return hit;
28974
- };
28975
- const checkGenerateCacheComponents = async (extractSessionId, tokensPath, restoreCache = false) => {
28976
- const timer = startWizardTimer("generation-cache-components", {
28977
- sessionId: extractSessionId,
28978
- restoreCache,
28979
- noCache: effectiveNoCache
28980
- });
28981
- if (effectiveNoCache) {
28982
- finishWizardTimer("generation-cache-components", timer, { status: "skipped" });
28983
- return /* @__PURE__ */ new Set();
28984
- }
28985
- const args = [...buildGenerateCliArgs(extractSessionId, tokensPath), "--cache-status"];
28986
- if (restoreCache) args.push("--restore-cache");
28987
- const result = await runCli(args);
28988
- if (result.exitCode !== 0) {
28989
- finishWizardTimer("generation-cache-components", timer, {
28990
- status: "error",
28991
- exitCode: result.exitCode,
28992
- stderrTail: result.stderr.trim().slice(-500)
28993
- });
28994
- return /* @__PURE__ */ new Set();
28995
- }
28996
- const line = /^cache-components=(.+)$/m.exec(result.stdout)?.[1];
28997
- if (!line) {
28998
- finishWizardTimer("generation-cache-components", timer, {
28999
- status: "missing-output",
29000
- exitCode: result.exitCode,
29001
- cachedCount: 0
29002
- });
29003
- return /* @__PURE__ */ new Set();
29004
- }
29005
- try {
29006
- const names = JSON.parse(line);
29007
- const cachedNames = new Set(
29008
- Array.isArray(names) ? names.filter((name) => typeof name === "string") : []
29009
- );
29010
- finishWizardTimer("generation-cache-components", timer, {
29011
- status: "complete",
29012
- exitCode: result.exitCode,
29013
- cachedCount: cachedNames.size
29014
- });
29015
- return cachedNames;
29016
- } catch {
29017
- finishWizardTimer("generation-cache-components", timer, {
29018
- status: "invalid-output",
29019
- exitCode: result.exitCode,
29020
- cachedCount: 0
29021
- });
29022
- return /* @__PURE__ */ new Set();
29023
- }
29024
- };
29025
- useEffect15(() => {
29026
- if (state.step !== "extracting" && state.step !== "scope-gate" || !state.extractSessionId || state.existingEntitiesStatus === "running" || state.existingEntitiesStatus === "idle" || state.selectionAgentStatus !== "complete" || state.compositionPhase !== "done" && state.compositionPhase !== "cache-hit" || state.rawTokensPath && state.tokenGenerationStatus !== "complete" || effectiveNoCache) {
29027
- return;
29028
- }
29029
- const sessionId2 = state.extractSessionId;
29030
- if (generationCachePreflightRef.current?.sessionId === sessionId2) return;
29031
- const timer = startWizardTimer("generation-cache-preflight", { sessionId: sessionId2 });
29032
- const db = openPipelineDb();
29033
- let generatedNames = null;
29034
- try {
29035
- const rows = db.prepare("SELECT name, status FROM raw_components WHERE session_id = ?").all(sessionId2);
29036
- if (rows.length > 0 && rows.every((row) => row.status === "generated")) {
29037
- generatedNames = new Set(rows.map((row) => row.name));
29038
- }
29039
- } finally {
29040
- db.close();
29041
- }
29042
- if (generatedNames) {
29043
- generationCachePreflightRef.current = { sessionId: sessionId2, promise: Promise.resolve(generatedNames) };
29044
- finishWizardTimer("generation-cache-preflight", timer, {
29045
- status: "complete",
29046
- source: "session-db",
29047
- cachedCount: generatedNames.size
29048
- });
29049
- return;
29050
- }
29051
- const promise = checkGenerateCacheComponents(sessionId2, state.tokensPath, true);
29052
- generationCachePreflightRef.current = { sessionId: sessionId2, promise };
29053
- void promise.then((cachedNames) => {
29054
- finishWizardTimer("generation-cache-preflight", timer, {
29055
- status: "complete",
29056
- source: "cache-status",
29057
- cachedCount: cachedNames.size
29058
- });
29059
- });
29060
- }, [
29061
- state.step,
29062
- state.extractSessionId,
29063
- state.tokensPath,
29064
- state.rawTokensPath,
29065
- state.tokenGenerationStatus,
29066
- state.selectionAgentStatus,
29067
- state.compositionPhase,
29068
- state.existingEntitiesStatus,
29069
- state.existingEntitiesPath
29070
- ]);
27995
+ }
27996
+ generateChildRef.current = null;
27997
+ generatePromiseRef.current = null;
27998
+ setState((prev) => ({
27999
+ ...prev,
28000
+ generatePrefetchStatus: "idle",
28001
+ generatePrefetchError: null,
28002
+ generateProgress: null
28003
+ }));
28004
+ };
28005
+ const buildGenerateOptions = (extractSessionId, tokensPath, generatePromptPath2) => ({
28006
+ sessionId: extractSessionId,
28007
+ tokensPath,
28008
+ agent: state.agent,
28009
+ ...state.agentModel ? { model: state.agentModel } : {},
28010
+ ...state.bedrock ? { bedrock: true } : {},
28011
+ ...state.existingEntitiesPath ? { existingEntitiesPath: state.existingEntitiesPath } : {},
28012
+ ...generatePromptPath2 ? { generatePromptPath: generatePromptPath2 } : {},
28013
+ promptOverrides
28014
+ });
28015
+ const buildGenerateArgs = (extractSessionId, tokensPath, generatePromptPath2) => buildGenerateProcessArgs(buildGenerateOptions(extractSessionId, tokensPath, generatePromptPath2));
29071
28016
  const startGeneratePrefetch = (extractSessionId, tokensPath) => {
29072
28017
  const args = buildGenerateArgs(extractSessionId, tokensPath);
29073
28018
  let progressCursor = null;
@@ -29122,14 +28067,13 @@ Make sure this path contains TypeScript/React/Vue component files (.tsx, .ts, .v
29122
28067
  });
29123
28068
  return donePromise;
29124
28069
  };
29125
- const runGenerate = async (extractSessionId, tokensPath, acceptedCount, suppressScreen = false, cachedComponents = []) => {
28070
+ const runGenerate = async (extractSessionId, tokensPath, acceptedCount, suppressScreen = false) => {
29126
28071
  const timer = startWizardTimer("component-generation", {
29127
28072
  sessionId: extractSessionId,
29128
28073
  acceptedCount,
29129
- suppressScreen,
29130
- noCache: effectiveNoCache
28074
+ suppressScreen
29131
28075
  });
29132
- const args = buildGenerateArgs(extractSessionId, tokensPath, generatePromptPath, cachedComponents);
28076
+ const args = buildGenerateArgs(extractSessionId, tokensPath, generatePromptPath);
29133
28077
  let progressCursor = state.generateProgress;
29134
28078
  const { donePromise } = spawnGenerateChild({
29135
28079
  command: "node",
@@ -29199,25 +28143,6 @@ Make sure this path contains TypeScript/React/Vue component files (.tsx, .ts, .v
29199
28143
  finishSelectionToReviewTimer("error");
29200
28144
  }
29201
28145
  };
29202
- const finishCachedGeneration = async (sessionId2, acceptedCount) => {
29203
- if (await runMapTokens2(sessionId2, true)) {
29204
- finishSelectionToReviewTimer("cached");
29205
- update(
29206
- {
29207
- acceptedCount,
29208
- autoRejectedCount: 0,
29209
- generateSessionId: sessionId2,
29210
- generatedCount: acceptedCount,
29211
- generateProgress: null,
29212
- mapTokensStatus: "complete",
29213
- step: "final-review"
29214
- },
29215
- { clearScreen: false }
29216
- );
29217
- } else {
29218
- finishSelectionToReviewTimer("error");
29219
- }
29220
- };
29221
28146
  const advanceToPushFlow = (generatedAcceptedCount) => {
29222
28147
  update({ generatedAcceptedCount });
29223
28148
  void runSaveAndPush();
@@ -29402,14 +28327,8 @@ Make sure this path contains TypeScript/React/Vue component files (.tsx, .ts, .v
29402
28327
  }
29403
28328
  }
29404
28329
  if (await runAgentAuthCheck("generating", true)) {
29405
- const cacheHit = await checkGenerateCache(sid, state.tokensPath);
29406
- if (cacheHit) {
29407
- update({ step: "generating" });
29408
- void finishCachedGeneration(sid, state.acceptedCount);
29409
- } else {
29410
- update({ step: "generating" });
29411
- void runGenerate(sid, state.tokensPath, state.acceptedCount);
29412
- }
28330
+ update({ step: "generating" });
28331
+ void runGenerate(sid, state.tokensPath, state.acceptedCount);
29413
28332
  }
29414
28333
  return;
29415
28334
  }
@@ -29773,7 +28692,7 @@ If using a custom host configuration, make sure the space exists on that host.`
29773
28692
  });
29774
28693
  return { ok: false };
29775
28694
  }
29776
- await new Promise((resolve22) => setTimeout(resolve22, SAVE_CONFIRMATION_DELAY_MS));
28695
+ await new Promise((resolve20) => setTimeout(resolve20, SAVE_CONFIRMATION_DELAY_MS));
29777
28696
  update(nextStateAfterPrint({ skipGate: opts.skipGate, componentsPath }));
29778
28697
  return { ok: true };
29779
28698
  };
@@ -29850,12 +28769,6 @@ If using a custom host configuration, make sure the space exists on that host.`
29850
28769
  tokenReuseChecked.current = true;
29851
28770
  const tokenNextStep = state.projectPath ? "path-validation" : "credentials";
29852
28771
  const existingTokensPath = join23(state.outDir, "tokens.json");
29853
- if (effectiveNoCache) {
29854
- tokenGenerationPromiseRef.current = runAgentAuthCheck(tokenNextStep).then(
29855
- (ok2) => ok2 ? runGenerateTokens(state.rawTokensPath, state.outDir) : false
29856
- );
29857
- return;
29858
- }
29859
28772
  (async () => {
29860
28773
  try {
29861
28774
  await access7(existingTokensPath);
@@ -29939,7 +28852,7 @@ If using a custom host configuration, make sure the space exists on that host.`
29939
28852
  const tokenNextStep = state.projectPath ? "path-validation" : "credentials";
29940
28853
  update({ step: tokenNextStep });
29941
28854
  if (await runAgentAuthCheck(tokenNextStep)) {
29942
- tokenGenerationPromiseRef.current = runGenerateTokens(state.rawTokensPath, state.outDir, true);
28855
+ tokenGenerationPromiseRef.current = runGenerateTokens(state.rawTokensPath, state.outDir);
29943
28856
  }
29944
28857
  },
29945
28858
  onQuit: () => process.exit(0)
@@ -29973,7 +28886,7 @@ If using a custom host configuration, make sure the space exists on that host.`
29973
28886
  );
29974
28887
  case "extracting": {
29975
28888
  const ep = state.extractProgress;
29976
- const compositionComplete = state.compositionPhase === "done" || state.compositionPhase === "cache-hit";
28889
+ const compositionComplete = state.compositionPhase === "done";
29977
28890
  const tokenGenerationComplete = !state.rawTokensPath || state.tokenGenerationStatus === "complete";
29978
28891
  const extractionTasksComplete = ep !== null && ep.totalFiles > 0 && compositionComplete && state.selectionAgentStatus === "complete" && tokenGenerationComplete && state.existingEntitiesStatus !== "running";
29979
28892
  if (extractionTasksComplete) return null;
@@ -29988,7 +28901,7 @@ If using a custom host configuration, make sure the space exists on that host.`
29988
28901
  extractDetail = "Scanning files...";
29989
28902
  }
29990
28903
  const selectionDetail = state.selectionAgentStatus === "complete" ? "Selection agent complete" : `Filtering component selection via ${state.agent}...`;
29991
- const compositionDetail = state.compositionPhase === "cache-hit" ? "Composition mapping (cached)" : compositionComplete ? "Composition mapping complete" : state.compositionPhase?.startsWith("agent:") ? `Mapping composition via ${state.compositionPhase.slice("agent:".length)}...` : `Mapping composition via ${state.agent}...`;
28904
+ const compositionDetail = compositionComplete ? "Composition mapping complete" : "Mapping composition from source call sites...";
29992
28905
  return /* @__PURE__ */ jsx50(
29993
28906
  RunningStep,
29994
28907
  {
@@ -30038,29 +28951,6 @@ If using a custom host configuration, make sure the space exists on that host.`
30038
28951
  acceptedCount: decisions.accepted.length,
30039
28952
  rejectedCount: decisions.rejected.length
30040
28953
  }) : null;
30041
- const preflight = generationCachePreflightRef.current;
30042
- const cachePromise = preflight?.sessionId === sessionId2 ? preflight.promise : checkGenerateCacheComponents(sessionId2, state.tokensPath, true);
30043
- if (!preflight || preflight.sessionId !== sessionId2) {
30044
- generationCachePreflightRef.current = { sessionId: sessionId2, promise: cachePromise };
30045
- }
30046
- const cacheWaitStartedAt = startWizardTimer("selection-cache-restoration-wait", {
30047
- sessionId: sessionId2,
30048
- preflight: Boolean(preflight?.sessionId === sessionId2)
30049
- });
30050
- try {
30051
- const cachedNames = await cachePromise;
30052
- finishWizardTimer("selection-cache-restoration-wait", cacheWaitStartedAt, {
30053
- status: "complete",
30054
- cachedCount: cachedNames.size
30055
- });
30056
- } catch (error) {
30057
- finishWizardTimer("selection-cache-restoration-wait", cacheWaitStartedAt, {
30058
- status: "error",
30059
- error: error instanceof Error ? error.message : String(error)
30060
- });
30061
- finishSelectionToReviewTimer("error");
30062
- throw error;
30063
- }
30064
28954
  await runScopeGate({
30065
28955
  sessionId: sessionId2,
30066
28956
  decisions,
@@ -30069,35 +28959,12 @@ If using a custom host configuration, make sure the space exists on that host.`
30069
28959
  if (shouldGenerateAfterScopeGate({ acceptedCount })) {
30070
28960
  const authPromise = runAgentAuthCheck("generating", true);
30071
28961
  if (await authPromise) {
30072
- const comparisonStartedAt = startWizardTimer("generation-cache-set-comparison", {
30073
- sessionId: sid,
30074
- acceptedCount: decisions?.accepted.length ?? 0
30075
- });
30076
- let cachedNames = await cachePromise;
30077
- const acceptedNames = decisions?.accepted ?? [];
30078
- let cacheHit = !effectiveNoCache && acceptedNames.length > 0 && acceptedNames.every((name) => cachedNames.has(name));
30079
- if (!cacheHit && !effectiveNoCache && acceptedNames.length > 0) {
30080
- cachedNames = await checkGenerateCacheComponents(sid, state.tokensPath, true);
30081
- cacheHit = acceptedNames.every((name) => cachedNames.has(name));
30082
- }
30083
- finishWizardTimer("generation-cache-set-comparison", comparisonStartedAt, {
30084
- status: "complete",
30085
- cacheHit,
30086
- cachedCount: cachedNames.size,
30087
- acceptedCount: acceptedNames.length
28962
+ update({
28963
+ step: "generating",
28964
+ generateProgress: null,
28965
+ acceptedCount
30088
28966
  });
30089
- if (cacheHit) {
30090
- void finishCachedGeneration(sid, acceptedCount);
30091
- } else {
30092
- const acceptedNameSet = new Set(acceptedNames);
30093
- const restoredCachedNames = [...cachedNames].filter((name) => acceptedNameSet.has(name));
30094
- update({
30095
- step: "generating",
30096
- generateProgress: null,
30097
- acceptedCount
30098
- });
30099
- void runGenerate(sid, state.tokensPath, acceptedCount, false, restoredCachedNames);
30100
- }
28967
+ void runGenerate(sid, state.tokensPath, acceptedCount);
30101
28968
  } else {
30102
28969
  finishSelectionToReviewTimer("error");
30103
28970
  }
@@ -30463,7 +29330,7 @@ function registerImportCommand(program) {
30463
29330
  "Override a composition, selection, token, generation, or token-mapping prompt (repeatable). value is a file path or literal text, e.g. --prompt select=./p.md",
30464
29331
  (v, acc) => [...acc, v],
30465
29332
  []
30466
- ).option("--no-cache", "Re-run all steps even if output already exists").action(async (opts) => {
29333
+ ).action(async (opts) => {
30467
29334
  const interactiveTerminalSupported = getInteractiveTerminalSupport().supported;
30468
29335
  if (opts.tokens !== void 0) {
30469
29336
  const { access: access9 } = await import("node:fs/promises");
@@ -30500,7 +29367,6 @@ function registerImportCommand(program) {
30500
29367
  ...resolvedModel ? { initialModel: resolvedModel } : {},
30501
29368
  initialProjectPath: opts.project !== "." ? normalizePath(opts.project) : void 0,
30502
29369
  ...buildCompositionForwardingOptions(opts),
30503
- noCache: opts.cache === false,
30504
29370
  skipMapTokens: false,
30505
29371
  livePreview: true,
30506
29372
  generatePromptPath: creds.generatePromptPath,
@@ -30588,7 +29454,7 @@ async function pathExists3(path) {
30588
29454
  return access8(path).then(() => true).catch(() => false);
30589
29455
  }
30590
29456
  function runSpawn(cmd, args, opts = {}) {
30591
- return new Promise((resolve22) => {
29457
+ return new Promise((resolve20) => {
30592
29458
  const child = spawn6(cmd, args, {
30593
29459
  cwd: opts.cwd,
30594
29460
  env: opts.env ?? process.env,
@@ -30600,7 +29466,7 @@ function runSpawn(cmd, args, opts = {}) {
30600
29466
  const settle = (result) => {
30601
29467
  if (settled) return;
30602
29468
  settled = true;
30603
- resolve22(result);
29469
+ resolve20(result);
30604
29470
  };
30605
29471
  child.on("error", (err) => settle({ exitCode: 1, stdout: "", stderr: err.message }));
30606
29472
  child.stdout.on("data", (d) => {
@@ -31801,13 +30667,13 @@ function PrerequisitesScreen({
31801
30667
  const driver = {
31802
30668
  ...base,
31803
30669
  emit: (event) => setEvents((current) => [...current, event]),
31804
- confirm: (question, defaultYes = true) => new Promise((resolve22) => {
30670
+ confirm: (question, defaultYes = true) => new Promise((resolve20) => {
31805
30671
  setConfirm({
31806
30672
  question,
31807
30673
  defaultYes,
31808
30674
  resolve: (answer) => {
31809
30675
  setConfirm(null);
31810
- resolve22(answer);
30676
+ resolve20(answer);
31811
30677
  }
31812
30678
  });
31813
30679
  })
@@ -31882,8 +30748,8 @@ function SetupScreen({
31882
30748
  useEffect21(() => {
31883
30749
  if (startedRef.current) return;
31884
30750
  startedRef.current = true;
31885
- const runScreen = (build) => new Promise((resolve22) => {
31886
- setScreen(build(resolve22));
30751
+ const runScreen = (build) => new Promise((resolve20) => {
30752
+ setScreen(build(resolve20));
31887
30753
  });
31888
30754
  void (async () => {
31889
30755
  const results = [];
@@ -32061,9 +30927,9 @@ var init_command8 = __esm({
32061
30927
  function rank(p) {
32062
30928
  if (p === "typed-slot") return 1;
32063
30929
  if (p === "structural") return 2;
32064
- if (p === "manifest") return 3;
32065
- if (p === "doc") return 4;
32066
- if (p.startsWith("adapter:")) return 5;
30930
+ if (p === "call-site") return 3;
30931
+ if (p === "manifest") return 4;
30932
+ if (p === "doc") return 5;
32067
30933
  return 6;
32068
30934
  }
32069
30935
  function mergeEdges(all) {
@@ -32099,65 +30965,6 @@ var init_merge_edges = __esm({
32099
30965
  }
32100
30966
  });
32101
30967
 
32102
- // packages/experience-design-system-cli-legacy/src/analyze/composition/parse-map-edges.ts
32103
- function parseMapEdges(raw, opts) {
32104
- const edges = [];
32105
- const warnings = [];
32106
- const { componentNames } = opts;
32107
- for (const line of raw.split("\n")) {
32108
- const trimmed = line.trim();
32109
- if (!trimmed.startsWith("{")) continue;
32110
- let obj;
32111
- try {
32112
- obj = JSON.parse(trimmed);
32113
- } catch {
32114
- warnings.push(`unparseable line: ${trimmed.slice(0, 120)}`);
32115
- continue;
32116
- }
32117
- if (typeof obj !== "object" || obj === null || !("tool" in obj)) continue;
32118
- const rec = obj;
32119
- if (!VALID_MAP_TOOL_NAMES.has(rec.tool)) {
32120
- warnings.push(`unknown tool: ${String(rec.tool)}`);
32121
- continue;
32122
- }
32123
- if (typeof rec.parent !== "string" || !rec.parent || typeof rec.child !== "string" || !rec.child) {
32124
- warnings.push("map_edge missing parent/child \u2014 skipped");
32125
- continue;
32126
- }
32127
- const { parent, child } = rec;
32128
- if (!componentNames.has(parent)) {
32129
- warnings.push(`map_edge names unknown component (parent): ${parent} \u2014 skipped`);
32130
- continue;
32131
- }
32132
- if (!componentNames.has(child)) {
32133
- warnings.push(`map_edge names unknown component (child): ${child} \u2014 skipped`);
32134
- continue;
32135
- }
32136
- const edge = { parent, child, provenance: "agent" };
32137
- if (typeof rec.slot === "string" && rec.slot) {
32138
- edge.slot = rec.slot;
32139
- }
32140
- if (rec.confidence !== void 0) {
32141
- if (typeof rec.confidence === "number" && rec.confidence >= 1 && rec.confidence <= 5) {
32142
- edge.confidence = rec.confidence;
32143
- } else {
32144
- warnings.push(
32145
- `map_edge (${parent}\u2192${child}): invalid confidence ${String(rec.confidence)} \u2014 edge kept without confidence`
32146
- );
32147
- }
32148
- }
32149
- edges.push(edge);
32150
- }
32151
- return { edges, warnings };
32152
- }
32153
- var VALID_MAP_TOOL_NAMES;
32154
- var init_parse_map_edges = __esm({
32155
- "packages/experience-design-system-cli-legacy/src/analyze/composition/parse-map-edges.ts"() {
32156
- "use strict";
32157
- VALID_MAP_TOOL_NAMES = /* @__PURE__ */ new Set(["map_edge"]);
32158
- }
32159
- });
32160
-
32161
30968
  // packages/experience-design-system-cli-legacy/src/analyze/composition/apply-mapping.ts
32162
30969
  function applyMapping(components, edges) {
32163
30970
  const warnings = [];
@@ -32217,44 +31024,9 @@ var init_apply_mapping = __esm({
32217
31024
  }
32218
31025
  });
32219
31026
 
32220
- // packages/experience-design-system-cli-legacy/src/analyze/composition/prompt-loader.ts
32221
- import { existsSync as existsSync10, readFileSync as readFileSync10 } from "node:fs";
32222
- import { dirname as dirname17, join as join27, resolve as resolve19 } from "node:path";
32223
- import { fileURLToPath as fileURLToPath3 } from "node:url";
32224
- function resolvePromptPath(fileName) {
32225
- const thisDir = dirname17(fileURLToPath3(import.meta.url));
32226
- let dir = thisDir;
32227
- for (; ; ) {
32228
- const candidate = join27(dir, "prompts");
32229
- if (existsSync10(candidate)) return join27(candidate, fileName);
32230
- const parent = resolve19(dir, "..");
32231
- if (parent === dir) {
32232
- throw new Error(
32233
- `prompt file missing from CLI installation (could not locate prompts/ directory from: ${thisDir})`
32234
- );
32235
- }
32236
- dir = parent;
32237
- }
32238
- }
32239
- function loadPrompt(fileName) {
32240
- const path = resolvePromptPath(fileName);
32241
- try {
32242
- return readFileSync10(path, "utf8");
32243
- } catch {
32244
- throw new Error(`prompt file missing from CLI installation \u2014 try reinstalling the CLI (looked for: ${path})`);
32245
- }
32246
- }
32247
- var init_prompt_loader = __esm({
32248
- "packages/experience-design-system-cli-legacy/src/analyze/composition/prompt-loader.ts"() {
32249
- "use strict";
32250
- }
32251
- });
32252
-
32253
31027
  // packages/experience-design-system-cli-legacy/src/analyze/composition/resolve-mapping.ts
32254
- async function resolveMapping(input) {
32255
- const componentNames = new Set(input.components.map((c2) => c2.name));
31028
+ function resolveMapping(input) {
32256
31029
  const collected = [];
32257
- const agentWarnings = [];
32258
31030
  for (const c2 of input.components) {
32259
31031
  for (const slot of c2.slots) {
32260
31032
  for (const child of slot.allowedComponents ?? []) {
@@ -32272,17 +31044,41 @@ async function resolveMapping(input) {
32272
31044
  if (input.extraEdges) {
32273
31045
  collected.push(...input.extraEdges);
32274
31046
  }
31047
+ for (const evidence of input.sourceCallSiteEvidence ?? []) {
31048
+ collected.push({
31049
+ parent: evidence.parent,
31050
+ child: evidence.child,
31051
+ ...evidence.slot ? { slot: evidence.slot } : {},
31052
+ citation: { sourcePath: evidence.sourcePath, startLine: evidence.startLine, endLine: evidence.endLine },
31053
+ provenance: "call-site"
31054
+ });
31055
+ }
32275
31056
  const coveredParents = new Set(collected.map((e) => e.parent));
32276
31057
  const residueParents = input.components.map((c2) => c2.name).filter((n) => !coveredParents.has(n));
32277
- const shouldRunAgent = input.forceAgent || residueParents.length > 0 && input.files.length > 0;
32278
- if (shouldRunAgent) {
32279
- const prompt = input.buildPrompt ? input.buildPrompt(input.files, [...componentNames]) : defaultPrompt(input.files, [...componentNames], input.promptOverride);
32280
- const raw = await input.runAgentFn({ prompt, files: input.files }) ?? "";
32281
- const parsed = parseMapEdges(raw, { componentNames });
32282
- collected.push(...parsed.edges);
32283
- agentWarnings.push(...parsed.warnings);
32284
- }
31058
+ const debug = getDebugLogger();
31059
+ const countByProvenance = (edges) => {
31060
+ const counts = {};
31061
+ for (const edge of edges) counts[edge.provenance] = (counts[edge.provenance] ?? 0) + 1;
31062
+ return counts;
31063
+ };
31064
+ debug.event("analyze", "composition.pre-merge", {
31065
+ edgeCountsByProvenance: countByProvenance(collected),
31066
+ coveredParents: [...coveredParents].sort(),
31067
+ residueParents,
31068
+ sourceCallSiteAccepted: input.sourceCallSiteEvidence?.length ?? 0,
31069
+ sourceCallSiteRejected: input.sourceCallSiteRejections?.length ?? 0
31070
+ });
32285
31071
  const merged = mergeEdges(collected);
31072
+ debug.event("analyze", "composition.merged", {
31073
+ edgeCountsByProvenance: countByProvenance(merged.edges),
31074
+ conflicts: merged.conflicts,
31075
+ edges: merged.edges.map((edge) => ({
31076
+ parent: edge.parent,
31077
+ child: edge.child,
31078
+ slot: edge.slot ?? null,
31079
+ provenance: edge.provenance
31080
+ }))
31081
+ });
32286
31082
  const base = input.components.map((c2) => ({
32287
31083
  ...c2,
32288
31084
  slots: c2.slots.map((s) => {
@@ -32291,127 +31087,32 @@ async function resolveMapping(input) {
32291
31087
  })
32292
31088
  }));
32293
31089
  const applied = applyMapping(base, merged.edges);
31090
+ debug.event("analyze", "composition.applied", {
31091
+ slots: applied.components.flatMap(
31092
+ (component) => component.slots.filter((slot) => (slot.allowedComponents?.length ?? 0) > 0).map((slot) => ({ component: component.name, slot: slot.name, allowedComponents: slot.allowedComponents }))
31093
+ ),
31094
+ warnings: applied.warnings
31095
+ });
32294
31096
  return {
32295
31097
  components: applied.components,
32296
31098
  edges: merged.edges,
32297
31099
  conflicts: merged.conflicts,
32298
- warnings: [...agentWarnings, ...applied.warnings]
31100
+ warnings: applied.warnings,
31101
+ sourceCallSiteEvidence: [...input.sourceCallSiteEvidence ?? []],
31102
+ sourceCallSiteRejections: [...input.sourceCallSiteRejections ?? []]
32299
31103
  };
32300
31104
  }
32301
- function defaultPrompt(files, componentNames, promptOverride) {
32302
- const fileBlocks = files.map((f) => `--- ${f.path} ---
32303
- ${f.content}`).join("\n\n");
32304
- const instruction = promptOverride?.trim() ? promptOverride.trim() : loadPrompt("composition-edges.md").trim();
32305
- return [
32306
- instruction,
32307
- "",
32308
- 'Emit one JSON object per line, each: {"tool":"map_edge","parent":"<Name>","child":"<Name>","slot"?:"<slot>","confidence"?:1-5,"reason":"<cite the file + declaration>"}.',
32309
- "Use ONLY these exact component names (an edge naming anything else is dropped):",
32310
- componentNames.join(", "),
32311
- "",
32312
- "Candidate files:",
32313
- fileBlocks
32314
- ].join("\n");
32315
- }
32316
31105
  var init_resolve_mapping = __esm({
32317
31106
  "packages/experience-design-system-cli-legacy/src/analyze/composition/resolve-mapping.ts"() {
32318
31107
  "use strict";
32319
31108
  init_merge_edges();
32320
- init_parse_map_edges();
32321
31109
  init_apply_mapping();
32322
- init_prompt_loader();
32323
- }
32324
- });
32325
-
32326
- // packages/experience-design-system-cli-legacy/src/analyze/composition/resolve-mapping-cli.ts
32327
- function resolveCompositionSources(opts) {
32328
- return {
32329
- forceAgent: opts.compositionRefresh === true || opts.noCache === true
32330
- };
32331
- }
32332
- var init_resolve_mapping_cli = __esm({
32333
- "packages/experience-design-system-cli-legacy/src/analyze/composition/resolve-mapping-cli.ts"() {
32334
- "use strict";
32335
- }
32336
- });
32337
-
32338
- // packages/experience-design-system-cli-legacy/src/analyze/composition/candidate-files.ts
32339
- function matchReason(file) {
32340
- const segments = file.path.split("/").filter((s) => s !== "");
32341
- for (const pattern of CANDIDATE_NAME_PATTERNS) {
32342
- if (segments.some((seg) => pattern.test(seg))) {
32343
- return `name:${pattern.source.toLowerCase()}`;
32344
- }
32345
- }
32346
- for (const marker of CANDIDATE_CONTENT_MARKERS) {
32347
- if (file.content.includes(marker)) return `content:${marker}`;
32348
- }
32349
- return void 0;
32350
- }
32351
- function selectCandidateFiles(files) {
32352
- const selected = [];
32353
- const seen = /* @__PURE__ */ new Set();
32354
- for (const file of files) {
32355
- if (seen.has(file.path)) continue;
32356
- const reason = matchReason(file);
32357
- if (reason === void 0) continue;
32358
- seen.add(file.path);
32359
- selected.push({ path: file.path, content: file.content, reason });
32360
- }
32361
- return selected;
32362
- }
32363
- function capCandidatesToPromptBudget(files, budget = PROMPT_CANDIDATE_TOKEN_BUDGET) {
32364
- const ordered = [...files].sort((a, b) => a.content.length - b.content.length || a.path.localeCompare(b.path));
32365
- const kept = [];
32366
- const dropped = [];
32367
- let spent = 0;
32368
- for (const file of ordered) {
32369
- const cost = tokenCost(file);
32370
- if (spent + cost > budget) {
32371
- dropped.push(file);
32372
- continue;
32373
- }
32374
- kept.push(file);
32375
- spent += cost;
32376
- }
32377
- return { kept, dropped };
32378
- }
32379
- function tokenCost(file) {
32380
- return Math.ceil(file.content.length / CHARS_PER_TOKEN);
32381
- }
32382
- var CANDIDATE_NAME_PATTERNS, CANDIDATE_CONTENT_MARKERS, PROMPT_CANDIDATE_TOKEN_BUDGET, CHARS_PER_TOKEN;
32383
- var init_candidate_files = __esm({
32384
- "packages/experience-design-system-cli-legacy/src/analyze/composition/candidate-files.ts"() {
32385
- "use strict";
32386
- CANDIDATE_NAME_PATTERNS = [/mapping/i, /meta/i, /registry/i, /schema/i, /composition/i];
32387
- CANDIDATE_CONTENT_MARKERS = [
32388
- "requiredParent",
32389
- "withParentType",
32390
- "allowedTagNames",
32391
- "createContext",
32392
- "MappingContext",
32393
- "allowedComponents"
32394
- ];
32395
- PROMPT_CANDIDATE_TOKEN_BUDGET = 8e4;
32396
- CHARS_PER_TOKEN = 4;
32397
- }
32398
- });
32399
-
32400
- // packages/experience-design-system-cli-legacy/src/analyze/composition/composition-cache-key.ts
32401
- function buildCompositionInputHash(input) {
32402
- const fileDigest = input.files.map((f) => `${f.path} ${hashContent(f.content)}`).sort().join("");
32403
- return hashContent(`agent:${input.agent}
32404
- ${fileDigest}`);
32405
- }
32406
- var init_composition_cache_key = __esm({
32407
- "packages/experience-design-system-cli-legacy/src/analyze/composition/composition-cache-key.ts"() {
32408
- "use strict";
32409
- init_cache_keys();
31110
+ init_debug_logger();
32410
31111
  }
32411
31112
  });
32412
31113
 
32413
31114
  // packages/experience-design-system-cli-legacy/src/analyze/composition/manifest-doc-evidence.ts
32414
- import { dirname as dirname18 } from "node:path";
31115
+ import { dirname as dirname17 } from "node:path";
32415
31116
  function kebabToPascal2(name) {
32416
31117
  return name.split("-").filter(Boolean).map((seg) => seg.charAt(0).toUpperCase() + seg.slice(1)).join("");
32417
31118
  }
@@ -32461,8 +31162,8 @@ function collectAgentsDocEdges(files, components, componentNames) {
32461
31162
  const seen = /* @__PURE__ */ new Set();
32462
31163
  for (const file of files) {
32463
31164
  if (!file.path.endsWith("AGENTS.md")) continue;
32464
- const docDir = dirname18(file.path);
32465
- const parent = components.find((c2) => c2.sourcePath && dirname18(c2.sourcePath) === docDir)?.name;
31165
+ const docDir = dirname17(file.path);
31166
+ const parent = components.find((c2) => c2.sourcePath && dirname17(c2.sourcePath) === docDir)?.name;
32466
31167
  if (!parent || !componentNames.has(parent)) continue;
32467
31168
  for (const line of file.content.split("\n")) {
32468
31169
  const lower = line.toLowerCase();
@@ -32492,12 +31193,172 @@ var init_manifest_doc_evidence = __esm({
32492
31193
  }
32493
31194
  });
32494
31195
 
32495
- // packages/experience-design-system-cli-legacy/src/analyze/extract-command.ts
32496
- import { mkdir as mkdir6, readdir as readdir3, readFile as readFile19, stat as stat6 } from "node:fs/promises";
32497
- import { isAbsolute as isAbsolute2, join as join28, relative as relative2, resolve as resolve20 } from "node:path";
32498
- function resolveExtractNoCache(opts) {
32499
- return opts.noCache === true || opts.cache === false;
31196
+ // packages/experience-design-system-cli-legacy/src/analyze/composition/source-call-site-evidence.ts
31197
+ import { Node as Node49, Project as Project11, SyntaxKind as SyntaxKind15 } from "ts-morph";
31198
+ function collectSourceCallSiteEvidence(files, components) {
31199
+ const componentNames = new Set(components.map((component) => component.name));
31200
+ const componentsBySource = /* @__PURE__ */ new Map();
31201
+ for (const component of components) {
31202
+ const sourcePath = component.sourcePath ?? component.source;
31203
+ const siblings = componentsBySource.get(sourcePath) ?? [];
31204
+ siblings.push(component);
31205
+ componentsBySource.set(sourcePath, siblings);
31206
+ }
31207
+ const project = new Project11({
31208
+ compilerOptions: { jsx: 1, target: 99, module: 99, moduleResolution: 100, skipLibCheck: true, allowJs: true },
31209
+ skipAddingFilesFromTsConfig: true
31210
+ });
31211
+ const sourceFiles = new Map(
31212
+ files.map((file) => [file.path, project.createSourceFile(file.path, file.content, { overwrite: true })])
31213
+ );
31214
+ const accepted = [];
31215
+ const rejected = [];
31216
+ for (const [sourcePath, parents] of componentsBySource) {
31217
+ const sourceFile = sourceFiles.get(sourcePath);
31218
+ if (!sourceFile) continue;
31219
+ const boundNames = collectBoundNames(sourceFile);
31220
+ for (const parent of parents) {
31221
+ for (const jsxElement of [
31222
+ ...sourceFile.getDescendantsOfKind(SyntaxKind15.JsxSelfClosingElement),
31223
+ ...sourceFile.getDescendantsOfKind(SyntaxKind15.JsxElement)
31224
+ ]) {
31225
+ const tagName = Node49.isJsxSelfClosingElement(jsxElement) ? jsxElement.getTagNameNode().getText() : jsxElement.getOpeningElement().getTagNameNode().getText();
31226
+ const candidate = tagName.split(".").at(-1) ?? tagName;
31227
+ if (candidate === parent.name || isIntrinsicTag(candidate)) continue;
31228
+ const lines = sourceExcerpt(sourceFile, jsxElement);
31229
+ if (!componentNames.has(candidate)) {
31230
+ rejected.push({ parent: parent.name, candidate, ...lines, reason: "unknown-component" });
31231
+ continue;
31232
+ }
31233
+ if (!boundNames.has(tagName) && !boundNames.has(candidate)) {
31234
+ rejected.push({ parent: parent.name, candidate, ...lines, reason: "unbound-component" });
31235
+ continue;
31236
+ }
31237
+ accepted.push({ parent: parent.name, child: candidate, ...lines, kind: "jsx-render" });
31238
+ }
31239
+ }
31240
+ }
31241
+ for (const sourceFile of sourceFiles.values()) {
31242
+ collectCallerSlotEvidence(sourceFile, componentNames, collectBoundNames(sourceFile), accepted, rejected);
31243
+ }
31244
+ const verifiedPairs = new Set(accepted.map((evidence) => `${evidence.parent}\0${evidence.child}`));
31245
+ for (const component of components) {
31246
+ const candidates = component.slots.flatMap((slot) => [
31247
+ ...slot.allowedComponents ?? [],
31248
+ ...slot.structuralAllowedComponents ?? []
31249
+ ]);
31250
+ for (const candidate of candidates) {
31251
+ if (verifiedPairs.has(`${component.name}\0${candidate}`)) continue;
31252
+ rejected.push({
31253
+ parent: component.name,
31254
+ candidate,
31255
+ sourcePath: component.sourcePath ?? component.source,
31256
+ reason: "no-call-site"
31257
+ });
31258
+ }
31259
+ }
31260
+ return {
31261
+ accepted: dedupeEvidence(accepted),
31262
+ rejected: dedupeRejections(rejected)
31263
+ };
32500
31264
  }
31265
+ function collectCallerSlotEvidence(sourceFile, componentNames, boundNames, accepted, rejected) {
31266
+ for (const parentElement of sourceFile.getDescendantsOfKind(SyntaxKind15.JsxElement)) {
31267
+ const parentTag = parentElement.getOpeningElement().getTagNameNode().getText();
31268
+ const parent = parentTag.split(".").at(-1) ?? parentTag;
31269
+ if (!componentNames.has(parent) || !boundNames.has(parentTag)) continue;
31270
+ for (const childNode of parentElement.getJsxChildren()) {
31271
+ if (!Node49.isJsxElement(childNode) && !Node49.isJsxSelfClosingElement(childNode)) {
31272
+ if (Node49.isJsxText(childNode) && childNode.getText().trim()) {
31273
+ const lines2 = sourceExcerpt(sourceFile, childNode);
31274
+ rejected.push({ parent, candidate: "<text>", ...lines2, reason: "text-only-child" });
31275
+ }
31276
+ continue;
31277
+ }
31278
+ const childTag = Node49.isJsxElement(childNode) ? childNode.getOpeningElement().getTagNameNode().getText() : childNode.getTagNameNode().getText();
31279
+ const child = childTag.split(".").at(-1) ?? childTag;
31280
+ if (isIntrinsicTag(child)) continue;
31281
+ const lines = sourceExcerpt(sourceFile, childNode);
31282
+ if (!componentNames.has(child)) {
31283
+ rejected.push({ parent, candidate: child, ...lines, reason: "unknown-component" });
31284
+ continue;
31285
+ }
31286
+ if (!boundNames.has(childTag) && !boundNames.has(child)) {
31287
+ rejected.push({ parent, candidate: child, ...lines, reason: "unbound-component" });
31288
+ continue;
31289
+ }
31290
+ const slotAttribute = Node49.isJsxElement(childNode) ? childNode.getOpeningElement().getAttribute("slot") : childNode.getAttribute("slot");
31291
+ const slotValue = slotAttribute && Node49.isJsxAttribute(slotAttribute) ? slotAttribute.getInitializer() : void 0;
31292
+ const slot = slotValue && Node49.isStringLiteral(slotValue) ? slotValue.getLiteralValue() : void 0;
31293
+ accepted.push({ parent, child, ...slot ? { slot } : {}, ...lines, kind: "jsx-render" });
31294
+ }
31295
+ }
31296
+ }
31297
+ function collectBoundNames(sourceFile) {
31298
+ const names = /* @__PURE__ */ new Set();
31299
+ for (const declaration of sourceFile.getImportDeclarations()) {
31300
+ const defaultImport = declaration.getDefaultImport();
31301
+ if (defaultImport) names.add(defaultImport.getText());
31302
+ const namespaceImport = declaration.getNamespaceImport();
31303
+ if (namespaceImport) names.add(namespaceImport.getText());
31304
+ for (const namedImport of declaration.getNamedImports()) {
31305
+ names.add((namedImport.getAliasNode() ?? namedImport.getNameNode()).getText());
31306
+ }
31307
+ }
31308
+ for (const declaration of sourceFile.getVariableDeclarations()) names.add(declaration.getName());
31309
+ for (const declaration of sourceFile.getFunctions()) {
31310
+ if (declaration.getName()) names.add(declaration.getName());
31311
+ }
31312
+ for (const declaration of sourceFile.getClasses()) {
31313
+ if (declaration.getName()) names.add(declaration.getName());
31314
+ }
31315
+ return names;
31316
+ }
31317
+ function sourceExcerpt(sourceFile, node) {
31318
+ const startLine = node.getStartLineNumber();
31319
+ const endLine = node.getEndLineNumber();
31320
+ const lines = sourceFile.getFullText().split("\n");
31321
+ return {
31322
+ sourcePath: sourceFile.getFilePath(),
31323
+ startLine,
31324
+ endLine,
31325
+ excerpt: lines.slice(startLine - 1, endLine).join("\n").trim()
31326
+ };
31327
+ }
31328
+ function isIntrinsicTag(tagName) {
31329
+ return /^[a-z]/.test(tagName) || tagName.includes("-");
31330
+ }
31331
+ function dedupeEvidence(evidence) {
31332
+ const seen = /* @__PURE__ */ new Set();
31333
+ return evidence.filter((item) => {
31334
+ const key = `${item.parent}\0${item.child}\0${item.slot ?? ""}\0${item.sourcePath}\0${item.startLine}`;
31335
+ if (seen.has(key)) return false;
31336
+ seen.add(key);
31337
+ return true;
31338
+ }).sort(
31339
+ (left, right) => `${left.parent}\0${left.child}\0${left.sourcePath}\0${left.startLine}`.localeCompare(
31340
+ `${right.parent}\0${right.child}\0${right.sourcePath}\0${right.startLine}`
31341
+ )
31342
+ );
31343
+ }
31344
+ function dedupeRejections(rejections) {
31345
+ const seen = /* @__PURE__ */ new Set();
31346
+ return rejections.filter((item) => {
31347
+ const key = `${item.parent}\0${item.candidate}\0${item.sourcePath}\0${item.startLine}`;
31348
+ if (seen.has(key)) return false;
31349
+ seen.add(key);
31350
+ return true;
31351
+ });
31352
+ }
31353
+ var init_source_call_site_evidence = __esm({
31354
+ "packages/experience-design-system-cli-legacy/src/analyze/composition/source-call-site-evidence.ts"() {
31355
+ "use strict";
31356
+ }
31357
+ });
31358
+
31359
+ // packages/experience-design-system-cli-legacy/src/analyze/extract-command.ts
31360
+ import { mkdir as mkdir6, readdir as readdir3, readFile as readFile18, stat as stat6 } from "node:fs/promises";
31361
+ import { isAbsolute as isAbsolute2, join as join27, relative as relative2, resolve as resolve18 } from "node:path";
32501
31362
  function isDenylistedNoiseFile(name) {
32502
31363
  return DENYLISTED_EXACT_FILE_NAMES.has(name) || DENYLISTED_FILE_NAME_PATTERNS.some((pattern) => pattern.test(name));
32503
31364
  }
@@ -32511,12 +31372,12 @@ async function retryDatabaseWrite(operation, attempts = 8) {
32511
31372
  } catch (error) {
32512
31373
  const message = error instanceof Error ? error.message : String(error);
32513
31374
  if (!/database is locked|database is busy/i.test(message) || attempt >= attempts) throw error;
32514
- await new Promise((resolve22) => setTimeout(resolve22, Math.min(250 * attempt, 2e3)));
31375
+ await new Promise((resolve20) => setTimeout(resolve20, Math.min(250 * attempt, 2e3)));
32515
31376
  }
32516
31377
  }
32517
31378
  }
32518
31379
  function resolveFromProjectRoot(projectRoot, inputPath) {
32519
- return isAbsolute2(inputPath) ? inputPath : resolve20(projectRoot, inputPath);
31380
+ return isAbsolute2(inputPath) ? inputPath : resolve18(projectRoot, inputPath);
32520
31381
  }
32521
31382
  async function pathExists4(path) {
32522
31383
  return Boolean(await stat6(path).catch(() => null));
@@ -32527,7 +31388,7 @@ async function collectSourceFiles(directory, onProgress) {
32527
31388
  const entries = await readdir3(currentDirectory, { withFileTypes: true });
32528
31389
  const subdirs = [];
32529
31390
  for (const entry of entries) {
32530
- const fullPath = join28(currentDirectory, entry.name);
31391
+ const fullPath = join27(currentDirectory, entry.name);
32531
31392
  if (entry.isDirectory()) {
32532
31393
  if (!IGNORED_DIRECTORY_NAMES.has(entry.name)) {
32533
31394
  subdirs.push(fullPath);
@@ -32554,12 +31415,6 @@ async function collectSourceFiles(directory, onProgress) {
32554
31415
  await visit(directory);
32555
31416
  return files.sort();
32556
31417
  }
32557
- function resolveCompositionAgentName(flagValue) {
32558
- if (flagValue && isAgentName(flagValue)) return flagValue;
32559
- const env = process.env["EDS_COMPOSITION_AGENT"];
32560
- if (env && isAgentName(env)) return env;
32561
- return DEFAULT_AGENT_NAME;
32562
- }
32563
31418
  async function readCandidateFiles(components, extraFiles = []) {
32564
31419
  const paths = new Set(extraFiles);
32565
31420
  for (const c2 of components) {
@@ -32569,7 +31424,7 @@ async function readCandidateFiles(components, extraFiles = []) {
32569
31424
  await Promise.all(
32570
31425
  [...paths].map(async (p) => {
32571
31426
  try {
32572
- const content = await readFile19(p, "utf8");
31427
+ const content = await readFile18(p, "utf8");
32573
31428
  out.push({ path: p, content });
32574
31429
  } catch {
32575
31430
  }
@@ -32578,21 +31433,11 @@ async function readCandidateFiles(components, extraFiles = []) {
32578
31433
  return out;
32579
31434
  }
32580
31435
  function registerInternalExtractCommand(program) {
32581
- const extractCmd = program.command("__extract", { hidden: true }).description("Extract component definitions from a project").requiredOption("--project <path>", "Path to the project root").option("--dir <path>", "Path to the component source directory relative to the project root").option(
31436
+ program.command("__extract", { hidden: true }).description("Extract component definitions from a project").requiredOption("--project <path>", "Path to the project root").option("--dir <path>", "Path to the component source directory relative to the project root").option(
32582
31437
  "--resolve-unreachable <mode>",
32583
31438
  "Retry pass for unresolved Svelte Props types: 'auto' (default), 'always', or 'never'",
32584
31439
  "auto"
32585
- ).option("--composition-refresh", "Force the mapping agent to run even where deterministic sources answered").option("--no-cache", "Re-run extraction even when all source files are unchanged").option(
32586
- "--prompt <stage=value>",
32587
- "Override a stage prompt (repeatable). value is a file path or literal text, e.g. --prompt composition=./p.md",
32588
- (v, acc) => [...acc, v],
32589
- []
32590
- );
32591
- addAgentModelOptions(extractCmd, {
32592
- includeModel: false,
32593
- agentDescription: "Coding agent for composition mapping resolution (claude|codex|opencode|cursor)"
32594
- }).action(async (opts) => {
32595
- const noCache = resolveExtractNoCache(opts);
31440
+ ).action(async (opts) => {
32596
31441
  const resolveUnreachable = (() => {
32597
31442
  const v = opts.resolveUnreachable ?? "auto";
32598
31443
  if (v !== "auto" && v !== "always" && v !== "never") {
@@ -32602,16 +31447,8 @@ function registerInternalExtractCommand(program) {
32602
31447
  }
32603
31448
  return v;
32604
31449
  })();
32605
- if (opts.bedrock) {
32606
- const bedrockAgent = resolveCompositionAgentName(opts.agent);
32607
- if (!agentSupportsBedrock(bedrockAgent)) {
32608
- process.stderr.write(`Error: --bedrock is not supported for --agent ${bedrockAgent}
32609
- `);
32610
- process.exit(1);
32611
- }
32612
- }
32613
- const projectRoot = resolve20(opts.project);
32614
- const outDir = join28(projectRoot, ".contentful");
31450
+ const projectRoot = resolve18(opts.project);
31451
+ const outDir = join27(projectRoot, ".contentful");
32615
31452
  let sourceDirectory;
32616
31453
  if (opts.dir !== void 0) {
32617
31454
  sourceDirectory = resolveFromProjectRoot(projectRoot, opts.dir);
@@ -32634,50 +31471,16 @@ function registerInternalExtractCommand(program) {
32634
31471
  process.stderr.write(`progress=scan-done:${sourceFiles.length}
32635
31472
  `);
32636
31473
  }
32637
- const extractionCacheDb = openPipelineDb();
32638
- let extraction;
32639
- let extractionCacheHits = 0;
32640
- try {
32641
- const cacheVersion = await getCliCacheVersion();
32642
- const cachedByPath = /* @__PURE__ */ new Map();
32643
- if (!noCache && sourceFiles.length > 0) {
32644
- const hashes = await Promise.all(
32645
- sourceFiles.map(async (filePath) => [filePath, await hashFile(filePath)])
32646
- );
32647
- for (const [filePath, fileHash] of hashes) {
32648
- cachedByPath.set(filePath, lookupExtractCache(extractionCacheDb, fileHash, cacheVersion));
32649
- }
32650
- }
32651
- const allFilesCached = !noCache && sourceFiles.length > 0 && sourceFiles.every((filePath) => cachedByPath.get(filePath) !== null);
32652
- if (allFilesCached) {
32653
- const cachedComponents = sourceFiles.flatMap((filePath) => cachedByPath.get(filePath).components);
32654
- extractionCacheHits = sourceFiles.length;
32655
- extraction = { components: cachedComponents, warnings: [], exclusions: [] };
31474
+ const extraction = await extractComponents(
31475
+ sourceFiles,
31476
+ ({ filesProcessed, componentsFound }) => {
32656
31477
  if (!process.stdout.isTTY) {
32657
- process.stderr.write(
32658
- `progress=extract:${sourceFiles.length}/${sourceFiles.length}:${cachedComponents.length}
32659
- `
32660
- );
32661
- }
32662
- getDebugLogger().event("analyze", "extract.cache-hit", {
32663
- files: sourceFiles.length,
32664
- components: cachedComponents.length
32665
- });
32666
- } else {
32667
- extraction = await extractComponents(
32668
- sourceFiles,
32669
- ({ filesProcessed, componentsFound }) => {
32670
- if (!process.stdout.isTTY) {
32671
- process.stderr.write(`progress=extract:${filesProcessed}/${sourceFiles.length}:${componentsFound}
31478
+ process.stderr.write(`progress=extract:${filesProcessed}/${sourceFiles.length}:${componentsFound}
32672
31479
  `);
32673
- }
32674
- },
32675
- { resolveUnreachable, projectRoot }
32676
- );
32677
- }
32678
- } finally {
32679
- extractionCacheDb.close();
32680
- }
31480
+ }
31481
+ },
31482
+ { resolveUnreachable, projectRoot }
31483
+ );
32681
31484
  await mkdir6(outDir, { recursive: true });
32682
31485
  const db = openPipelineDb();
32683
31486
  const { sessionId: sessionId2 } = getOrCreateSession(db, void 0, void 0, {
@@ -32692,25 +31495,6 @@ function registerInternalExtractCommand(program) {
32692
31495
  const stepId = createStep(db, sessionId2, "analyze extract", {
32693
31496
  project: projectRoot
32694
31497
  });
32695
- if (extractionCacheHits === 0 && !noCache) {
32696
- const cacheVersion = await getCliCacheVersion();
32697
- const componentsBySourcePath = /* @__PURE__ */ new Map();
32698
- for (const component of extraction.components) {
32699
- if (!component.sourcePath) continue;
32700
- const components = componentsBySourcePath.get(component.sourcePath) ?? [];
32701
- components.push(component);
32702
- componentsBySourcePath.set(component.sourcePath, components);
32703
- }
32704
- for (const filePath of sourceFiles) {
32705
- storeExtractCache(
32706
- db,
32707
- filePath,
32708
- await hashFile(filePath),
32709
- cacheVersion,
32710
- componentsBySourcePath.get(filePath) ?? []
32711
- );
32712
- }
32713
- }
32714
31498
  const classifiedComponents = extraction.components.map(preClassifyComponent);
32715
31499
  for (const exclusion of extraction.exclusions ?? []) {
32716
31500
  getDebugLogger().event("filter", "extract.excluded", { ...exclusion });
@@ -32734,28 +31518,9 @@ function registerInternalExtractCommand(program) {
32734
31518
  storeRawComponents(db, sessionId2, validatedComponents);
32735
31519
  process.stdout.write(`session=${sessionId2}
32736
31520
  `);
31521
+ let sourceCallSiteEvidence = [];
31522
+ let sourceCallSiteRejections = [];
32737
31523
  {
32738
- const sources = resolveCompositionSources({
32739
- ...opts,
32740
- noCache
32741
- });
32742
- const { overrides: promptOverrides, errors: promptErrors } = parsePromptOverrides(opts.prompt ?? []);
32743
- for (const err of promptErrors) {
32744
- process.stderr.write(`Error: ${err}
32745
- `);
32746
- process.exit(1);
32747
- }
32748
- let compositionPrompt;
32749
- const compositionOverride = promptOverrides.get("composition");
32750
- if (compositionOverride) {
32751
- try {
32752
- compositionPrompt = await resolvePromptOverride(compositionOverride);
32753
- } catch (e) {
32754
- process.stderr.write(`Error: ${e instanceof Error ? e.message : String(e)}
32755
- `);
32756
- process.exit(1);
32757
- }
32758
- }
32759
31524
  {
32760
31525
  const emitCompositionProgress = (phase) => {
32761
31526
  if (!process.stdout.isTTY) process.stderr.write(`progress=composition:${phase}
@@ -32763,62 +31528,18 @@ function registerInternalExtractCommand(program) {
32763
31528
  };
32764
31529
  emitCompositionProgress("resolving");
32765
31530
  const allFiles = await readCandidateFiles(validatedComponents, sourceFiles);
32766
- const selectedCandidates = selectCandidateFiles(allFiles).map((c2) => ({ path: c2.path, content: c2.content }));
32767
- const capped = capCandidatesToPromptBudget(selectedCandidates);
32768
- const promptFiles = capped.kept;
32769
- if (capped.dropped.length > 0) {
32770
- process.stderr.write(
32771
- `Warning: composition \u2014 ${capped.dropped.length} candidate file(s) omitted from the agent prompt to fit the context budget; resolution runs on the ${promptFiles.length} highest-value files.
32772
- `
32773
- );
32774
- }
32775
31531
  const runtimeFiles = allFiles.map((c2) => ({ path: c2.path, content: c2.content }));
32776
- const resolverAgent = resolveCompositionAgentName(opts.agent);
32777
31532
  const componentNameSet = new Set(validatedComponents.map((c2) => c2.name));
32778
- const cacheVersion = await getCliCacheVersion();
32779
- let lastAgentExitCode = 0;
32780
- const spawnAgent = async (prompt) => {
32781
- const res = await runAgent({
32782
- agent: resolverAgent,
32783
- prompt,
32784
- timeoutMs: 12e4,
32785
- promptViaStdin: true,
32786
- onDebugEvent: (name, payload) => getDebugLogger().event("agent", name, payload)
32787
- });
32788
- lastAgentExitCode = res.exitCode;
32789
- if (res.exitCode !== 0 && res.stderr.trim()) {
32790
- process.stderr.write(`Warning: composition \u2014 agent exited ${res.exitCode}: ${res.stderr.trim()}
32791
- `);
32792
- }
32793
- return res.stdout;
32794
- };
32795
31533
  const manifestDocEdges = collectManifestDocEdges(runtimeFiles, validatedComponents, componentNameSet);
32796
31534
  const extraEdges = manifestDocEdges;
32797
- const agentCacheKey = buildCompositionInputHash({
32798
- files: promptFiles,
32799
- agent: resolverAgent
32800
- });
32801
- const result = await resolveMapping({
31535
+ const sourceCallSites = collectSourceCallSiteEvidence(runtimeFiles, validatedComponents);
31536
+ sourceCallSiteEvidence = sourceCallSites.accepted;
31537
+ sourceCallSiteRejections = sourceCallSites.rejected;
31538
+ const result = resolveMapping({
32802
31539
  components: validatedComponents,
32803
31540
  ...extraEdges.length > 0 ? { extraEdges } : {},
32804
- forceAgent: sources.forceAgent,
32805
- files: promptFiles,
32806
- ...compositionPrompt ? { promptOverride: compositionPrompt } : {},
32807
- runAgentFn: async ({ prompt }) => {
32808
- if (!noCache && !opts.compositionRefresh) {
32809
- const cached = lookupCompositionCache(db, agentCacheKey, cacheVersion);
32810
- if (cached !== null) {
32811
- emitCompositionProgress("cache-hit");
32812
- return cached;
32813
- }
32814
- }
32815
- emitCompositionProgress(`agent:${resolverAgent}`);
32816
- const stdout = await spawnAgent(prompt);
32817
- if (lastAgentExitCode === 0) {
32818
- storeCompositionCache(db, agentCacheKey, cacheVersion, stdout);
32819
- }
32820
- return stdout;
32821
- }
31541
+ sourceCallSiteEvidence,
31542
+ sourceCallSiteRejections
32822
31543
  });
32823
31544
  emitCompositionProgress("done");
32824
31545
  for (const w of result.warnings) process.stderr.write(`Warning: composition \u2014 ${w}
@@ -32848,7 +31569,13 @@ function registerInternalExtractCommand(program) {
32848
31569
  sessionId2,
32849
31570
  sourceFiles.map((f) => relative2(projectRoot, f))
32850
31571
  );
32851
- await retryDatabaseWrite(() => updateStep(db, stepId, "complete", { sessionId: sessionId2 }));
31572
+ await retryDatabaseWrite(
31573
+ () => updateStep(db, stepId, "complete", {
31574
+ sessionId: sessionId2,
31575
+ compositionEvidence: JSON.stringify(sourceCallSiteEvidence),
31576
+ compositionRejections: JSON.stringify(sourceCallSiteRejections)
31577
+ })
31578
+ );
32852
31579
  enrichCommandResult({ extracted_component_count: validatedComponents.length });
32853
31580
  db.close();
32854
31581
  const allWarnings = [...extraction.warnings, ...filterWarnings];
@@ -32870,18 +31597,12 @@ var SCANNED_FILE_EXTENSIONS, DENYLIST_GATED_EXTENSIONS, DENYLISTED_EXACT_FILE_NA
32870
31597
  var init_extract_command = __esm({
32871
31598
  "packages/experience-design-system-cli-legacy/src/analyze/extract-command.ts"() {
32872
31599
  "use strict";
32873
- init_agent_model_options();
32874
31600
  init_src2();
32875
31601
  init_db();
32876
- init_cache_keys();
32877
31602
  init_cycle_detection();
32878
31603
  init_resolve_mapping();
32879
- init_resolve_mapping_cli();
32880
- init_candidate_files();
32881
- init_composition_cache_key();
32882
31604
  init_manifest_doc_evidence();
32883
- init_prompt_overrides();
32884
- init_src();
31605
+ init_source_call_site_evidence();
32885
31606
  init_analytics();
32886
31607
  init_debug_logger();
32887
31608
  SCANNED_FILE_EXTENSIONS = /* @__PURE__ */ new Set([".astro", ".js", ".jsx", ".svelte", ".ts", ".tsx", ".vue"]);
@@ -32975,9 +31696,9 @@ __export(program_exports, {
32975
31696
  runBuild: () => runBuild
32976
31697
  });
32977
31698
  import { spawn as spawn7 } from "node:child_process";
32978
- import { fileURLToPath as fileURLToPath4 } from "node:url";
32979
- import { dirname as dirname19, join as join29, resolve as resolve21 } from "node:path";
32980
- import { readFileSync as readFileSync11 } from "node:fs";
31699
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
31700
+ import { dirname as dirname18, join as join28, resolve as resolve19 } from "node:path";
31701
+ import { readFileSync as readFileSync10 } from "node:fs";
32981
31702
  import { Command } from "commander";
32982
31703
  async function runBuild(opts) {
32983
31704
  return new Promise((resolvePromise) => {
@@ -33006,7 +31727,7 @@ function resolveBedrockFromAncestors(actionCommand) {
33006
31727
  }
33007
31728
  function registerBuildCommand(program) {
33008
31729
  program.command("build").description("Rebuild from source and re-link exo/experiences binaries to this build").helpOption(false).action(async () => {
33009
- const pkgRoot = resolve21(dirname19(fileURLToPath4(import.meta.url)), "..", "..");
31730
+ const pkgRoot = resolve19(dirname18(fileURLToPath3(import.meta.url)), "..", "..");
33010
31731
  process.stderr.write("\u2699 Building from source...\n");
33011
31732
  const { exitCode } = await runBuild({
33012
31733
  spawnFn: () => spawn7("pnpm", ["build"], { cwd: pkgRoot, stdio: "inherit" }),
@@ -33076,7 +31797,7 @@ var init_program = __esm({
33076
31797
  init_analytics();
33077
31798
  init_credentials_store();
33078
31799
  init_cli_path();
33079
- pkg3 = JSON.parse(readFileSync11(join29(findPkgRoot(), "package.json"), "utf8"));
31800
+ pkg3 = JSON.parse(readFileSync10(join28(findPkgRoot(), "package.json"), "utf8"));
33080
31801
  }
33081
31802
  });
33082
31803