@contentful/experience-design-system-cli 2.35.1-dev-build-925d6206.0 → 2.35.1-dev-build-c518de8c.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.
@@ -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";
@@ -10365,41 +10280,6 @@ var init_read3 = __esm({
10365
10280
  }
10366
10281
  });
10367
10282
 
10368
- // packages/experience-design-system-cli-legacy/src/session/core/components/hash-component-shape.ts
10369
- import { createHash as createHash2 } from "node:crypto";
10370
- function hashComponentShape(component) {
10371
- const payload = {
10372
- framework: component.framework,
10373
- name: component.name,
10374
- source: component.source,
10375
- props: component.props.map((p) => ({
10376
- name: p.name,
10377
- type: p.type
10378
- })),
10379
- slots: component.slots.map((s) => ({
10380
- name: s.name,
10381
- isDefault: s.isDefault
10382
- }))
10383
- };
10384
- return createHash2("sha256").update(JSON.stringify(payload)).digest("hex");
10385
- }
10386
- var init_hash_component_shape = __esm({
10387
- "packages/experience-design-system-cli-legacy/src/session/core/components/hash-component-shape.ts"() {
10388
- "use strict";
10389
- }
10390
- });
10391
-
10392
- // packages/experience-design-system-cli-legacy/src/session/core/tokens/hash-token-content.ts
10393
- import { createHash as createHash3 } from "node:crypto";
10394
- function hashTokenContent(rawTokenContent) {
10395
- return createHash3("sha256").update(rawTokenContent.trim()).digest("hex");
10396
- }
10397
- var init_hash_token_content = __esm({
10398
- "packages/experience-design-system-cli-legacy/src/session/core/tokens/hash-token-content.ts"() {
10399
- "use strict";
10400
- }
10401
- });
10402
-
10403
10283
  // packages/experience-design-system-cli-legacy/src/session/repositories/tokens/write.ts
10404
10284
  function deleteRawTokensForSession(db, sessionId2) {
10405
10285
  db.prepare("DELETE FROM raw_token_groups WHERE session_id = ?").run(sessionId2);
@@ -10563,47 +10443,17 @@ var init_replace_raw_prop_token_paths = __esm({
10563
10443
  }
10564
10444
  });
10565
10445
 
10566
- // packages/experience-design-system-cli-legacy/src/session/cache-keys.ts
10567
- var cache_keys_exports = {};
10568
- __export(cache_keys_exports, {
10569
- hashContent: () => hashContent,
10570
- hashFile: () => hashFile,
10571
- hashPromptForSkill: () => hashPromptForSkill
10572
- });
10573
- import { createHash as createHash4 } from "node:crypto";
10574
- import { readFile as readFile7 } from "node:fs/promises";
10575
- import { resolve as resolve8 } from "node:path";
10576
- function hashContent(content) {
10577
- return createHash4("sha256").update(content).digest("hex");
10578
- }
10579
- async function hashFile(filePath) {
10580
- const content = await readFile7(filePath, "utf8");
10581
- return hashContent(content);
10582
- }
10583
- async function hashPromptForSkill(skill, agent, model, skillPathOverride, extraInputs = [], skillContentOverride) {
10584
- const promptHash = skillContentOverride ? hashContent(skillContentOverride) : skillPathOverride ? await hashFile(resolve8(skillPathOverride)) : await hashFile(resolveSkillPath(skill));
10585
- const extraSegment = extraInputs.length > 0 ? `|${extraInputs.join("|")}` : "";
10586
- return hashContent(`${promptHash}|${agent}|${model ?? ""}${extraSegment}`);
10587
- }
10588
- var init_cache_keys = __esm({
10589
- "packages/experience-design-system-cli-legacy/src/session/cache-keys.ts"() {
10590
- "use strict";
10591
- init_src();
10592
- }
10593
- });
10594
-
10595
10446
  // packages/experience-design-system-cli-legacy/src/session/db.ts
10596
10447
  import { DatabaseSync } from "node:sqlite";
10597
10448
  import { mkdirSync as mkdirSync2, readFileSync as readFileSync5 } from "node:fs";
10598
- import { readFile as readFile8 } from "node:fs/promises";
10599
- import { createHash as createHash5 } from "node:crypto";
10449
+ import { readFile as readFile7 } from "node:fs/promises";
10600
10450
  import { homedir as homedir3 } from "node:os";
10601
- import { dirname as dirname14, resolve as resolve9 } from "node:path";
10451
+ import { dirname as dirname14, resolve as resolve8 } from "node:path";
10602
10452
  function getPipelineDbPath() {
10603
10453
  if (process.env.EDS_PIPELINE_DB_PATH) {
10604
- return resolve9(process.env.EDS_PIPELINE_DB_PATH);
10454
+ return resolve8(process.env.EDS_PIPELINE_DB_PATH);
10605
10455
  }
10606
- return resolve9(homedir3(), ".contentful", "experience-design-system-cli", "pipeline.db");
10456
+ return resolve8(homedir3(), ".contentful", "experience-design-system-cli", "pipeline.db");
10607
10457
  }
10608
10458
  function openPipelineDb(dbPath) {
10609
10459
  const path = dbPath ?? getPipelineDbPath();
@@ -10737,134 +10587,8 @@ function applyDbMigrations(db) {
10737
10587
  if (!rawSlotColsForRationale.some((c2) => c2.name === "rationale")) {
10738
10588
  db.exec("ALTER TABLE raw_slots ADD COLUMN rationale TEXT");
10739
10589
  }
10740
- const hasExtractCache = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='extract_cache'`).all();
10741
- if (hasExtractCache.length === 0) {
10742
- db.exec(`
10743
- CREATE TABLE extract_cache (
10744
- file_path TEXT NOT NULL,
10745
- file_hash TEXT NOT NULL,
10746
- cli_version TEXT NOT NULL,
10747
- created_at TEXT NOT NULL,
10748
- updated_at TEXT NOT NULL,
10749
- components_json TEXT NOT NULL,
10750
- PRIMARY KEY (file_hash, cli_version)
10751
- );
10752
- CREATE INDEX idx_extract_cache_file ON extract_cache(file_path);
10753
- `);
10754
- }
10755
- const hasSelectCache = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='select_cache'`).all();
10756
- if (hasSelectCache.length === 0) {
10757
- db.exec(`
10758
- CREATE TABLE select_cache (
10759
- component_hash TEXT NOT NULL,
10760
- prompt_hash TEXT NOT NULL,
10761
- cli_version TEXT NOT NULL,
10762
- decision TEXT NOT NULL CHECK (decision IN ('accepted','rejected')),
10763
- reason TEXT,
10764
- created_at TEXT NOT NULL,
10765
- updated_at TEXT NOT NULL,
10766
- PRIMARY KEY (component_hash, prompt_hash, cli_version)
10767
- );
10768
- `);
10769
- }
10770
- const tables = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='generation_cache'`).all();
10771
- if (tables.length === 0) {
10772
- db.exec(`
10773
- CREATE TABLE generation_cache (
10774
- input_hash TEXT NOT NULL,
10775
- entity_type TEXT NOT NULL CHECK (entity_type IN ('component', 'token_set', 'token_mapping')),
10776
- entity_id TEXT NOT NULL,
10777
- source_session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
10778
- human_edited INTEGER NOT NULL DEFAULT 0 CHECK (human_edited IN (0, 1)),
10779
- created_at TEXT NOT NULL,
10780
- updated_at TEXT NOT NULL,
10781
- PRIMARY KEY (input_hash, entity_type, entity_id)
10782
- );
10783
- CREATE INDEX idx_generation_cache_entity ON generation_cache(entity_type, entity_id);
10784
- CREATE INDEX idx_generation_cache_session ON generation_cache(source_session_id);
10785
- `);
10786
- }
10787
- const genCacheCols = db.prepare(`PRAGMA table_info(generation_cache)`).all();
10788
- const hasPromptHash = genCacheCols.some((c2) => c2.name === "prompt_hash");
10789
- const oldPkCols = genCacheCols.filter((c2) => c2.pk > 0).map((c2) => c2.name);
10790
- const promptHashInPk = oldPkCols.includes("prompt_hash");
10791
- if (!hasPromptHash) {
10792
- db.exec(`ALTER TABLE generation_cache ADD COLUMN prompt_hash TEXT NOT NULL DEFAULT ''`);
10793
- }
10794
- if (!promptHashInPk) {
10795
- db.exec("BEGIN");
10796
- try {
10797
- db.exec(`
10798
- CREATE TABLE generation_cache__new (
10799
- input_hash TEXT NOT NULL,
10800
- entity_type TEXT NOT NULL CHECK (entity_type IN ('component', 'token_set', 'token_mapping')),
10801
- entity_id TEXT NOT NULL,
10802
- source_session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
10803
- human_edited INTEGER NOT NULL DEFAULT 0 CHECK (human_edited IN (0, 1)),
10804
- created_at TEXT NOT NULL,
10805
- updated_at TEXT NOT NULL,
10806
- prompt_hash TEXT NOT NULL DEFAULT '',
10807
- PRIMARY KEY (input_hash, prompt_hash, entity_type, entity_id)
10808
- );
10809
- INSERT INTO generation_cache__new
10810
- (input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash)
10811
- SELECT input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash
10812
- FROM generation_cache;
10813
- DROP TABLE generation_cache;
10814
- ALTER TABLE generation_cache__new RENAME TO generation_cache;
10815
- CREATE INDEX IF NOT EXISTS idx_generation_cache_entity ON generation_cache(entity_type, entity_id);
10816
- CREATE INDEX IF NOT EXISTS idx_generation_cache_session ON generation_cache(source_session_id);
10817
- `);
10818
- db.exec("COMMIT");
10819
- } catch (e) {
10820
- db.exec("ROLLBACK");
10821
- throw e;
10822
- }
10823
- }
10824
- const genCacheTableSql = db.prepare(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'generation_cache'`).get();
10825
- const hasTokenMappingEntityType = genCacheTableSql?.sql.includes("'token_mapping'") ?? true;
10826
- if (!hasTokenMappingEntityType) {
10827
- db.exec("BEGIN");
10828
- try {
10829
- db.exec(`
10830
- CREATE TABLE generation_cache__new2 (
10831
- input_hash TEXT NOT NULL,
10832
- entity_type TEXT NOT NULL CHECK (entity_type IN ('component', 'token_set', 'token_mapping')),
10833
- entity_id TEXT NOT NULL,
10834
- source_session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
10835
- human_edited INTEGER NOT NULL DEFAULT 0 CHECK (human_edited IN (0, 1)),
10836
- created_at TEXT NOT NULL,
10837
- updated_at TEXT NOT NULL,
10838
- prompt_hash TEXT NOT NULL DEFAULT '',
10839
- PRIMARY KEY (input_hash, prompt_hash, entity_type, entity_id)
10840
- );
10841
- INSERT INTO generation_cache__new2
10842
- (input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash)
10843
- SELECT input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash
10844
- FROM generation_cache;
10845
- DROP TABLE generation_cache;
10846
- ALTER TABLE generation_cache__new2 RENAME TO generation_cache;
10847
- CREATE INDEX IF NOT EXISTS idx_generation_cache_entity ON generation_cache(entity_type, entity_id);
10848
- CREATE INDEX IF NOT EXISTS idx_generation_cache_session ON generation_cache(source_session_id);
10849
- `);
10850
- db.exec("COMMIT");
10851
- } catch (e) {
10852
- db.exec("ROLLBACK");
10853
- throw e;
10854
- }
10855
- }
10856
- const hasCompositionCache = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name='composition_cache'`).all();
10857
- if (hasCompositionCache.length === 0) {
10858
- db.exec(`
10859
- CREATE TABLE composition_cache (
10860
- input_hash TEXT NOT NULL,
10861
- cli_version TEXT NOT NULL,
10862
- agent_output TEXT NOT NULL,
10863
- created_at TEXT NOT NULL,
10864
- updated_at TEXT NOT NULL,
10865
- PRIMARY KEY (input_hash, cli_version)
10866
- );
10867
- `);
10590
+ for (const table of REMOVED_CACHE_TABLES) {
10591
+ db.exec(`DROP TABLE IF EXISTS ${table}`);
10868
10592
  }
10869
10593
  }
10870
10594
  function loadComponentReviewMetadata(db, sessionId2, componentName) {
@@ -11404,16 +11128,16 @@ function extractRelativeImportPaths(sourceText) {
11404
11128
  return [...specifiers];
11405
11129
  }
11406
11130
  async function resolveRelativeImport(specifier, fromDir) {
11407
- const basePath = resolve9(fromDir, specifier);
11131
+ const basePath = resolve8(fromDir, specifier);
11408
11132
  const candidates = [
11409
11133
  basePath,
11410
11134
  ...rewrittenSourcePaths(basePath),
11411
11135
  ...SIBLING_FILE_EXTENSIONS.map((ext) => `${basePath}${ext}`),
11412
- ...SIBLING_FILE_EXTENSIONS.map((ext) => resolve9(basePath, `index${ext}`))
11136
+ ...SIBLING_FILE_EXTENSIONS.map((ext) => resolve8(basePath, `index${ext}`))
11413
11137
  ];
11414
11138
  for (const candidate of candidates) {
11415
11139
  try {
11416
- await readFile8(candidate, "utf8");
11140
+ await readFile7(candidate, "utf8");
11417
11141
  return candidate;
11418
11142
  } catch {
11419
11143
  }
@@ -11429,7 +11153,7 @@ async function resolveImportSpecifiers(sourceText, fromDir) {
11429
11153
  return resolvedPaths;
11430
11154
  }
11431
11155
  async function loadSiblingFiles(sourceText, sourcePath, propNames, candidateTypeNames = []) {
11432
- const visited = /* @__PURE__ */ new Set([resolve9(sourcePath)]);
11156
+ const visited = /* @__PURE__ */ new Set([resolve8(sourcePath)]);
11433
11157
  const discovered = [];
11434
11158
  let frontier = [{ text: sourceText, dir: dirname14(sourcePath) }];
11435
11159
  for (let hop = 0; hop < MAX_SIBLING_DEPTH && discovered.length < MAX_SIBLING_CANDIDATES_EXPLORED; hop++) {
@@ -11443,7 +11167,7 @@ async function loadSiblingFiles(sourceText, sourcePath, propNames, candidateType
11443
11167
  if (discovered.length >= MAX_SIBLING_CANDIDATES_EXPLORED) break;
11444
11168
  let content;
11445
11169
  try {
11446
- content = await readFile8(resolvedPath, "utf8");
11170
+ content = await readFile7(resolvedPath, "utf8");
11447
11171
  } catch {
11448
11172
  continue;
11449
11173
  }
@@ -11480,7 +11204,7 @@ async function loadComponentSourceRef(name, sourcePath, propNames = [], propType
11480
11204
  let truncatedSiblingCount = 0;
11481
11205
  const usesNotShown = /* @__PURE__ */ new Set();
11482
11206
  try {
11483
- const rawText = await readFile8(sourcePath, "utf8");
11207
+ const rawText = await readFile7(sourcePath, "utf8");
11484
11208
  let siblingUsesNotShown;
11485
11209
  let declaredTypeNames;
11486
11210
  ({
@@ -11916,108 +11640,6 @@ function backfillUnclassifiedProps(db, sessionId2) {
11916
11640
  ).run(sessionId2, sessionId2);
11917
11641
  return Number(withCategory.changes) + Number(withoutCategory.changes);
11918
11642
  }
11919
- function computeMapTokensInputHash(db, sessionId2, componentSourceRefs = []) {
11920
- const props = db.prepare(
11921
- `SELECT rc.name AS component_name, rp.name AS prop_name, rp.cdf_token_kind, rp.default_value
11922
- FROM raw_props rp
11923
- JOIN raw_components rc ON rc.session_id = rp.session_id AND rc.component_id = rp.component_id
11924
- WHERE rp.session_id = ? AND rp.cdf_type = 'token' AND rp.cdf_category = 'design'
11925
- ORDER BY rc.name, rp.name`
11926
- ).all(sessionId2);
11927
- const tokens = db.prepare(`SELECT path, type FROM raw_tokens WHERE session_id = ? ORDER BY path`).all(sessionId2);
11928
- const defaultMappings = db.prepare("SELECT raw_name, path, source FROM raw_token_name_paths WHERE session_id = ? ORDER BY raw_name").all(sessionId2);
11929
- const payload = {
11930
- props: props.map((p) => ({
11931
- component: p.component_name,
11932
- prop: p.prop_name,
11933
- tokenKind: p.cdf_token_kind,
11934
- rawDefault: p.default_value
11935
- })),
11936
- tokens,
11937
- defaultMappings,
11938
- // The agent's evidence, not just its inputs: a comment or allowlist edit
11939
- // in a source file (or a sibling it reads) changes the correct answer
11940
- // without touching props or tokens, so it must invalidate the cache too.
11941
- sourceRefs: [...componentSourceRefs].sort((a, b) => a.component.localeCompare(b.component)).map((ref) => ({
11942
- component: ref.component,
11943
- content: ref.content,
11944
- siblingFiles: (ref.siblingFiles ?? []).map((s) => ({ path: s.path, content: s.content })).sort((a, b) => a.path.localeCompare(b.path)),
11945
- usesNotShown: [...ref.usesNotShown ?? []].sort()
11946
- }))
11947
- };
11948
- return createHash5("sha256").update(JSON.stringify(payload)).digest("hex");
11949
- }
11950
- function lookupCache(db, inputHash, entityType, entityId, promptHash = "") {
11951
- const row = db.prepare(
11952
- `SELECT input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash
11953
- FROM generation_cache
11954
- WHERE input_hash = ? AND entity_type = ? AND entity_id = ? AND prompt_hash = ?`
11955
- ).get(inputHash, entityType, entityId, promptHash);
11956
- if (!row) return null;
11957
- return {
11958
- inputHash: row.input_hash,
11959
- entityType: row.entity_type,
11960
- entityId: row.entity_id,
11961
- sourceSessionId: row.source_session_id,
11962
- humanEdited: row.human_edited === 1,
11963
- promptHash: row.prompt_hash,
11964
- createdAt: row.created_at,
11965
- updatedAt: row.updated_at
11966
- };
11967
- }
11968
- function lookupCacheByEntity(db, entityType, entityId) {
11969
- const row = db.prepare(
11970
- `SELECT input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash
11971
- FROM generation_cache
11972
- WHERE entity_type = ? AND entity_id = ?
11973
- ORDER BY updated_at DESC LIMIT 1`
11974
- ).get(entityType, entityId);
11975
- if (!row) return null;
11976
- return {
11977
- inputHash: row.input_hash,
11978
- entityType: row.entity_type,
11979
- entityId: row.entity_id,
11980
- sourceSessionId: row.source_session_id,
11981
- humanEdited: row.human_edited === 1,
11982
- promptHash: row.prompt_hash,
11983
- createdAt: row.created_at,
11984
- updatedAt: row.updated_at
11985
- };
11986
- }
11987
- function storeCache(db, inputHash, entityType, entityId, sourceSessionId, humanEdited, promptHash = "") {
11988
- storeCaches(db, [{ inputHash, entityType, entityId, sourceSessionId, humanEdited, promptHash }]);
11989
- }
11990
- function storeCaches(db, entries) {
11991
- if (entries.length === 0) return;
11992
- const now = (/* @__PURE__ */ new Date()).toISOString();
11993
- const insert = db.prepare(
11994
- `INSERT INTO generation_cache (input_hash, entity_type, entity_id, source_session_id, human_edited, created_at, updated_at, prompt_hash)
11995
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
11996
- ON CONFLICT(input_hash, prompt_hash, entity_type, entity_id) DO UPDATE SET
11997
- source_session_id = excluded.source_session_id,
11998
- human_edited = CASE WHEN generation_cache.human_edited = 1 THEN 1 ELSE excluded.human_edited END,
11999
- updated_at = excluded.updated_at`
12000
- );
12001
- db.exec("BEGIN");
12002
- try {
12003
- for (const entry of entries) {
12004
- insert.run(
12005
- entry.inputHash,
12006
- entry.entityType,
12007
- entry.entityId,
12008
- entry.sourceSessionId,
12009
- entry.humanEdited ? 1 : 0,
12010
- now,
12011
- now,
12012
- entry.promptHash ?? ""
12013
- );
12014
- }
12015
- db.exec("COMMIT");
12016
- } catch (e) {
12017
- db.exec("ROLLBACK");
12018
- throw e;
12019
- }
12020
- }
12021
11643
  function storeScannedFiles(db, sessionId2, filePaths) {
12022
11644
  db.exec("BEGIN");
12023
11645
  try {
@@ -12100,105 +11722,7 @@ function filterUnknownSlotAllowedComponents(db, sessionId2, allowedComponentName
12100
11722
  }
12101
11723
  return unknown;
12102
11724
  }
12103
- function copyComponentFromCache(db, sourceSessionId, targetSessionId, componentId, manageTransaction = true, options = {}) {
12104
- const now = (/* @__PURE__ */ new Date()).toISOString();
12105
- if (manageTransaction) db.exec("BEGIN");
12106
- try {
12107
- const srcComp = db.prepare(
12108
- `SELECT description, status, component_description_rationale, props_rationale, slots_rationale
12109
- FROM raw_components WHERE session_id = ? AND component_id = ?`
12110
- ).get(sourceSessionId, componentId);
12111
- if (srcComp) {
12112
- db.prepare(
12113
- `UPDATE raw_components
12114
- SET description = ?, status = ?, component_description_rationale = ?, props_rationale = ?, slots_rationale = ?, extracted_at = ?
12115
- WHERE session_id = ? AND component_id = ?`
12116
- ).run(
12117
- srcComp.description,
12118
- srcComp.status,
12119
- srcComp.component_description_rationale,
12120
- srcComp.props_rationale,
12121
- srcComp.slots_rationale,
12122
- now,
12123
- targetSessionId,
12124
- componentId
12125
- );
12126
- }
12127
- const srcProps = db.prepare(
12128
- `SELECT name, cdf_type, cdf_category, cdf_token_kind, required, description, default_value, rationale
12129
- FROM raw_props WHERE session_id = ? AND component_id = ?`
12130
- ).all(sourceSessionId, componentId);
12131
- for (const p of srcProps) {
12132
- db.prepare(
12133
- `UPDATE raw_props SET cdf_type = ?, cdf_category = ?, cdf_token_kind = ?, required = ?, description = ?, default_value = ?, rationale = ?
12134
- WHERE session_id = ? AND component_id = ? AND name = ?`
12135
- ).run(
12136
- p.cdf_type,
12137
- p.cdf_category,
12138
- p.cdf_token_kind,
12139
- p.required,
12140
- p.description,
12141
- p.default_value,
12142
- p.rationale,
12143
- targetSessionId,
12144
- componentId,
12145
- p.name
12146
- );
12147
- }
12148
- db.prepare(`DELETE FROM raw_prop_allowed_values WHERE session_id = ? AND component_id = ?`).run(
12149
- targetSessionId,
12150
- componentId
12151
- );
12152
- const srcAV = db.prepare(
12153
- `SELECT prop_name, position, value FROM raw_prop_allowed_values WHERE session_id = ? AND component_id = ?`
12154
- ).all(sourceSessionId, componentId);
12155
- const insertAV = db.prepare(
12156
- `INSERT INTO raw_prop_allowed_values (session_id, component_id, prop_name, position, value) VALUES (?, ?, ?, ?, ?)`
12157
- );
12158
- for (const av of srcAV) {
12159
- insertAV.run(targetSessionId, componentId, av.prop_name, av.position, av.value);
12160
- }
12161
- const srcSlots = db.prepare(`SELECT name, required, description, rationale FROM raw_slots WHERE session_id = ? AND component_id = ?`).all(sourceSessionId, componentId);
12162
- for (const s of srcSlots) {
12163
- db.prepare(
12164
- `UPDATE raw_slots SET required = ?, description = ?, rationale = ? WHERE session_id = ? AND component_id = ? AND name = ?`
12165
- ).run(s.required, s.description, s.rationale, targetSessionId, componentId, s.name);
12166
- }
12167
- db.prepare(`DELETE FROM raw_slot_allowed_components WHERE session_id = ? AND component_id = ?`).run(
12168
- targetSessionId,
12169
- componentId
12170
- );
12171
- const srcSAC = db.prepare(
12172
- `SELECT slot_name, position, allowed_component FROM raw_slot_allowed_components WHERE session_id = ? AND component_id = ?`
12173
- ).all(sourceSessionId, componentId);
12174
- const insertSAC = db.prepare(
12175
- `INSERT INTO raw_slot_allowed_components (session_id, component_id, slot_name, allowed_component, position) VALUES (?, ?, ?, ?, ?)`
12176
- );
12177
- const allowedSAC = options.allowedComponentNames ? srcSAC.filter((sac) => options.allowedComponentNames.has(sac.allowed_component)) : srcSAC;
12178
- for (const sac of allowedSAC) {
12179
- insertSAC.run(targetSessionId, componentId, sac.slot_name, sac.allowed_component, sac.position);
12180
- }
12181
- db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, targetSessionId);
12182
- if (manageTransaction) db.exec("COMMIT");
12183
- } catch (e) {
12184
- if (manageTransaction) db.exec("ROLLBACK");
12185
- throw e;
12186
- }
12187
- }
12188
- function copyComponentsFromCache(db, entries, options = {}) {
12189
- if (entries.length === 0) return;
12190
- db.exec("BEGIN");
12191
- try {
12192
- for (const entry of entries) {
12193
- copyComponentFromCache(db, entry.sourceSessionId, entry.targetSessionId, entry.componentId, false, options);
12194
- }
12195
- db.exec("COMMIT");
12196
- } catch (e) {
12197
- db.exec("ROLLBACK");
12198
- throw e;
12199
- }
12200
- }
12201
- function copyTokensFromCache(db, sourceSessionId, targetSessionId) {
11725
+ function copyTokensBetweenSessions(db, sourceSessionId, targetSessionId) {
12202
11726
  const now = (/* @__PURE__ */ new Date()).toISOString();
12203
11727
  db.exec("BEGIN");
12204
11728
  try {
@@ -12219,153 +11743,7 @@ function copyTokensFromCache(db, sourceSessionId, targetSessionId) {
12219
11743
  throw e;
12220
11744
  }
12221
11745
  }
12222
- function copyMapTokensFromCache(db, sourceSessionId, targetSessionId) {
12223
- const now = (/* @__PURE__ */ new Date()).toISOString();
12224
- let copiedCount = 0;
12225
- db.exec("BEGIN");
12226
- try {
12227
- const sourceRows = db.prepare(
12228
- `SELECT rc.name AS component_name, rptp.prop_name, rptp.source, rptp.position, rptp.path
12229
- FROM raw_prop_token_paths rptp
12230
- JOIN raw_components rc ON rc.session_id = rptp.session_id AND rc.component_id = rptp.component_id
12231
- WHERE rptp.session_id = ?
12232
- ORDER BY rc.name, rptp.prop_name, rptp.position`
12233
- ).all(sourceSessionId);
12234
- const targetComponents = db.prepare(`SELECT component_id, name FROM raw_components WHERE session_id = ?`).all(targetSessionId);
12235
- const targetIdByName = new Map(targetComponents.map((c2) => [c2.name, c2.component_id]));
12236
- const targetProps = new Set(
12237
- db.prepare(`SELECT component_id, name FROM raw_props WHERE session_id = ?`).all(targetSessionId).map((p) => `${p.component_id}::${p.name}`)
12238
- );
12239
- const insertPath = db.prepare(
12240
- `INSERT INTO raw_prop_token_paths (session_id, component_id, prop_name, source, position, path)
12241
- VALUES (?, ?, ?, ?, ?, ?)`
12242
- );
12243
- const clearedProps = /* @__PURE__ */ new Set();
12244
- const copiedProps = /* @__PURE__ */ new Set();
12245
- for (const row of sourceRows) {
12246
- const targetComponentId = targetIdByName.get(row.component_name);
12247
- if (!targetComponentId) continue;
12248
- if (!targetProps.has(`${targetComponentId}::${row.prop_name}`)) continue;
12249
- const propKey = `${targetComponentId}::${row.prop_name}`;
12250
- if (!clearedProps.has(propKey)) {
12251
- clearedProps.add(propKey);
12252
- db.prepare(`DELETE FROM raw_prop_token_paths WHERE session_id = ? AND component_id = ? AND prop_name = ?`).run(
12253
- targetSessionId,
12254
- targetComponentId,
12255
- row.prop_name
12256
- );
12257
- }
12258
- insertPath.run(targetSessionId, targetComponentId, row.prop_name, row.source, row.position, row.path);
12259
- copiedProps.add(propKey);
12260
- }
12261
- copiedCount = copiedProps.size;
12262
- db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, targetSessionId);
12263
- db.exec("COMMIT");
12264
- } catch (e) {
12265
- db.exec("ROLLBACK");
12266
- throw e;
12267
- }
12268
- return copiedCount;
12269
- }
12270
- async function getCliCacheVersion() {
12271
- if (_cliCacheVersionCache) return _cliCacheVersionCache;
12272
- try {
12273
- const { hashContent: hashContent2 } = await Promise.resolve().then(() => (init_cache_keys(), cache_keys_exports));
12274
- const { resolveSkillPath: resolveSkillPath2 } = await Promise.resolve().then(() => (init_src(), src_exports));
12275
- const skills = ["components", "tokens", "select"];
12276
- const parts = [];
12277
- for (const s of skills) {
12278
- try {
12279
- const p = resolveSkillPath2(s);
12280
- parts.push(readFileSync5(p, "utf8"));
12281
- } catch {
12282
- parts.push(`<missing:${s}>`);
12283
- }
12284
- }
12285
- _cliCacheVersionCache = hashContent2(parts.join("\n---\n"));
12286
- return _cliCacheVersionCache;
12287
- } catch {
12288
- _cliCacheVersionCache = "fallback";
12289
- return _cliCacheVersionCache;
12290
- }
12291
- }
12292
- function storeExtractCache(db, filePath, fileHash, cliVersion2, components) {
12293
- const now = (/* @__PURE__ */ new Date()).toISOString();
12294
- const componentsJson = JSON.stringify(components);
12295
- db.prepare(
12296
- `INSERT INTO extract_cache (file_path, file_hash, cli_version, created_at, updated_at, components_json)
12297
- VALUES (?, ?, ?, ?, ?, ?)
12298
- ON CONFLICT(file_hash, cli_version) DO UPDATE SET
12299
- file_path = excluded.file_path,
12300
- updated_at = excluded.updated_at,
12301
- components_json = excluded.components_json`
12302
- ).run(filePath, fileHash, cliVersion2, now, now, componentsJson);
12303
- }
12304
- function lookupExtractCache(db, fileHash, cliVersion2) {
12305
- const row = db.prepare(
12306
- `SELECT file_path, file_hash, cli_version, created_at, updated_at, components_json
12307
- FROM extract_cache
12308
- WHERE file_hash = ? AND cli_version = ?`
12309
- ).get(fileHash, cliVersion2);
12310
- if (!row) return null;
12311
- let components = [];
12312
- try {
12313
- components = JSON.parse(row.components_json);
12314
- } catch {
12315
- return null;
12316
- }
12317
- return {
12318
- filePath: row.file_path,
12319
- fileHash: row.file_hash,
12320
- cliVersion: row.cli_version,
12321
- createdAt: row.created_at,
12322
- updatedAt: row.updated_at,
12323
- components
12324
- };
12325
- }
12326
- function storeCompositionCache(db, inputHash, cliVersion2, agentOutput) {
12327
- const now = (/* @__PURE__ */ new Date()).toISOString();
12328
- db.prepare(
12329
- `INSERT INTO composition_cache (input_hash, cli_version, agent_output, created_at, updated_at)
12330
- VALUES (?, ?, ?, ?, ?)
12331
- ON CONFLICT(input_hash, cli_version) DO UPDATE SET
12332
- agent_output = excluded.agent_output,
12333
- updated_at = excluded.updated_at`
12334
- ).run(inputHash, cliVersion2, agentOutput, now, now);
12335
- }
12336
- function lookupCompositionCache(db, inputHash, cliVersion2) {
12337
- const row = db.prepare(`SELECT agent_output FROM composition_cache WHERE input_hash = ? AND cli_version = ?`).get(inputHash, cliVersion2);
12338
- return row ? row.agent_output : null;
12339
- }
12340
- function storeSelectCache(db, componentHash, promptHash, cliVersion2, decision, reason) {
12341
- const now = (/* @__PURE__ */ new Date()).toISOString();
12342
- db.prepare(
12343
- `INSERT INTO select_cache (component_hash, prompt_hash, cli_version, decision, reason, created_at, updated_at)
12344
- VALUES (?, ?, ?, ?, ?, ?, ?)
12345
- ON CONFLICT(component_hash, prompt_hash, cli_version) DO UPDATE SET
12346
- decision = excluded.decision,
12347
- reason = excluded.reason,
12348
- updated_at = excluded.updated_at`
12349
- ).run(componentHash, promptHash, cliVersion2, decision, reason, now, now);
12350
- }
12351
- function lookupSelectCache(db, componentHash, promptHash, cliVersion2) {
12352
- const row = db.prepare(
12353
- `SELECT component_hash, prompt_hash, cli_version, decision, reason, created_at, updated_at
12354
- FROM select_cache
12355
- WHERE component_hash = ? AND prompt_hash = ? AND cli_version = ?`
12356
- ).get(componentHash, promptHash, cliVersion2);
12357
- if (!row) return null;
12358
- return {
12359
- componentHash: row.component_hash,
12360
- promptHash: row.prompt_hash,
12361
- cliVersion: row.cli_version,
12362
- decision: row.decision,
12363
- reason: row.reason,
12364
- createdAt: row.created_at,
12365
- updatedAt: row.updated_at
12366
- };
12367
- }
12368
- 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;
11746
+ 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;
12369
11747
  var init_db = __esm({
12370
11748
  "packages/experience-design-system-cli-legacy/src/session/db.ts"() {
12371
11749
  "use strict";
@@ -12379,8 +11757,6 @@ var init_db = __esm({
12379
11757
  init_write2();
12380
11758
  init_session_resolver();
12381
11759
  init_read3();
12382
- init_hash_component_shape();
12383
- init_hash_token_content();
12384
11760
  init_read3();
12385
11761
  init_store_dtcg_tokens();
12386
11762
  init_apply_tool_calls();
@@ -12504,17 +11880,6 @@ CREATE TABLE IF NOT EXISTS raw_tokens (
12504
11880
  FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
12505
11881
  );
12506
11882
 
12507
- CREATE TABLE IF NOT EXISTS generation_cache (
12508
- input_hash TEXT NOT NULL,
12509
- entity_type TEXT NOT NULL CHECK (entity_type IN ('component', 'token_set', 'token_mapping')),
12510
- entity_id TEXT NOT NULL,
12511
- source_session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
12512
- human_edited INTEGER NOT NULL DEFAULT 0 CHECK (human_edited IN (0, 1)),
12513
- created_at TEXT NOT NULL,
12514
- updated_at TEXT NOT NULL,
12515
- PRIMARY KEY (input_hash, entity_type, entity_id)
12516
- );
12517
-
12518
11883
  CREATE TABLE IF NOT EXISTS scanned_files (
12519
11884
  session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
12520
11885
  path TEXT NOT NULL,
@@ -12560,10 +11925,9 @@ CREATE INDEX IF NOT EXISTS idx_raw_props_session ON raw_props(session_id,
12560
11925
  CREATE INDEX IF NOT EXISTS idx_raw_slots_session ON raw_slots(session_id, component_id);
12561
11926
  CREATE INDEX IF NOT EXISTS idx_raw_tokens_session ON raw_tokens(session_id);
12562
11927
  CREATE INDEX IF NOT EXISTS idx_raw_token_groups_session ON raw_token_groups(session_id);
12563
- CREATE INDEX IF NOT EXISTS idx_generation_cache_entity ON generation_cache(entity_type, entity_id);
12564
- CREATE INDEX IF NOT EXISTS idx_generation_cache_session ON generation_cache(source_session_id);
12565
11928
  CREATE INDEX IF NOT EXISTS idx_scanned_files_session ON scanned_files(session_id);
12566
11929
  `;
11930
+ REMOVED_CACHE_TABLES = ["generation_cache", "extract_cache", "composition_cache", "select_cache"];
12567
11931
  MAX_COMPONENT_SOURCE_CHARS = 8e3;
12568
11932
  MAX_SIBLING_FILES = 5;
12569
11933
  MAX_SIBLING_SNIPPET_CHARS = 1200;
@@ -12580,16 +11944,15 @@ CREATE INDEX IF NOT EXISTS idx_scanned_files_session ON scanned_files(session
12580
11944
  [".cjs", [".cts", ".cjs"]]
12581
11945
  ];
12582
11946
  IDENTIFIER_PATTERN = /[A-Za-z_$][A-Za-z0-9_$]*/g;
12583
- _cliCacheVersionCache = null;
12584
11947
  }
12585
11948
  });
12586
11949
 
12587
11950
  // packages/experience-design-system-cli-legacy/src/helpers/read-existing-contentful-entities-from-session.ts
12588
- import { readFile as readFile9 } from "node:fs/promises";
11951
+ import { readFile as readFile8 } from "node:fs/promises";
12589
11952
  async function readExistingContentfulEntitiesFromSession(path) {
12590
11953
  if (!path) return void 0;
12591
11954
  try {
12592
- const raw = await readFile9(path, "utf8");
11955
+ const raw = await readFile8(path, "utf8");
12593
11956
  const parsed = JSON.parse(raw);
12594
11957
  if (!Array.isArray(parsed.components) || !Array.isArray(parsed.tokens)) return void 0;
12595
11958
  return parsed;
@@ -12713,21 +12076,21 @@ var init_resolve_session_id = __esm({
12713
12076
  });
12714
12077
 
12715
12078
  // packages/experience-design-system-cli-legacy/src/analyze/select/persistence.ts
12716
- import { access, appendFile, mkdir as mkdir2, readFile as readFile10, writeFile as writeFile2 } from "node:fs/promises";
12079
+ import { access, appendFile, mkdir as mkdir2, readFile as readFile9, writeFile as writeFile2 } from "node:fs/promises";
12717
12080
  import { homedir as homedir4 } from "node:os";
12718
- import { resolve as resolve10 } from "node:path";
12081
+ import { resolve as resolve9 } from "node:path";
12719
12082
  function getRefineArtifactsRoot() {
12720
12083
  if (process.env.EDS_REVIEW_ARTIFACTS_DIR) {
12721
- return resolve10(process.env.EDS_REVIEW_ARTIFACTS_DIR);
12084
+ return resolve9(process.env.EDS_REVIEW_ARTIFACTS_DIR);
12722
12085
  }
12723
- return resolve10(homedir4(), ".contentful", "experience-design-system-cli", "reviews");
12086
+ return resolve9(homedir4(), ".contentful", "experience-design-system-cli", "reviews");
12724
12087
  }
12725
12088
  async function getRefineSessionPaths(sessionId2, artifactsRoot) {
12726
- const sessionDir = resolve10(artifactsRoot, sessionId2);
12089
+ const sessionDir = resolve9(artifactsRoot, sessionId2);
12727
12090
  return {
12728
12091
  sessionDir,
12729
- eventsPath: resolve10(sessionDir, "events.jsonl"),
12730
- statePath: resolve10(sessionDir, "current-review-state.json")
12092
+ eventsPath: resolve9(sessionDir, "events.jsonl"),
12093
+ statePath: resolve9(sessionDir, "current-review-state.json")
12731
12094
  };
12732
12095
  }
12733
12096
  async function saveReviewState(statePath, session) {
@@ -12738,7 +12101,7 @@ async function ensureRefineSession(sessionId2, artifactsRoot, initialSnapshot) {
12738
12101
  await mkdir2(paths.sessionDir, { recursive: true });
12739
12102
  try {
12740
12103
  await access(paths.statePath);
12741
- const savedState = await readFile10(paths.statePath, "utf8");
12104
+ const savedState = await readFile9(paths.statePath, "utf8");
12742
12105
  return JSON.parse(savedState);
12743
12106
  } catch {
12744
12107
  await writeFile2(paths.statePath, JSON.stringify(initialSnapshot, null, 2), "utf8");
@@ -13223,8 +12586,8 @@ var init_path_exists = __esm({
13223
12586
  });
13224
12587
 
13225
12588
  // packages/experience-design-system-cli-legacy/src/lib/prompt-overrides.ts
13226
- import { readFile as readFile11 } from "node:fs/promises";
13227
- import { resolve as resolve11 } from "node:path";
12589
+ import { readFile as readFile10 } from "node:fs/promises";
12590
+ import { resolve as resolve10 } from "node:path";
13228
12591
  function looksLikePath(value) {
13229
12592
  if (value.includes("/") || value.includes("\\")) return true;
13230
12593
  if (value.startsWith("~")) return true;
@@ -13256,9 +12619,9 @@ function parsePromptOverrides(inputs) {
13256
12619
  }
13257
12620
  async function resolvePromptOverride(override) {
13258
12621
  if (override.kind === "text") return override.value;
13259
- const abs = resolve11(override.value);
12622
+ const abs = resolve10(override.value);
13260
12623
  try {
13261
- return await readFile11(abs, "utf8");
12624
+ return await readFile10(abs, "utf8");
13262
12625
  } catch {
13263
12626
  throw new Error(`--prompt: could not read prompt file: ${abs}`);
13264
12627
  }
@@ -13273,21 +12636,21 @@ var init_prompt_overrides = __esm({
13273
12636
 
13274
12637
  // packages/experience-design-system-cli-legacy/src/generate/command.ts
13275
12638
  import { createElement } from "react";
13276
- import { readFile as readFile12, readdir, stat } from "node:fs/promises";
13277
- import { join as join14, resolve as resolve12 } from "node:path";
12639
+ import { readFile as readFile11, readdir, stat } from "node:fs/promises";
12640
+ import { join as join14, resolve as resolve11 } from "node:path";
13278
12641
  async function assertFileExists(flag, p) {
13279
12642
  if (!await pathExists(p)) die(`Error: file not found: ${p} (from ${flag})`);
13280
12643
  }
13281
12644
  async function readFileInline(path) {
13282
12645
  if (!path) return void 0;
13283
- const resolved = resolve12(path);
12646
+ const resolved = resolve11(path);
13284
12647
  let s;
13285
12648
  try {
13286
12649
  s = await stat(resolved);
13287
12650
  } catch {
13288
12651
  return void 0;
13289
12652
  }
13290
- if (!s.isDirectory()) return readFile12(resolved, "utf8");
12653
+ if (!s.isDirectory()) return readFile11(resolved, "utf8");
13291
12654
  const files = [];
13292
12655
  async function walk(dir) {
13293
12656
  let entries;
@@ -13313,7 +12676,7 @@ async function readFileInline(path) {
13313
12676
  }
13314
12677
  await walk(resolved);
13315
12678
  if (files.length === 0) return void 0;
13316
- const parts = await Promise.all(files.map((f) => readFile12(f, "utf8").catch(() => "")));
12679
+ const parts = await Promise.all(files.map((f) => readFile11(f, "utf8").catch(() => "")));
13317
12680
  return parts.filter(Boolean).join("\n\n");
13318
12681
  }
13319
12682
  function printFallbackInstructions(options) {
@@ -13335,23 +12698,6 @@ function printFallbackInstructions(options) {
13335
12698
  lines.push(` Re-run the generate command with the agent available, or use --dry-run to inspect the prompt.`);
13336
12699
  process.stderr.write(lines.join("\n") + "\n");
13337
12700
  }
13338
- function createCachedComponentResult(componentName, warnings = []) {
13339
- return {
13340
- componentName,
13341
- classified: 0,
13342
- excluded: 0,
13343
- slots: 0,
13344
- warnings,
13345
- failed: false,
13346
- cached: true,
13347
- renamedSlotsCount: 0
13348
- };
13349
- }
13350
- function writeCachedComponentStatus(position, componentName, pinned) {
13351
- const status = pinned ? c.cyan("pinned (human-edited)") : c.green("cached");
13352
- process.stderr.write(` ${position} ${c.bold(componentName)} ${status}
13353
- `);
13354
- }
13355
12701
  async function showGenerateView(result) {
13356
12702
  if (process.stdout.isTTY) {
13357
12703
  const { waitUntilExit } = renderWithGoodbye(
@@ -13372,29 +12718,6 @@ session=${result.sessionId}
13372
12718
  );
13373
12719
  await exitWithAnalytics(0);
13374
12720
  }
13375
- function normalizeComponentForCache(component) {
13376
- const slots = component.slots.map((slot, index, allSlots) => ({
13377
- ...slot,
13378
- name: slot.name.trim() || (allSlots.length === 1 ? "children" : `slot_${index}`)
13379
- }));
13380
- return { ...component, slots };
13381
- }
13382
- function lookupComponentCache(db, component, promptHash) {
13383
- const normalized = normalizeComponentForCache(component);
13384
- const inputHash = hashComponentShape(normalized);
13385
- const cached = lookupCache(db, inputHash, "component", component.component_id, promptHash);
13386
- if (cached) return cached;
13387
- const legacyInputHash = hashComponentShape(component);
13388
- return legacyInputHash === inputHash ? null : lookupCache(db, legacyInputHash, "component", component.component_id, promptHash);
13389
- }
13390
- function resolveComponentCache(db, component, promptHash, allowedComponentNames2) {
13391
- const cached = lookupComponentCache(db, component, promptHash);
13392
- if (cached && findUnknownSlotAllowedComponents(db, cached.sourceSessionId, allowedComponentNames2, component.component_id).length === 0) {
13393
- return { entry: cached, humanEdited: cached.humanEdited };
13394
- }
13395
- const pinned = lookupCacheByEntity(db, "component", component.component_id);
13396
- return pinned?.humanEdited && findUnknownSlotAllowedComponents(db, pinned.sourceSessionId, allowedComponentNames2, component.component_id).length === 0 ? { entry: pinned, humanEdited: true } : null;
13397
- }
13398
12721
  async function runOneComponent(options, component, index, total) {
13399
12722
  const {
13400
12723
  agent,
@@ -13404,13 +12727,10 @@ async function runOneComponent(options, component, index, total) {
13404
12727
  tokensInline,
13405
12728
  tokenMapInline,
13406
12729
  verbose,
13407
- noCache,
13408
12730
  skillPathOverride,
13409
12731
  skillContentOverride,
13410
- promptHash,
13411
12732
  existingContentfulEntities,
13412
12733
  existingTokensInline,
13413
- precomputedCachedNames,
13414
12734
  allowedComponentNames: allowedComponentNames2
13415
12735
  } = options;
13416
12736
  const pos = c.dim(`[${index + 1}/${total}]`);
@@ -13435,40 +12755,6 @@ async function runOneComponent(options, component, index, total) {
13435
12755
  allowedComponents: slot.allowedComponents.filter((name) => allowedComponentNames2.has(name))
13436
12756
  };
13437
12757
  });
13438
- const cacheComponent = normalizeComponentForCache(component);
13439
- if (!noCache && precomputedCachedNames.has(component.name)) {
13440
- writeCachedComponentStatus(pos, component.name, false);
13441
- return createCachedComponentResult(component.name);
13442
- }
13443
- if (!noCache) {
13444
- const inputHash = hashComponentShape(cacheComponent);
13445
- const resolution = resolveComponentCache(db, component, promptHash, allowedComponentNames2);
13446
- if (resolution && !resolution.humanEdited) {
13447
- copyComponentFromCache(db, resolution.entry.sourceSessionId, sessionId2, component.component_id, true, {
13448
- allowedComponentNames: allowedComponentNames2
13449
- });
13450
- storeCache(
13451
- db,
13452
- inputHash,
13453
- "component",
13454
- component.component_id,
13455
- resolution.entry.sourceSessionId,
13456
- resolution.entry.humanEdited,
13457
- promptHash
13458
- );
13459
- writeCachedComponentStatus(pos, component.name, false);
13460
- return createCachedComponentResult(component.name);
13461
- }
13462
- if (resolution?.humanEdited) {
13463
- copyComponentFromCache(db, resolution.entry.sourceSessionId, sessionId2, component.component_id, true, {
13464
- allowedComponentNames: allowedComponentNames2
13465
- });
13466
- writeCachedComponentStatus(pos, component.name, true);
13467
- return createCachedComponentResult(`${component.name}`, [
13468
- `${component.name}: source changed but human edits preserved`
13469
- ]);
13470
- }
13471
- }
13472
12758
  const componentBuckets = bucketComponentProps(component);
13473
12759
  getDebugLogger().event("analyze", "prop-buckets.generate", { ...componentBuckets });
13474
12760
  const rawComponentsInline = JSON.stringify(
@@ -13543,10 +12829,6 @@ ${outputBuf}`);
13543
12829
  const applied = applyToolCalls(db, sessionId2, component.component_id, component.name, calls, warnings, {
13544
12830
  allowedComponentNames: allowedComponentNames2
13545
12831
  });
13546
- if (!noCache) {
13547
- const inputHash = hashComponentShape(cacheComponent);
13548
- storeCache(db, inputHash, "component", component.component_id, sessionId2, false, promptHash);
13549
- }
13550
12832
  return {
13551
12833
  componentName: component.name,
13552
12834
  classified: applied.classified,
@@ -13598,7 +12880,7 @@ async function loadAcceptedNames(sessionId2) {
13598
12880
  try {
13599
12881
  const artifactsRoot = getRefineArtifactsRoot();
13600
12882
  const paths = await getRefineSessionPaths(sessionId2, artifactsRoot);
13601
- const raw = await readFile12(paths.statePath, "utf8");
12883
+ const raw = await readFile11(paths.statePath, "utf8");
13602
12884
  const snapshot = JSON.parse(raw);
13603
12885
  const accepted = snapshot.components.filter((c2) => c2.status === "accepted").map((c2) => c2.name);
13604
12886
  if (accepted.length === 0) return null;
@@ -13607,15 +12889,6 @@ async function loadAcceptedNames(sessionId2) {
13607
12889
  return null;
13608
12890
  }
13609
12891
  }
13610
- function parsePrecomputedCachedNames(value) {
13611
- if (!value) return /* @__PURE__ */ new Set();
13612
- try {
13613
- const parsed = JSON.parse(value);
13614
- return new Set(Array.isArray(parsed) ? parsed.filter((name) => typeof name === "string") : []);
13615
- } catch {
13616
- return /* @__PURE__ */ new Set();
13617
- }
13618
- }
13619
12892
  async function runGenerateSkill(skill, opts, verbose = false) {
13620
12893
  const savedCreds = await readExperiencesCredentials();
13621
12894
  const agentName = opts.agent ?? savedCreds.agent;
@@ -13644,8 +12917,8 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13644
12917
  }
13645
12918
  const generatePromptPath = generatePrompt === void 0 ? configuredGeneratePromptPath : void 0;
13646
12919
  if (generatePromptPath) {
13647
- if (!await pathExists(resolve12(generatePromptPath))) {
13648
- die(`Error: custom prompt path not found: ${resolve12(generatePromptPath)}`);
12920
+ if (!await pathExists(resolve11(generatePromptPath))) {
12921
+ die(`Error: custom prompt path not found: ${resolve11(generatePromptPath)}`);
13649
12922
  }
13650
12923
  if (!generatePromptPath.toLowerCase().endsWith(".md")) {
13651
12924
  process.stderr.write(
@@ -13653,7 +12926,7 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13653
12926
  `
13654
12927
  );
13655
12928
  }
13656
- process.stderr.write(formatCustomPromptBanner("components", resolve12(generatePromptPath)));
12929
+ process.stderr.write(formatCustomPromptBanner("components", resolve11(generatePromptPath)));
13657
12930
  }
13658
12931
  if (skill === "tokens" && !opts.rawTokens) {
13659
12932
  die("Error: --raw-tokens is required when using generate tokens");
@@ -13669,7 +12942,7 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13669
12942
  let existingContentfulEntities;
13670
12943
  let existingTokensInline;
13671
12944
  if (opts.existingEntitiesPath) {
13672
- existingContentfulEntities = await readExistingContentfulEntitiesFromSession(resolve12(opts.existingEntitiesPath));
12945
+ existingContentfulEntities = await readExistingContentfulEntitiesFromSession(resolve11(opts.existingEntitiesPath));
13673
12946
  if (existingContentfulEntities) {
13674
12947
  existingTokensInline = JSON.stringify(summarizeForMapTokens(existingContentfulEntities));
13675
12948
  } else {
@@ -13770,7 +13043,7 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13770
13043
  rawComponentsInline: sampleInline ?? rawTokensInline,
13771
13044
  propBucketsInline: sampleBuckets ? JSON.stringify(sampleBuckets) : void 0,
13772
13045
  rawTokensInline: skill === "tokens" ? rawTokensInline : void 0,
13773
- rawTokensFilename: opts.rawTokens ? resolve12(opts.rawTokens).split("/").pop() : void 0,
13046
+ rawTokensFilename: opts.rawTokens ? resolve11(opts.rawTokens).split("/").pop() : void 0,
13774
13047
  tokensInline,
13775
13048
  tokenMapInline,
13776
13049
  outDir: process.cwd(),
@@ -13796,64 +13069,7 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13796
13069
  if (skill === "components" && allComponents && sessionId2) {
13797
13070
  const db = openPipelineDb();
13798
13071
  let componentResults;
13799
- const precomputedCachedNames = parsePrecomputedCachedNames(opts.cachedComponents);
13800
13072
  try {
13801
- const existingContentfulEntitiesHashInputs = [];
13802
- if (existingTokensInline) existingContentfulEntitiesHashInputs.push(hashContent(existingTokensInline));
13803
- const promptHash = await hashPromptForSkill(
13804
- "components",
13805
- agent,
13806
- model,
13807
- generatePromptPath,
13808
- existingContentfulEntitiesHashInputs,
13809
- generatePrompt
13810
- );
13811
- if (opts.cacheStatus) {
13812
- const cacheEnabled = opts.cache !== false && process.env.EDS_NO_CACHE !== "1";
13813
- const cachedComponents = cacheEnabled ? allComponents.flatMap((component) => {
13814
- const resolution = resolveComponentCache(db, component, promptHash, allowedComponentNames2);
13815
- return resolution ? [{ component, resolution }] : [];
13816
- }) : [];
13817
- if (cacheEnabled && opts.restoreCache) {
13818
- const restorations = [];
13819
- const rekeyed = [];
13820
- const componentStatus = db.prepare(
13821
- "SELECT status FROM raw_components WHERE session_id = ? AND component_id = ?"
13822
- );
13823
- for (const { component, resolution } of cachedComponents) {
13824
- const current = componentStatus.get(sessionId2, component.component_id);
13825
- if (current?.status === "generated") continue;
13826
- renameEmptySlots(db, sessionId2, component.component_id, component.name, component.slots.length);
13827
- restorations.push({
13828
- sourceSessionId: resolution.entry.sourceSessionId,
13829
- targetSessionId: sessionId2,
13830
- componentId: component.component_id
13831
- });
13832
- rekeyed.push({ component, cached: resolution.entry });
13833
- }
13834
- copyComponentsFromCache(db, restorations, { allowedComponentNames: allowedComponentNames2 });
13835
- storeCaches(
13836
- db,
13837
- rekeyed.map(({ component, cached }) => ({
13838
- inputHash: hashComponentShape(normalizeComponentForCache(component)),
13839
- entityType: "component",
13840
- entityId: component.component_id,
13841
- sourceSessionId: cached.sourceSessionId,
13842
- humanEdited: cached.humanEdited,
13843
- promptHash
13844
- }))
13845
- );
13846
- }
13847
- const fullyCached = cacheEnabled && cachedComponents.length === allComponents.length;
13848
- process.stdout.write(`cache-status=${fullyCached ? "hit" : "miss"}
13849
- `);
13850
- process.stdout.write(
13851
- `cache-components=${JSON.stringify(cachedComponents.map(({ component }) => component.name))}
13852
- `
13853
- );
13854
- await exitWithAnalytics(0);
13855
- return;
13856
- }
13857
13073
  componentResults = await runAllComponents(
13858
13074
  {
13859
13075
  agent,
@@ -13863,13 +13079,10 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13863
13079
  tokensInline,
13864
13080
  tokenMapInline,
13865
13081
  verbose,
13866
- noCache: opts.cache === false || process.env.EDS_NO_CACHE === "1",
13867
13082
  skillPathOverride: generatePromptPath,
13868
13083
  skillContentOverride: generatePrompt,
13869
- promptHash,
13870
13084
  existingContentfulEntities,
13871
13085
  existingTokensInline,
13872
- precomputedCachedNames,
13873
13086
  allowedComponentNames: allowedComponentNames2
13874
13087
  },
13875
13088
  allComponents
@@ -13878,8 +13091,7 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13878
13091
  db.close();
13879
13092
  }
13880
13093
  const failed = componentResults.filter((r) => r.failed);
13881
- const cachedResults = componentResults.filter((r) => r.cached);
13882
- const generated = componentResults.filter((r) => !r.failed && !r.cached);
13094
+ const generated = componentResults.filter((r) => !r.failed);
13883
13095
  const allWarnings = componentResults.flatMap((r) => r.warnings.map((w) => ` ${r.componentName}: ${w}`));
13884
13096
  if (allWarnings.length > 0) {
13885
13097
  process.stderr.write(c.yellow("Warnings:") + "\n" + allWarnings.join("\n") + "\n");
@@ -13895,21 +13107,17 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13895
13107
  const totalExcluded = generated.reduce((s, r) => s + r.excluded, 0);
13896
13108
  const totalRenamedSlots = componentResults.reduce((s, r) => s + r.renamedSlotsCount, 0);
13897
13109
  const allOk = failed.length === 0;
13898
- const cachedNote = cachedResults.length > 0 ? c.dim(` (${cachedResults.length} cached)`) : "";
13899
13110
  process.stderr.write(
13900
- (allOk ? c.green("\u2713") : c.yellow("\u26A0")) + ` ${generated.length + cachedResults.length}/${componentResults.length} components` + cachedNote + c.dim(` ${totalClassified} classified, ${totalExcluded} unattached`) + "\n"
13111
+ (allOk ? c.green("\u2713") : c.yellow("\u26A0")) + ` ${generated.length}/${componentResults.length} components` + c.dim(` ${totalClassified} classified, ${totalExcluded} unattached`) + "\n"
13901
13112
  );
13902
13113
  process.stdout.write(`renamed-slots: ${totalRenamedSlots}
13903
13114
  `);
13904
- if (generated.length === 0 && cachedResults.length === 0) {
13115
+ if (generated.length === 0) {
13905
13116
  die(
13906
13117
  `Error: all ${componentResults.length} component(s) failed to generate \u2014 see the per-component errors above.`
13907
13118
  );
13908
13119
  }
13909
13120
  } else if (skill === "tokens") {
13910
- const noCache = opts.cache === false || process.env.EDS_NO_CACHE === "1";
13911
- const tokenInputContent = rawTokensInline ?? "";
13912
- const tokenInputHash = hashTokenContent(tokenInputContent);
13913
13121
  const db = openPipelineDb();
13914
13122
  try {
13915
13123
  let resolvedSessionId = opts.session;
@@ -13936,26 +13144,11 @@ async function runGenerateSkill(skill, opts, verbose = false) {
13936
13144
  }
13937
13145
  sessionId2 = resolvedSessionId;
13938
13146
  await bindAnalyticsSessionId(resolvedSessionId);
13939
- const tokenPromptHash = await hashPromptForSkill("tokens", agent, model);
13940
- if (!noCache) {
13941
- const tokenCached = lookupCache(db, tokenInputHash, "token_set", "__tokens__", tokenPromptHash);
13942
- if (tokenCached) {
13943
- copyTokensFromCache(db, tokenCached.sourceSessionId, resolvedSessionId);
13944
- sessionId2 = resolvedSessionId;
13945
- process.stderr.write(
13946
- `Done: tokens reused from cache ${c.dim(`(source: ${tokenCached.sourceSessionId.slice(0, 12)})`)}
13947
- `
13948
- );
13949
- db.close();
13950
- await showGenerateView({ skill, agent, sessionId: sessionId2 ?? "" });
13951
- return;
13952
- }
13953
- }
13954
13147
  const prompt = await buildPrompt({
13955
13148
  skill,
13956
13149
  mode: "autonomous",
13957
13150
  rawTokensInline,
13958
- rawTokensFilename: opts.rawTokens ? resolve12(opts.rawTokens).split("/").pop() : void 0,
13151
+ rawTokensFilename: opts.rawTokens ? resolve11(opts.rawTokens).split("/").pop() : void 0,
13959
13152
  tokensInline,
13960
13153
  tokenMapInline,
13961
13154
  outDir: process.cwd()
@@ -13992,9 +13185,6 @@ ${tokenWarnings.map((w) => ` ${w}`).join("\n")}
13992
13185
  `);
13993
13186
  }
13994
13187
  applyTokenToolCalls(db, resolvedSessionId, tokenCalls, []);
13995
- if (!noCache) {
13996
- storeCache(db, tokenInputHash, "token_set", "__tokens__", resolvedSessionId, false, tokenPromptHash);
13997
- }
13998
13188
  sessionId2 = resolvedSessionId;
13999
13189
  const groupCount = tokenCalls.filter((tc) => tc.tool === "set_group").length;
14000
13190
  process.stderr.write(`Done: ${tokenCount} tokens, ${groupCount} groups stored
@@ -14006,10 +13196,7 @@ ${tokenWarnings.map((w) => ` ${w}`).join("\n")}
14006
13196
  await showGenerateView({ skill, agent, sessionId: sessionId2 ?? "" });
14007
13197
  }
14008
13198
  function addAgentFlags(cmd) {
14009
- return addAgentModelOptions(cmd).option("--verbose", "Show full agent output including reasoning text").option("--dry-run", "Print the prompt without invoking the agent").option(
14010
- "--no-cache",
14011
- "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."
14012
- );
13199
+ return addAgentModelOptions(cmd).option("--verbose", "Show full agent output including reasoning text").option("--dry-run", "Print the prompt without invoking the agent");
14013
13200
  }
14014
13201
  function registerInternalGenerateCommand(program) {
14015
13202
  const generate = program.command("__generate", { hidden: true }).description("Internal import pipeline generation command");
@@ -14025,12 +13212,6 @@ function registerInternalGenerateCommand(program) {
14025
13212
  "--existing-entities-path <path>",
14026
13213
  "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."
14027
13214
  );
14028
- componentsCmd.option("--cache-status", "Check whether all selected component definitions are cached");
14029
- componentsCmd.option("--restore-cache", "Restore cached component definitions into the current session");
14030
- componentsCmd.option(
14031
- "--cached-components <json>",
14032
- "Component names already restored by a prior cache-status lookup; skip per-component cache lookup"
14033
- );
14034
13215
  addAgentFlags(componentsCmd).action(async (opts) => {
14035
13216
  await runGenerateSkill("components", opts, opts.verbose ?? false);
14036
13217
  });
@@ -14056,7 +13237,6 @@ var init_command = __esm({
14056
13237
  init_agent_output();
14057
13238
  init_GenerateView();
14058
13239
  init_db();
14059
- init_cache_keys();
14060
13240
  init_read_existing_contentful_entities_from_session();
14061
13241
  init_summarize_existing_contentful_entities();
14062
13242
  init_resolve_session_id();
@@ -14772,7 +13952,7 @@ var init_user_agent = __esm({
14772
13952
  // packages/experience-design-system-cli-legacy/src/apply/api-client.ts
14773
13953
  import { parseCDFComponents } from "@contentful/experience-design-system-types";
14774
13954
  function defaultSleep(delayMs) {
14775
- return new Promise((resolve22) => setTimeout(resolve22, delayMs));
13955
+ return new Promise((resolve20) => setTimeout(resolve20, delayMs));
14776
13956
  }
14777
13957
  function isTransientStatus(status) {
14778
13958
  return status >= 500 && status <= 599;
@@ -15162,7 +14342,7 @@ ${trimmed}`;
15162
14342
  const progress = maxAttempts > 1 ? attempt / (maxAttempts - 1) : 0;
15163
14343
  const baseDelay = intervalMs + (maxIntervalMs - intervalMs) * progress;
15164
14344
  const jitter = Math.random() * baseDelay * 0.15;
15165
- await new Promise((resolve22) => setTimeout(resolve22, baseDelay + jitter));
14345
+ await new Promise((resolve20) => setTimeout(resolve20, baseDelay + jitter));
15166
14346
  }
15167
14347
  }
15168
14348
  throw new Error(`Operation ${operationId} timed out after ${maxAttempts} attempts`);
@@ -15972,7 +15152,7 @@ var init_terminal_capabilities = __esm({
15972
15152
 
15973
15153
  // packages/experience-design-system-cli-legacy/src/apply/command.ts
15974
15154
  import { createElement as createElement2 } from "react";
15975
- import { readFile as readFile13, readdir as readdir2, stat as stat2 } from "node:fs/promises";
15155
+ import { readFile as readFile12, readdir as readdir2, stat as stat2 } from "node:fs/promises";
15976
15156
  import { join as join16 } from "node:path";
15977
15157
  import {
15978
15158
  validateCDF,
@@ -15993,7 +15173,7 @@ function dieWithApiError(error) {
15993
15173
  async function readJsonFile(flag, p) {
15994
15174
  let text;
15995
15175
  try {
15996
- text = await readFile13(p, "utf8");
15176
+ text = await readFile12(p, "utf8");
15997
15177
  } catch {
15998
15178
  return await die2(`Error: file not found: ${p} (from ${flag})`);
15999
15179
  }
@@ -16047,7 +15227,7 @@ async function readTokensFromPath(flag, p) {
16047
15227
  for (const file of files.sort()) {
16048
15228
  let text;
16049
15229
  try {
16050
- text = await readFile13(file, "utf8");
15230
+ text = await readFile12(file, "utf8");
16051
15231
  } catch {
16052
15232
  continue;
16053
15233
  }
@@ -16416,11 +15596,11 @@ var init_command2 = __esm({
16416
15596
  });
16417
15597
 
16418
15598
  // packages/experience-design-system-cli-legacy/src/print/validate/validators/read-json-file.ts
16419
- import { readFile as readFile14 } from "node:fs/promises";
15599
+ import { readFile as readFile13 } from "node:fs/promises";
16420
15600
  async function readJsonFile2(filePath) {
16421
15601
  let content;
16422
15602
  try {
16423
- content = await readFile14(filePath, "utf-8");
15603
+ content = await readFile13(filePath, "utf-8");
16424
15604
  } catch (err) {
16425
15605
  return {
16426
15606
  ok: false,
@@ -16831,7 +16011,7 @@ var init_ValidateView = __esm({
16831
16011
  // packages/experience-design-system-cli-legacy/src/print/command.ts
16832
16012
  import { createElement as createElement3 } from "react";
16833
16013
  import { access as access3, mkdir as mkdir3, stat as stat3, writeFile as writeFile3 } from "node:fs/promises";
16834
- import { basename as basename5, resolve as resolve13 } from "node:path";
16014
+ import { basename as basename5, resolve as resolve12 } from "node:path";
16835
16015
  import { CDF_SCHEMA_URL } from "@contentful/experience-design-system-types";
16836
16016
  async function die3(message) {
16837
16017
  process.stderr.write(`${message}
@@ -16898,7 +16078,7 @@ function registerPrintCommand(program) {
16898
16078
  "--allow-empty",
16899
16079
  "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."
16900
16080
  ).action(async (opts) => {
16901
- const outPath = resolve13(opts.out);
16081
+ const outPath = resolve12(opts.out);
16902
16082
  await assertOutIsNotDirectory(outPath);
16903
16083
  const sessionId2 = await resolveSession(opts.session, "generate components");
16904
16084
  await bindAnalyticsSessionId(sessionId2);
@@ -16946,7 +16126,7 @@ function registerPrintCommand(program) {
16946
16126
  `
16947
16127
  );
16948
16128
  }
16949
- await mkdir3(resolve13(outPath, ".."), { recursive: true });
16129
+ await mkdir3(resolve12(outPath, ".."), { recursive: true });
16950
16130
  await writeFile3(outPath, `${JSON.stringify(cdfObj, null, 2)}
16951
16131
  `);
16952
16132
  process.stdout.write(
@@ -16955,7 +16135,7 @@ function registerPrintCommand(program) {
16955
16135
  );
16956
16136
  });
16957
16137
  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) => {
16958
- const outPath = resolve13(opts.out);
16138
+ const outPath = resolve12(opts.out);
16959
16139
  await assertOutIsNotDirectory(outPath);
16960
16140
  const sessionId2 = await resolveSession(opts.session, "generate tokens");
16961
16141
  await bindAnalyticsSessionId(sessionId2);
@@ -16970,7 +16150,7 @@ function registerPrintCommand(program) {
16970
16150
  await die3(`Error: no generated tokens in session '${sessionId2}'. Run generate tokens first.`);
16971
16151
  }
16972
16152
  const tree = rebuildDTCGTree(result.groups, result.tokens);
16973
- await mkdir3(resolve13(outPath, ".."), { recursive: true });
16153
+ await mkdir3(resolve12(outPath, ".."), { recursive: true });
16974
16154
  await writeFile3(outPath, `${JSON.stringify(tree, null, 2)}
16975
16155
  `);
16976
16156
  process.stdout.write(
@@ -17119,7 +16299,7 @@ function MapTokensView({ result, onExit }) {
17119
16299
  const timer = setTimeout(onExit, 100);
17120
16300
  return () => clearTimeout(timer);
17121
16301
  }, [onExit]);
17122
- const summary = result.cached ? "reused from cache" : `${result.applied} mapping${result.applied === 1 ? "" : "s"} applied`;
16302
+ const summary = `${result.applied} mapping${result.applied === 1 ? "" : "s"} applied`;
17123
16303
  return /* @__PURE__ */ jsx8(
17124
16304
  CommandCompletionView,
17125
16305
  {
@@ -17253,8 +16433,8 @@ var init_resolve_defaults = __esm({
17253
16433
 
17254
16434
  // packages/experience-design-system-cli-legacy/src/map-tokens/command.ts
17255
16435
  import { createElement as createElement4 } from "react";
17256
- import { readFile as readFile15 } from "node:fs/promises";
17257
- import { resolve as resolve14 } from "node:path";
16436
+ import { readFile as readFile14 } from "node:fs/promises";
16437
+ import { resolve as resolve13 } from "node:path";
17258
16438
  async function renderResult(result) {
17259
16439
  if (process.stdout.isTTY) {
17260
16440
  const { waitUntilExit } = renderWithGoodbye(
@@ -17262,12 +16442,13 @@ async function renderResult(result) {
17262
16442
  );
17263
16443
  await waitUntilExit();
17264
16444
  } else {
17265
- const summary = result.cached ? "cached" : `${result.applied} mapping(s) applied`;
17266
- process.stdout.write(`map tokens complete
16445
+ process.stdout.write(
16446
+ `map tokens complete
17267
16447
  agent: ${result.agent}
17268
16448
  session=${result.sessionId}
17269
- ${summary}
17270
- `);
16449
+ ${result.applied} mapping(s) applied
16450
+ `
16451
+ );
17271
16452
  await exitWithAnalytics(0);
17272
16453
  }
17273
16454
  }
@@ -17289,7 +16470,7 @@ async function runMapTokens(opts) {
17289
16470
  let mapPromptPath;
17290
16471
  if (mapPromptOverride?.kind === "text") mapPromptText = mapPromptOverride.value;
17291
16472
  if (mapPromptOverride?.kind === "path") {
17292
- mapPromptPath = resolve14(mapPromptOverride.value);
16473
+ mapPromptPath = resolve13(mapPromptOverride.value);
17293
16474
  try {
17294
16475
  await resolvePromptOverride(mapPromptOverride);
17295
16476
  } catch (error) {
@@ -17309,7 +16490,7 @@ async function runMapTokens(opts) {
17309
16490
  const knownTokenPaths = new Set(tokenLeaves.map((t) => t.path));
17310
16491
  const tokenMapDiagnostics = [];
17311
16492
  if (opts.tokenMap) {
17312
- const fileMappings = JSON.parse(await readFile15(opts.tokenMap, "utf8"));
16493
+ const fileMappings = JSON.parse(await readFile14(opts.tokenMap, "utf8"));
17313
16494
  const validMappings = {};
17314
16495
  for (const [rawName, path] of Object.entries(fileMappings)) {
17315
16496
  if (knownTokenPaths.has(path)) {
@@ -17387,7 +16568,7 @@ ${defaultDiagnostics.map((diagnostic) => ` ${diagnostic}`).join("\n")}
17387
16568
  let existingTokensInline;
17388
16569
  if (opts.existingEntitiesPath) {
17389
16570
  const existingContentfulEntities = await readExistingContentfulEntitiesFromSession(
17390
- resolve14(opts.existingEntitiesPath)
16571
+ resolve13(opts.existingEntitiesPath)
17391
16572
  );
17392
16573
  if (existingContentfulEntities) {
17393
16574
  existingTokensInline = JSON.stringify(summarizeForMapTokens(existingContentfulEntities));
@@ -17422,30 +16603,10 @@ ${defaultDiagnostics.map((diagnostic) => ` ${diagnostic}`).join("\n")}
17422
16603
  skipAgent: "true"
17423
16604
  });
17424
16605
  updateStep(db, stepId2, "complete", { applied: "0", skipAgent: "true" });
17425
- await renderResult({ agent: resultAgent, sessionId: sessionId2, applied: 0, cached: false });
16606
+ await renderResult({ agent: resultAgent, sessionId: sessionId2, applied: 0 });
17426
16607
  return;
17427
16608
  }
17428
16609
  const agent = configuredAgent;
17429
- const noCache = opts.cache === false || process.env.EDS_NO_CACHE === "1";
17430
- const promptHash = await hashPromptForSkill(
17431
- "map-tokens",
17432
- agent,
17433
- model,
17434
- void 0,
17435
- existingTokensInline ? [hashContent(existingTokensInline)] : [],
17436
- mapPromptText
17437
- );
17438
- const inputHash = computeMapTokensInputHash(db, sessionId2, componentSourceRefs);
17439
- if (!noCache) {
17440
- const cached = lookupCache(db, inputHash, "token_mapping", "__map_tokens__", promptHash);
17441
- if (cached) {
17442
- const appliedFromCache = copyMapTokensFromCache(db, cached.sourceSessionId, sessionId2);
17443
- const stepId2 = createStep(db, sessionId2, "map tokens", { agent, model: model ?? "" });
17444
- updateStep(db, stepId2, "complete", { cached: "true", applied: String(appliedFromCache) });
17445
- await renderResult({ agent, sessionId: sessionId2, applied: appliedFromCache, cached: true });
17446
- return;
17447
- }
17448
- }
17449
16610
  const binary = resolveAgentBinary(agent);
17450
16611
  if (!await assertBinaryInPath(binary)) {
17451
16612
  die(
@@ -17465,23 +16626,20 @@ Install it, choose another agent with --agent, or use --print-prompt to run the
17465
16626
  }
17466
16627
  const { calls, warnings: parseWarnings } = parseMapTokenPropToolCallLines(result.stdout);
17467
16628
  const { applied, warnings } = applyMapTokenPropCalls(db, sessionId2, calls, parseWarnings);
17468
- if (!noCache) {
17469
- storeCache(db, inputHash, "token_mapping", "__map_tokens__", sessionId2, false, promptHash);
17470
- }
17471
16629
  updateStep(db, stepId, "complete", { applied: String(applied), warnings: String(warnings.length) });
17472
16630
  if (warnings.length > 0) {
17473
16631
  process.stderr.write(`Warnings:
17474
16632
  ${warnings.map((w) => ` ${w}`).join("\n")}
17475
16633
  `);
17476
16634
  }
17477
- await renderResult({ agent, sessionId: sessionId2, applied, cached: false });
16635
+ await renderResult({ agent, sessionId: sessionId2, applied });
17478
16636
  } finally {
17479
16637
  db.close();
17480
16638
  }
17481
16639
  }
17482
16640
  function registerMapTokensCommand(program) {
17483
16641
  const map = program.command("map", { hidden: true }).description("Suggest token restrictions for generated design-token props");
17484
- 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(
16642
+ 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(
17485
16643
  "--prompt <stage=value>",
17486
16644
  "Override a stage prompt (repeatable). Used here for the map-tokens stage.",
17487
16645
  (v, acc) => [...acc, v],
@@ -17501,7 +16659,6 @@ var init_command4 = __esm({
17501
16659
  init_render_with_goodbye();
17502
16660
  init_src();
17503
16661
  init_db();
17504
- init_cache_keys();
17505
16662
  init_read_existing_contentful_entities_from_session();
17506
16663
  init_summarize_existing_contentful_entities();
17507
16664
  init_command3();
@@ -17518,7 +16675,7 @@ var init_command4 = __esm({
17518
16675
  });
17519
16676
 
17520
16677
  // packages/experience-design-system-cli-legacy/src/import/path-utils.ts
17521
- import { resolve as resolve15 } from "node:path";
16678
+ import { resolve as resolve14 } from "node:path";
17522
16679
  import { homedir as homedir5 } from "node:os";
17523
16680
  function expandTilde(input) {
17524
16681
  if (input === "~" || input.startsWith("~/") || input.startsWith("~\\")) {
@@ -17532,7 +16689,7 @@ function normalizePath(input) {
17532
16689
  p = p.slice(1, -1);
17533
16690
  }
17534
16691
  p = expandTilde(p);
17535
- return resolve15(p);
16692
+ return resolve14(p);
17536
16693
  }
17537
16694
  var init_path_utils = __esm({
17538
16695
  "packages/experience-design-system-cli-legacy/src/import/path-utils.ts"() {
@@ -17757,7 +16914,7 @@ var init_save_path_resolver = __esm({
17757
16914
  });
17758
16915
 
17759
16916
  // packages/experience-design-system-cli-legacy/src/runs/store.ts
17760
- import { readFile as readFile16, writeFile as writeFile4, mkdir as mkdir4, rename } from "node:fs/promises";
16917
+ import { readFile as readFile15, writeFile as writeFile4, mkdir as mkdir4, rename } from "node:fs/promises";
17761
16918
  import { join as join20 } from "node:path";
17762
16919
  import { homedir as homedir6 } from "node:os";
17763
16920
  import { randomBytes as randomBytes2 } from "node:crypto";
@@ -17797,7 +16954,7 @@ function migrateRecord(rec) {
17797
16954
  }
17798
16955
  async function readFileMaybe() {
17799
16956
  try {
17800
- const raw = await readFile16(RUNS_PATH, "utf8");
16957
+ const raw = await readFile15(RUNS_PATH, "utf8");
17801
16958
  const parsed = JSON.parse(raw);
17802
16959
  if (!READABLE_VERSIONS.has(parsed.version)) {
17803
16960
  throw new Error(
@@ -17861,15 +17018,15 @@ var init_store = __esm({
17861
17018
  });
17862
17019
 
17863
17020
  // packages/experience-design-system-cli-legacy/src/runs/fingerprint.ts
17864
- import { createHash as createHash6 } from "node:crypto";
17865
- import { readFile as readFile17, stat as stat4 } from "node:fs/promises";
17866
- import { resolve as resolve16 } from "node:path";
17021
+ import { createHash as createHash2 } from "node:crypto";
17022
+ import { readFile as readFile16, stat as stat4 } from "node:fs/promises";
17023
+ import { resolve as resolve15 } from "node:path";
17867
17024
  function rowField(row, key) {
17868
17025
  const v = row[key];
17869
17026
  return typeof v === "string" ? v : null;
17870
17027
  }
17871
17028
  function sha256Hex(buf) {
17872
- return createHash6("sha256").update(buf).digest("hex");
17029
+ return createHash2("sha256").update(buf).digest("hex");
17873
17030
  }
17874
17031
  async function buildSourceFingerprint(opts) {
17875
17032
  const rows = opts.db.prepare("SELECT name, source_path FROM raw_components WHERE session_id = ?").all(opts.extractSessionId);
@@ -17879,7 +17036,7 @@ async function buildSourceFingerprint(opts) {
17879
17036
  const sourcePath = rowField(row, "source_path");
17880
17037
  const name = rowField(row, "name");
17881
17038
  if (!sourcePath) continue;
17882
- const abs = resolve16(sourcePath);
17039
+ const abs = resolve15(sourcePath);
17883
17040
  if (seen.has(abs)) continue;
17884
17041
  seen.add(abs);
17885
17042
  try {
@@ -17894,10 +17051,10 @@ async function buildSourceFingerprint(opts) {
17894
17051
  let rawTokensMtime = null;
17895
17052
  let rawTokensContentHash = null;
17896
17053
  if (opts.rawTokensPath) {
17897
- const abs = resolve16(opts.rawTokensPath);
17054
+ const abs = resolve15(opts.rawTokensPath);
17898
17055
  rawTokensPath = abs;
17899
17056
  try {
17900
- const [st, buf] = await Promise.all([stat4(abs), readFile17(abs)]);
17057
+ const [st, buf] = await Promise.all([stat4(abs), readFile16(abs)]);
17901
17058
  rawTokensMtime = st.mtime.toISOString();
17902
17059
  rawTokensContentHash = sha256Hex(buf);
17903
17060
  } catch {
@@ -19652,11 +18809,11 @@ var init_slot_graph = __esm({
19652
18809
  });
19653
18810
 
19654
18811
  // packages/experience-design-system-cli-legacy/src/analyze/select/parser.ts
19655
- import { createHash as createHash7 } from "node:crypto";
18812
+ import { createHash as createHash3 } from "node:crypto";
19656
18813
  import { access as access5 } from "node:fs/promises";
19657
- import { isAbsolute, relative, resolve as resolve17 } from "node:path";
18814
+ import { isAbsolute, relative, resolve as resolve16 } from "node:path";
19658
18815
  function createComponentId(name, resolvedSourcePath) {
19659
- const sourceHash = createHash7("sha256").update(`${name}:${resolvedSourcePath}`).digest("hex").slice(0, 12);
18816
+ const sourceHash = createHash3("sha256").update(`${name}:${resolvedSourcePath}`).digest("hex").slice(0, 12);
19660
18817
  return `${name}-${sourceHash}`;
19661
18818
  }
19662
18819
  async function resolveComponentSourcePath(source, reviewRoot) {
@@ -19668,7 +18825,7 @@ async function resolveComponentSourcePath(source, reviewRoot) {
19668
18825
  throw new Error(`Unable to access component source at ${source}`);
19669
18826
  }
19670
18827
  }
19671
- const candidate = resolve17(reviewRoot, source);
18828
+ const candidate = resolve16(reviewRoot, source);
19672
18829
  const relativeToRoot = relative(reviewRoot, candidate);
19673
18830
  if (relativeToRoot.startsWith("..") || relativeToRoot === ".." || isAbsolute(relativeToRoot)) {
19674
18831
  throw new Error(
@@ -19683,7 +18840,7 @@ async function resolveComponentSourcePath(source, reviewRoot) {
19683
18840
  }
19684
18841
  }
19685
18842
  async function loadReviewInput(components, options = {}) {
19686
- const reviewRoot = resolve17(options.reviewRoot ?? process.cwd());
18843
+ const reviewRoot = resolve16(options.reviewRoot ?? process.cwd());
19687
18844
  const records = await Promise.all(
19688
18845
  components.map(async (component) => {
19689
18846
  let resolvedSourcePath;
@@ -19714,7 +18871,7 @@ var init_parser = __esm({
19714
18871
  });
19715
18872
 
19716
18873
  // packages/experience-design-system-cli-legacy/src/analyze/select/command.ts
19717
- import { access as access6, readFile as readFile18 } from "node:fs/promises";
18874
+ import { access as access6, readFile as readFile17 } from "node:fs/promises";
19718
18875
  async function loadAndValidateForReview(sessionId2, projectRoot) {
19719
18876
  const db = openPipelineDb();
19720
18877
  let rawComponents;
@@ -19732,7 +18889,7 @@ async function patchReviewStateWithValidationErrors(sessionId2, errors, opts = {
19732
18889
  let snapshot;
19733
18890
  try {
19734
18891
  await access6(paths.statePath);
19735
- snapshot = JSON.parse(await readFile18(paths.statePath, "utf8"));
18892
+ snapshot = JSON.parse(await readFile17(paths.statePath, "utf8"));
19736
18893
  } catch {
19737
18894
  snapshot = await loadAndValidateForReview(sessionId2, void 0);
19738
18895
  snapshot = await ensureRefineSession(sessionId2, artifactsRoot, snapshot);
@@ -19783,7 +18940,7 @@ async function rejectComponentsByName(sessionId2, names, opts = {}) {
19783
18940
  const nameSet = new Set(names);
19784
18941
  let snapshot;
19785
18942
  try {
19786
- snapshot = JSON.parse(await readFile18(paths.statePath, "utf8"));
18943
+ snapshot = JSON.parse(await readFile17(paths.statePath, "utf8"));
19787
18944
  } catch {
19788
18945
  return;
19789
18946
  }
@@ -19882,9 +19039,9 @@ function spawnGenerateChild(opts) {
19882
19039
  stderr += chunk;
19883
19040
  opts.onStderr?.(chunk);
19884
19041
  });
19885
- const donePromise = new Promise((resolve22) => {
19042
+ const donePromise = new Promise((resolve20) => {
19886
19043
  child.on("close", (code, signal) => {
19887
- resolve22({
19044
+ resolve20({
19888
19045
  exitCode: code ?? 0,
19889
19046
  signal: signal ?? null,
19890
19047
  stdout,
@@ -19892,7 +19049,7 @@ function spawnGenerateChild(opts) {
19892
19049
  });
19893
19050
  });
19894
19051
  child.on("error", (err) => {
19895
- resolve22({
19052
+ resolve20({
19896
19053
  exitCode: 1,
19897
19054
  signal: null,
19898
19055
  stdout,
@@ -28030,9 +27187,6 @@ function shouldGenerateAfterCredentialsValidated(opts) {
28030
27187
  function shouldSkipFinalReviewAfterCredentials(state) {
28031
27188
  return state.finalReviewPassed && state.generateSessionId != null;
28032
27189
  }
28033
- function resolveNoCacheForGenerate(opts) {
28034
- return opts.cliNoCache;
28035
- }
28036
27190
  function shouldBypassPreview(state) {
28037
27191
  return state.credentialsSkipped === true;
28038
27192
  }
@@ -28059,70 +27213,43 @@ var init_wizard_state_transitions = __esm({
28059
27213
  async function runSelectionAgent(options) {
28060
27214
  const db = openPipelineDb();
28061
27215
  let components;
28062
- const cachedDecisions = /* @__PURE__ */ new Map();
28063
- const cliVersion2 = await getCliCacheVersion();
28064
- const promptHash = await hashPromptForSkill(
28065
- "select",
28066
- options.agent,
28067
- options.model,
28068
- options.promptPath,
28069
- [SELECT_PAYLOAD_FORMAT],
28070
- options.promptText
28071
- );
28072
27216
  try {
28073
27217
  components = loadRawComponents(db, options.sessionId);
28074
- if (!options.noCache) {
28075
- for (const component of components) {
28076
- const componentHash = hashComponentShape(component);
28077
- const cached = lookupSelectCache(db, componentHash, promptHash, cliVersion2);
28078
- if (cached) {
28079
- cachedDecisions.set(component.name, {
28080
- decision: cached.decision,
28081
- reason: cached.reason
28082
- });
28083
- }
28084
- }
28085
- }
28086
27218
  } finally {
28087
27219
  db.close();
28088
27220
  }
28089
27221
  if (components.length === 0) return;
28090
- const componentsToRun = components.filter((component) => !cachedDecisions.has(component.name));
28091
- let calls = [];
28092
- if (componentsToRun.length > 0) {
28093
- const invoker2 = createLocalCliAgentInvoker({
28094
- onDebugEvent: (name, payload) => getDebugLogger().event("agent", name, payload)
28095
- });
28096
- const selectBuckets = bucketComponentsProps(componentsToRun);
28097
- for (const assignment of selectBuckets) {
28098
- getDebugLogger().event("analyze", "prop-buckets.select", { ...assignment });
28099
- }
28100
- const prompt = await buildPrompt({
28101
- skill: "select",
28102
- mode: "autonomous",
28103
- rawComponentsInline: JSON.stringify(
28104
- componentsToRun.map((component) => ({ ...component, props: component.props.map(stripPropProvenance) })),
28105
- null,
28106
- 2
28107
- ),
28108
- propBucketsInline: JSON.stringify(selectBuckets),
28109
- outDir: process.cwd(),
28110
- ...options.promptText !== void 0 ? { skillContentOverride: options.promptText } : {},
28111
- ...options.promptText === void 0 && options.promptPath ? { skillPathOverride: options.promptPath } : {}
28112
- });
28113
- const { result } = await invokeAgentWithOutput(
28114
- invoker2,
28115
- { agent: options.agent, model: options.model, prompt, timeoutMs: DEFAULT_TIMEOUT_MS4 },
28116
- false
28117
- );
28118
- if (result.timedOut) throw new Error("selection agent timed out");
28119
- if (result.exitCode !== 0) throw new Error(`selection agent exited with code ${result.exitCode}`);
28120
- const parsed = parseSelectToolCallLines(result.stdout);
28121
- for (const warning of parsed.warnings) process.stderr.write(`Warning: selection agent: ${warning}
28122
- `);
28123
- calls = parsed.calls;
27222
+ const invoker2 = createLocalCliAgentInvoker({
27223
+ onDebugEvent: (name, payload) => getDebugLogger().event("agent", name, payload)
27224
+ });
27225
+ const selectBuckets = bucketComponentsProps(components);
27226
+ for (const assignment of selectBuckets) {
27227
+ getDebugLogger().event("analyze", "prop-buckets.select", { ...assignment });
28124
27228
  }
28125
- const byName = new Map(calls.map((call) => [call.name, call]));
27229
+ const prompt = await buildPrompt({
27230
+ skill: "select",
27231
+ mode: "autonomous",
27232
+ rawComponentsInline: JSON.stringify(
27233
+ components.map((component) => ({ ...component, props: component.props.map(stripPropProvenance) })),
27234
+ null,
27235
+ 2
27236
+ ),
27237
+ propBucketsInline: JSON.stringify(selectBuckets),
27238
+ outDir: process.cwd(),
27239
+ ...options.promptText !== void 0 ? { skillContentOverride: options.promptText } : {},
27240
+ ...options.promptText === void 0 && options.promptPath ? { skillPathOverride: options.promptPath } : {}
27241
+ });
27242
+ const { result } = await invokeAgentWithOutput(
27243
+ invoker2,
27244
+ { agent: options.agent, model: options.model, prompt, timeoutMs: DEFAULT_TIMEOUT_MS4 },
27245
+ false
27246
+ );
27247
+ if (result.timedOut) throw new Error("selection agent timed out");
27248
+ if (result.exitCode !== 0) throw new Error(`selection agent exited with code ${result.exitCode}`);
27249
+ const parsed = parseSelectToolCallLines(result.stdout);
27250
+ for (const warning of parsed.warnings) process.stderr.write(`Warning: selection agent: ${warning}
27251
+ `);
27252
+ const byName = new Map(parsed.calls.map((call) => [call.name, call]));
28126
27253
  const writeDb = openPipelineDb();
28127
27254
  try {
28128
27255
  writeDb.exec("BEGIN");
@@ -28130,27 +27257,15 @@ async function runSelectionAgent(options) {
28130
27257
  `UPDATE raw_components SET status = ?, reject_reason = ? WHERE session_id = ? AND component_id = ?`
28131
27258
  );
28132
27259
  for (const component of components) {
28133
- const cached = cachedDecisions.get(component.name);
28134
27260
  const call = byName.get(component.name);
28135
- if (!cached && !call) continue;
28136
- const rejected = cached ? cached.decision === "rejected" : call.tool === "reject_component";
28137
- const reason = cached ? cached.reason : call.reason ?? null;
27261
+ if (!call) continue;
27262
+ const rejected = call.tool === "reject_component";
28138
27263
  update.run(
28139
27264
  rejected ? "rejected" : "accepted",
28140
- rejected ? reason : null,
27265
+ rejected ? call.reason ?? null : null,
28141
27266
  options.sessionId,
28142
27267
  component.component_id
28143
27268
  );
28144
- if (!cached) {
28145
- storeSelectCache(
28146
- writeDb,
28147
- hashComponentShape(component),
28148
- promptHash,
28149
- cliVersion2,
28150
- rejected ? "rejected" : "accepted",
28151
- rejected ? reason : null
28152
- );
28153
- }
28154
27269
  }
28155
27270
  writeDb.exec("COMMIT");
28156
27271
  } catch (error) {
@@ -28160,7 +27275,7 @@ async function runSelectionAgent(options) {
28160
27275
  writeDb.close();
28161
27276
  }
28162
27277
  }
28163
- var SELECT_PAYLOAD_FORMAT, DEFAULT_TIMEOUT_MS4;
27278
+ var DEFAULT_TIMEOUT_MS4;
28164
27279
  var init_run_selection_agent = __esm({
28165
27280
  "packages/experience-design-system-cli-legacy/src/import/tui/run-selection-agent.ts"() {
28166
27281
  "use strict";
@@ -28169,8 +27284,6 @@ var init_run_selection_agent = __esm({
28169
27284
  init_debug_logger();
28170
27285
  init_agent_output();
28171
27286
  init_db();
28172
- init_cache_keys();
28173
- SELECT_PAYLOAD_FORMAT = "prop-buckets-v1";
28174
27287
  DEFAULT_TIMEOUT_MS4 = Number(process.env.EDS_AGENT_TIMEOUT_MS ?? 5 * 60 * 1e3);
28175
27288
  }
28176
27289
  });
@@ -28189,7 +27302,7 @@ __export(WizardApp_exports, {
28189
27302
  });
28190
27303
  import { useEffect as useEffect15, useRef as useRef10, useState as useState23 } from "react";
28191
27304
  import { Box as Box42, Text as Text46 } from "ink";
28192
- import { join as join23, resolve as resolve18 } from "node:path";
27305
+ import { join as join23, resolve as resolve17 } from "node:path";
28193
27306
  import { appendFileSync as appendFileSync2, writeFileSync } from "node:fs";
28194
27307
  import { access as access7, stat as stat5, writeFile as writeFile6 } from "node:fs/promises";
28195
27308
  import { tmpdir } from "node:os";
@@ -28202,28 +27315,21 @@ function buildGenerateComponentsArgs(opts) {
28202
27315
  if (opts.tokensPath) args.push("--tokens", opts.tokensPath);
28203
27316
  if (opts.model) args.push("--model", opts.model);
28204
27317
  if (opts.bedrock) args.push("--bedrock");
28205
- if (opts.noCache) args.push("--no-cache");
28206
27318
  if (opts.generatePromptPath) args.push("--generate-prompt-path", opts.generatePromptPath);
28207
27319
  for (const prompt of opts.promptOverrides ?? []) args.push("--prompt", prompt);
28208
27320
  if (opts.existingEntitiesPath) args.push("--existing-entities-path", opts.existingEntitiesPath);
28209
- if (opts.restoreCache) args.push("--restore-cache");
28210
- if (opts.cachedComponents && opts.cachedComponents.length > 0) {
28211
- args.push("--cached-components", JSON.stringify(opts.cachedComponents));
28212
- }
28213
27321
  return args;
28214
27322
  }
28215
27323
  function buildGenerateTokensArgs(opts) {
28216
27324
  const args = [findCliPath(), "__generate", "tokens", "--agent", opts.agent, "--raw-tokens", opts.rawTokensPath];
28217
27325
  if (opts.model) args.push("--model", opts.model);
28218
27326
  if (opts.bedrock) args.push("--bedrock");
28219
- if (opts.noCache) args.push("--no-cache");
28220
27327
  for (const prompt of opts.promptOverrides ?? []) args.push("--prompt", prompt);
28221
27328
  return args;
28222
27329
  }
28223
27330
  function buildMapTokensArgs(opts) {
28224
27331
  const args = ["map", "tokens", "--session", opts.sessionId, "--agent", opts.agent];
28225
27332
  if (opts.model) args.push("--model", opts.model);
28226
- if (opts.noCache) args.push("--no-cache");
28227
27333
  if (opts.skipAgent) args.push("--skip-agent");
28228
27334
  for (const prompt of opts.promptOverrides ?? []) args.push("--prompt", prompt);
28229
27335
  if (opts.existingEntitiesPath) args.push("--existing-entities-path", opts.existingEntitiesPath);
@@ -28315,7 +27421,6 @@ function WizardApp({
28315
27421
  initialProjectPath,
28316
27422
  host,
28317
27423
  promptOverrides,
28318
- noCache = false,
28319
27424
  livePreview = true,
28320
27425
  generatePromptPath,
28321
27426
  skipMapTokens = false,
@@ -28340,7 +27445,6 @@ function WizardApp({
28340
27445
  });
28341
27446
  const allowEmptyDeleteAllRef = useRef10(false);
28342
27447
  const generateChildRef = useRef10(null);
28343
- const generationCachePreflightRef = useRef10(null);
28344
27448
  const selectionToReviewStartedAtRef = useRef10(null);
28345
27449
  const credentialsValidationIdRef = useRef10(0);
28346
27450
  const pendingCredentialValidationRef = useRef10(null);
@@ -28355,9 +27459,8 @@ function WizardApp({
28355
27459
  const existingEntitiesPromiseRef = useRef10(null);
28356
27460
  const generatePromiseRef = useRef10(null);
28357
27461
  const rawTokensEntryReady = !!initialRawTokensPath;
28358
- const effectiveNoCache = resolveNoCacheForGenerate({ cliNoCache: noCache });
28359
27462
  const initialStepResolved = rawTokensEntryReady ? initialProjectPath ? "path-validation" : "credentials" : initialProjectPath ? "token-input" : "welcome";
28360
- const initialOutDir = initialProjectPath ? join23(resolve18(initialProjectPath), ".contentful") : "";
27463
+ const initialOutDir = initialProjectPath ? join23(resolve17(initialProjectPath), ".contentful") : "";
28361
27464
  const [state, setState] = useState23({
28362
27465
  step: initialStepResolved,
28363
27466
  agent: initialAgent ?? "claude",
@@ -28533,14 +27636,13 @@ If you are using AWS Bedrock, run:
28533
27636
  if (!deferStep) update({ step: nextStep });
28534
27637
  return true;
28535
27638
  };
28536
- const runGenerateTokens = async (rawTokensPath, outDir, forceRegenerate = false) => {
27639
+ const runGenerateTokens = async (rawTokensPath, outDir) => {
28537
27640
  update({ tokenGenerationStatus: "running" });
28538
27641
  const tokenArgs = buildGenerateTokensArgs({
28539
27642
  rawTokensPath,
28540
27643
  agent: state.agent,
28541
27644
  ...state.agentModel ? { model: state.agentModel } : {},
28542
27645
  ...state.bedrock ? { bedrock: true } : {},
28543
- noCache: effectiveNoCache || forceRegenerate,
28544
27646
  promptOverrides
28545
27647
  });
28546
27648
  const result = await runSpawnedCli(tokenArgs);
@@ -28589,7 +27691,6 @@ If you are using AWS Bedrock, run:
28589
27691
  const timer = startWizardTimer("token-mapping", {
28590
27692
  sessionId: sessionId2,
28591
27693
  silent,
28592
- noCache: effectiveNoCache,
28593
27694
  skipAgent: skipMapTokens
28594
27695
  });
28595
27696
  let mappablePropCount = 0;
@@ -28598,7 +27699,7 @@ If you are using AWS Bedrock, run:
28598
27699
  const db = openPipelineDb();
28599
27700
  try {
28600
27701
  if (state.tokenSessionId && state.tokenSessionId !== sessionId2) {
28601
- copyTokensFromCache(db, state.tokenSessionId, sessionId2);
27702
+ copyTokensBetweenSessions(db, state.tokenSessionId, sessionId2);
28602
27703
  } else if (!state.tokenSessionId && state.tokensPath) {
28603
27704
  const tokens = await readTokensFromPath("tokens", state.tokensPath);
28604
27705
  storeDtcgTokens(db, sessionId2, [], tokens);
@@ -28638,7 +27739,6 @@ If you are using AWS Bedrock, run:
28638
27739
  sessionId: sessionId2,
28639
27740
  agent: state.agent,
28640
27741
  ...state.agentModel ? { model: state.agentModel } : {},
28641
- noCache: effectiveNoCache,
28642
27742
  skipAgent: skipMapTokens,
28643
27743
  promptOverrides,
28644
27744
  ...state.existingEntitiesPath ? { existingEntitiesPath: state.existingEntitiesPath } : {}
@@ -28718,7 +27818,7 @@ If you are using AWS Bedrock, run:
28718
27818
  return promise;
28719
27819
  };
28720
27820
  const runExtract = async (projectPath, showProgress = true) => {
28721
- const outDir = join23(resolve18(projectPath), ".contentful");
27821
+ const outDir = join23(resolve17(projectPath), ".contentful");
28722
27822
  const existingEntitiesExpected = !state.credentialsSkipped && Boolean(state.spaceId && state.environmentId && state.cmaToken && projectPath);
28723
27823
  update({
28724
27824
  ...showProgress ? { step: "extracting" } : {},
@@ -28733,10 +27833,6 @@ If you are using AWS Bedrock, run:
28733
27833
  });
28734
27834
  const existingEntitiesPromise = startExistingEntitiesFetch(projectPath, outDir);
28735
27835
  const extractArgs = [findCliPath(), "__extract", "--project", projectPath];
28736
- if (effectiveNoCache) extractArgs.push("--composition-refresh", "--no-cache");
28737
- for (const p of promptOverrides ?? []) extractArgs.push("--prompt", p);
28738
- if (state.agent) extractArgs.push("--agent", state.agent);
28739
- if (state.bedrock) extractArgs.push("--bedrock");
28740
27836
  let selectionPromptText;
28741
27837
  let selectionPromptPath;
28742
27838
  try {
@@ -28745,7 +27841,7 @@ If you are using AWS Bedrock, run:
28745
27841
  const selectOverride = overrides.get("select");
28746
27842
  if (selectOverride?.kind === "text") selectionPromptText = selectOverride.value;
28747
27843
  if (selectOverride?.kind === "path") {
28748
- selectionPromptPath = resolve18(selectOverride.value);
27844
+ selectionPromptPath = resolve17(selectOverride.value);
28749
27845
  await resolvePromptOverride(selectOverride);
28750
27846
  }
28751
27847
  } catch (error) {
@@ -28769,8 +27865,7 @@ If you are using AWS Bedrock, run:
28769
27865
  agent: state.agent,
28770
27866
  ...state.agentModel ? { model: state.agentModel } : {},
28771
27867
  ...selectionPromptText !== void 0 ? { promptText: selectionPromptText } : {},
28772
- ...selectionPromptPath ? { promptPath: selectionPromptPath } : {},
28773
- noCache: effectiveNoCache
27868
+ ...selectionPromptPath ? { promptPath: selectionPromptPath } : {}
28774
27869
  });
28775
27870
  })().catch((error) => {
28776
27871
  selectionError = error;
@@ -28915,136 +28010,17 @@ Make sure this path contains TypeScript/React/Vue component files (.tsx, .ts, .v
28915
28010
  generateProgress: null
28916
28011
  }));
28917
28012
  };
28918
- const buildGenerateOptions = (extractSessionId, tokensPath, generatePromptPath2, cachedComponents) => ({
28013
+ const buildGenerateOptions = (extractSessionId, tokensPath, generatePromptPath2) => ({
28919
28014
  sessionId: extractSessionId,
28920
28015
  tokensPath,
28921
28016
  agent: state.agent,
28922
28017
  ...state.agentModel ? { model: state.agentModel } : {},
28923
28018
  ...state.bedrock ? { bedrock: true } : {},
28924
- noCache: effectiveNoCache,
28925
28019
  ...state.existingEntitiesPath ? { existingEntitiesPath: state.existingEntitiesPath } : {},
28926
28020
  ...generatePromptPath2 ? { generatePromptPath: generatePromptPath2 } : {},
28927
- promptOverrides,
28928
- ...cachedComponents && cachedComponents.length > 0 ? { cachedComponents } : {}
28021
+ promptOverrides
28929
28022
  });
28930
- const buildGenerateArgs = (extractSessionId, tokensPath, generatePromptPath2, cachedComponents) => buildGenerateProcessArgs(buildGenerateOptions(extractSessionId, tokensPath, generatePromptPath2, cachedComponents));
28931
- const buildGenerateCliArgs = (extractSessionId, tokensPath, generatePromptPath2, cachedComponents) => buildGenerateComponentsArgs(
28932
- buildGenerateOptions(extractSessionId, tokensPath, generatePromptPath2, cachedComponents)
28933
- );
28934
- const checkGenerateCache = async (extractSessionId, tokensPath) => {
28935
- const timer = startWizardTimer("generation-cache-status", {
28936
- sessionId: extractSessionId,
28937
- noCache: effectiveNoCache
28938
- });
28939
- if (effectiveNoCache) {
28940
- finishWizardTimer("generation-cache-status", timer, { status: "skipped" });
28941
- return false;
28942
- }
28943
- const result = await runCli([...buildGenerateCliArgs(extractSessionId, tokensPath), "--cache-status"]);
28944
- const hit = result.exitCode === 0 && /^cache-status=hit$/m.test(result.stdout);
28945
- finishWizardTimer("generation-cache-status", timer, {
28946
- status: hit ? "hit" : "miss",
28947
- exitCode: result.exitCode,
28948
- ...result.exitCode !== 0 ? { stderrTail: result.stderr.trim().slice(-500) } : {}
28949
- });
28950
- return hit;
28951
- };
28952
- const checkGenerateCacheComponents = async (extractSessionId, tokensPath, restoreCache = false) => {
28953
- const timer = startWizardTimer("generation-cache-components", {
28954
- sessionId: extractSessionId,
28955
- restoreCache,
28956
- noCache: effectiveNoCache
28957
- });
28958
- if (effectiveNoCache) {
28959
- finishWizardTimer("generation-cache-components", timer, { status: "skipped" });
28960
- return /* @__PURE__ */ new Set();
28961
- }
28962
- const args = [...buildGenerateCliArgs(extractSessionId, tokensPath), "--cache-status"];
28963
- if (restoreCache) args.push("--restore-cache");
28964
- const result = await runCli(args);
28965
- if (result.exitCode !== 0) {
28966
- finishWizardTimer("generation-cache-components", timer, {
28967
- status: "error",
28968
- exitCode: result.exitCode,
28969
- stderrTail: result.stderr.trim().slice(-500)
28970
- });
28971
- return /* @__PURE__ */ new Set();
28972
- }
28973
- const line = /^cache-components=(.+)$/m.exec(result.stdout)?.[1];
28974
- if (!line) {
28975
- finishWizardTimer("generation-cache-components", timer, {
28976
- status: "missing-output",
28977
- exitCode: result.exitCode,
28978
- cachedCount: 0
28979
- });
28980
- return /* @__PURE__ */ new Set();
28981
- }
28982
- try {
28983
- const names = JSON.parse(line);
28984
- const cachedNames = new Set(
28985
- Array.isArray(names) ? names.filter((name) => typeof name === "string") : []
28986
- );
28987
- finishWizardTimer("generation-cache-components", timer, {
28988
- status: "complete",
28989
- exitCode: result.exitCode,
28990
- cachedCount: cachedNames.size
28991
- });
28992
- return cachedNames;
28993
- } catch {
28994
- finishWizardTimer("generation-cache-components", timer, {
28995
- status: "invalid-output",
28996
- exitCode: result.exitCode,
28997
- cachedCount: 0
28998
- });
28999
- return /* @__PURE__ */ new Set();
29000
- }
29001
- };
29002
- useEffect15(() => {
29003
- 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) {
29004
- return;
29005
- }
29006
- const sessionId2 = state.extractSessionId;
29007
- if (generationCachePreflightRef.current?.sessionId === sessionId2) return;
29008
- const timer = startWizardTimer("generation-cache-preflight", { sessionId: sessionId2 });
29009
- const db = openPipelineDb();
29010
- let generatedNames = null;
29011
- try {
29012
- const rows = db.prepare("SELECT name, status FROM raw_components WHERE session_id = ?").all(sessionId2);
29013
- if (rows.length > 0 && rows.every((row) => row.status === "generated")) {
29014
- generatedNames = new Set(rows.map((row) => row.name));
29015
- }
29016
- } finally {
29017
- db.close();
29018
- }
29019
- if (generatedNames) {
29020
- generationCachePreflightRef.current = { sessionId: sessionId2, promise: Promise.resolve(generatedNames) };
29021
- finishWizardTimer("generation-cache-preflight", timer, {
29022
- status: "complete",
29023
- source: "session-db",
29024
- cachedCount: generatedNames.size
29025
- });
29026
- return;
29027
- }
29028
- const promise = checkGenerateCacheComponents(sessionId2, state.tokensPath, true);
29029
- generationCachePreflightRef.current = { sessionId: sessionId2, promise };
29030
- void promise.then((cachedNames) => {
29031
- finishWizardTimer("generation-cache-preflight", timer, {
29032
- status: "complete",
29033
- source: "cache-status",
29034
- cachedCount: cachedNames.size
29035
- });
29036
- });
29037
- }, [
29038
- state.step,
29039
- state.extractSessionId,
29040
- state.tokensPath,
29041
- state.rawTokensPath,
29042
- state.tokenGenerationStatus,
29043
- state.selectionAgentStatus,
29044
- state.compositionPhase,
29045
- state.existingEntitiesStatus,
29046
- state.existingEntitiesPath
29047
- ]);
28023
+ const buildGenerateArgs = (extractSessionId, tokensPath, generatePromptPath2) => buildGenerateProcessArgs(buildGenerateOptions(extractSessionId, tokensPath, generatePromptPath2));
29048
28024
  const startGeneratePrefetch = (extractSessionId, tokensPath) => {
29049
28025
  const args = buildGenerateArgs(extractSessionId, tokensPath);
29050
28026
  let progressCursor = null;
@@ -29099,14 +28075,13 @@ Make sure this path contains TypeScript/React/Vue component files (.tsx, .ts, .v
29099
28075
  });
29100
28076
  return donePromise;
29101
28077
  };
29102
- const runGenerate = async (extractSessionId, tokensPath, acceptedCount, suppressScreen = false, cachedComponents = []) => {
28078
+ const runGenerate = async (extractSessionId, tokensPath, acceptedCount, suppressScreen = false) => {
29103
28079
  const timer = startWizardTimer("component-generation", {
29104
28080
  sessionId: extractSessionId,
29105
28081
  acceptedCount,
29106
- suppressScreen,
29107
- noCache: effectiveNoCache
28082
+ suppressScreen
29108
28083
  });
29109
- const args = buildGenerateArgs(extractSessionId, tokensPath, generatePromptPath, cachedComponents);
28084
+ const args = buildGenerateArgs(extractSessionId, tokensPath, generatePromptPath);
29110
28085
  let progressCursor = state.generateProgress;
29111
28086
  const { donePromise } = spawnGenerateChild({
29112
28087
  command: "node",
@@ -29176,25 +28151,6 @@ Make sure this path contains TypeScript/React/Vue component files (.tsx, .ts, .v
29176
28151
  finishSelectionToReviewTimer("error");
29177
28152
  }
29178
28153
  };
29179
- const finishCachedGeneration = async (sessionId2, acceptedCount) => {
29180
- if (await runMapTokens2(sessionId2, true)) {
29181
- finishSelectionToReviewTimer("cached");
29182
- update(
29183
- {
29184
- acceptedCount,
29185
- autoRejectedCount: 0,
29186
- generateSessionId: sessionId2,
29187
- generatedCount: acceptedCount,
29188
- generateProgress: null,
29189
- mapTokensStatus: "complete",
29190
- step: "final-review"
29191
- },
29192
- { clearScreen: false }
29193
- );
29194
- } else {
29195
- finishSelectionToReviewTimer("error");
29196
- }
29197
- };
29198
28154
  const advanceToPushFlow = (generatedAcceptedCount) => {
29199
28155
  update({ generatedAcceptedCount });
29200
28156
  void runSaveAndPush();
@@ -29379,14 +28335,8 @@ Make sure this path contains TypeScript/React/Vue component files (.tsx, .ts, .v
29379
28335
  }
29380
28336
  }
29381
28337
  if (await runAgentAuthCheck("generating", true)) {
29382
- const cacheHit = await checkGenerateCache(sid, state.tokensPath);
29383
- if (cacheHit) {
29384
- update({ step: "generating" });
29385
- void finishCachedGeneration(sid, state.acceptedCount);
29386
- } else {
29387
- update({ step: "generating" });
29388
- void runGenerate(sid, state.tokensPath, state.acceptedCount);
29389
- }
28338
+ update({ step: "generating" });
28339
+ void runGenerate(sid, state.tokensPath, state.acceptedCount);
29390
28340
  }
29391
28341
  return;
29392
28342
  }
@@ -29750,7 +28700,7 @@ If using a custom host configuration, make sure the space exists on that host.`
29750
28700
  });
29751
28701
  return { ok: false };
29752
28702
  }
29753
- await new Promise((resolve22) => setTimeout(resolve22, SAVE_CONFIRMATION_DELAY_MS));
28703
+ await new Promise((resolve20) => setTimeout(resolve20, SAVE_CONFIRMATION_DELAY_MS));
29754
28704
  update(nextStateAfterPrint({ skipGate: opts.skipGate, componentsPath }));
29755
28705
  return { ok: true };
29756
28706
  };
@@ -29827,12 +28777,6 @@ If using a custom host configuration, make sure the space exists on that host.`
29827
28777
  tokenReuseChecked.current = true;
29828
28778
  const tokenNextStep = state.projectPath ? "path-validation" : "credentials";
29829
28779
  const existingTokensPath = join23(state.outDir, "tokens.json");
29830
- if (effectiveNoCache) {
29831
- tokenGenerationPromiseRef.current = runAgentAuthCheck(tokenNextStep).then(
29832
- (ok2) => ok2 ? runGenerateTokens(state.rawTokensPath, state.outDir) : false
29833
- );
29834
- return;
29835
- }
29836
28780
  (async () => {
29837
28781
  try {
29838
28782
  await access7(existingTokensPath);
@@ -29916,7 +28860,7 @@ If using a custom host configuration, make sure the space exists on that host.`
29916
28860
  const tokenNextStep = state.projectPath ? "path-validation" : "credentials";
29917
28861
  update({ step: tokenNextStep });
29918
28862
  if (await runAgentAuthCheck(tokenNextStep)) {
29919
- tokenGenerationPromiseRef.current = runGenerateTokens(state.rawTokensPath, state.outDir, true);
28863
+ tokenGenerationPromiseRef.current = runGenerateTokens(state.rawTokensPath, state.outDir);
29920
28864
  }
29921
28865
  },
29922
28866
  onQuit: () => process.exit(0)
@@ -29950,7 +28894,7 @@ If using a custom host configuration, make sure the space exists on that host.`
29950
28894
  );
29951
28895
  case "extracting": {
29952
28896
  const ep = state.extractProgress;
29953
- const compositionComplete = state.compositionPhase === "done" || state.compositionPhase === "cache-hit";
28897
+ const compositionComplete = state.compositionPhase === "done";
29954
28898
  const tokenGenerationComplete = !state.rawTokensPath || state.tokenGenerationStatus === "complete";
29955
28899
  const extractionTasksComplete = ep !== null && ep.totalFiles > 0 && compositionComplete && state.selectionAgentStatus === "complete" && tokenGenerationComplete && state.existingEntitiesStatus !== "running";
29956
28900
  if (extractionTasksComplete) return null;
@@ -29965,7 +28909,7 @@ If using a custom host configuration, make sure the space exists on that host.`
29965
28909
  extractDetail = "Scanning files...";
29966
28910
  }
29967
28911
  const selectionDetail = state.selectionAgentStatus === "complete" ? "Selection agent complete" : `Filtering component selection via ${state.agent}...`;
29968
- 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}...`;
28912
+ const compositionDetail = compositionComplete ? "Composition mapping complete" : "Mapping composition from source call sites...";
29969
28913
  return /* @__PURE__ */ jsx50(
29970
28914
  RunningStep,
29971
28915
  {
@@ -30015,29 +28959,6 @@ If using a custom host configuration, make sure the space exists on that host.`
30015
28959
  acceptedCount: decisions.accepted.length,
30016
28960
  rejectedCount: decisions.rejected.length
30017
28961
  }) : null;
30018
- const preflight = generationCachePreflightRef.current;
30019
- const cachePromise = preflight?.sessionId === sessionId2 ? preflight.promise : checkGenerateCacheComponents(sessionId2, state.tokensPath, true);
30020
- if (!preflight || preflight.sessionId !== sessionId2) {
30021
- generationCachePreflightRef.current = { sessionId: sessionId2, promise: cachePromise };
30022
- }
30023
- const cacheWaitStartedAt = startWizardTimer("selection-cache-restoration-wait", {
30024
- sessionId: sessionId2,
30025
- preflight: Boolean(preflight?.sessionId === sessionId2)
30026
- });
30027
- try {
30028
- const cachedNames = await cachePromise;
30029
- finishWizardTimer("selection-cache-restoration-wait", cacheWaitStartedAt, {
30030
- status: "complete",
30031
- cachedCount: cachedNames.size
30032
- });
30033
- } catch (error) {
30034
- finishWizardTimer("selection-cache-restoration-wait", cacheWaitStartedAt, {
30035
- status: "error",
30036
- error: error instanceof Error ? error.message : String(error)
30037
- });
30038
- finishSelectionToReviewTimer("error");
30039
- throw error;
30040
- }
30041
28962
  await runScopeGate({
30042
28963
  sessionId: sessionId2,
30043
28964
  decisions,
@@ -30046,35 +28967,12 @@ If using a custom host configuration, make sure the space exists on that host.`
30046
28967
  if (shouldGenerateAfterScopeGate({ acceptedCount })) {
30047
28968
  const authPromise = runAgentAuthCheck("generating", true);
30048
28969
  if (await authPromise) {
30049
- const comparisonStartedAt = startWizardTimer("generation-cache-set-comparison", {
30050
- sessionId: sid,
30051
- acceptedCount: decisions?.accepted.length ?? 0
30052
- });
30053
- let cachedNames = await cachePromise;
30054
- const acceptedNames = decisions?.accepted ?? [];
30055
- let cacheHit = !effectiveNoCache && acceptedNames.length > 0 && acceptedNames.every((name) => cachedNames.has(name));
30056
- if (!cacheHit && !effectiveNoCache && acceptedNames.length > 0) {
30057
- cachedNames = await checkGenerateCacheComponents(sid, state.tokensPath, true);
30058
- cacheHit = acceptedNames.every((name) => cachedNames.has(name));
30059
- }
30060
- finishWizardTimer("generation-cache-set-comparison", comparisonStartedAt, {
30061
- status: "complete",
30062
- cacheHit,
30063
- cachedCount: cachedNames.size,
30064
- acceptedCount: acceptedNames.length
28970
+ update({
28971
+ step: "generating",
28972
+ generateProgress: null,
28973
+ acceptedCount
30065
28974
  });
30066
- if (cacheHit) {
30067
- void finishCachedGeneration(sid, acceptedCount);
30068
- } else {
30069
- const acceptedNameSet = new Set(acceptedNames);
30070
- const restoredCachedNames = [...cachedNames].filter((name) => acceptedNameSet.has(name));
30071
- update({
30072
- step: "generating",
30073
- generateProgress: null,
30074
- acceptedCount
30075
- });
30076
- void runGenerate(sid, state.tokensPath, acceptedCount, false, restoredCachedNames);
30077
- }
28975
+ void runGenerate(sid, state.tokensPath, acceptedCount);
30078
28976
  } else {
30079
28977
  finishSelectionToReviewTimer("error");
30080
28978
  }
@@ -30440,7 +29338,7 @@ function registerImportCommand(program) {
30440
29338
  "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",
30441
29339
  (v, acc) => [...acc, v],
30442
29340
  []
30443
- ).option("--no-cache", "Re-run all steps even if output already exists").action(async (opts) => {
29341
+ ).action(async (opts) => {
30444
29342
  const interactiveTerminalSupported = getInteractiveTerminalSupport().supported;
30445
29343
  if (opts.tokens !== void 0) {
30446
29344
  const { access: access9 } = await import("node:fs/promises");
@@ -30477,7 +29375,6 @@ function registerImportCommand(program) {
30477
29375
  ...resolvedModel ? { initialModel: resolvedModel } : {},
30478
29376
  initialProjectPath: opts.project !== "." ? normalizePath(opts.project) : void 0,
30479
29377
  ...buildCompositionForwardingOptions(opts),
30480
- noCache: opts.cache === false,
30481
29378
  skipMapTokens: false,
30482
29379
  livePreview: true,
30483
29380
  generatePromptPath: creds.generatePromptPath,
@@ -30565,7 +29462,7 @@ async function pathExists3(path) {
30565
29462
  return access8(path).then(() => true).catch(() => false);
30566
29463
  }
30567
29464
  function runSpawn(cmd, args, opts = {}) {
30568
- return new Promise((resolve22) => {
29465
+ return new Promise((resolve20) => {
30569
29466
  const child = spawn6(cmd, args, {
30570
29467
  cwd: opts.cwd,
30571
29468
  env: opts.env ?? process.env,
@@ -30577,7 +29474,7 @@ function runSpawn(cmd, args, opts = {}) {
30577
29474
  const settle = (result) => {
30578
29475
  if (settled) return;
30579
29476
  settled = true;
30580
- resolve22(result);
29477
+ resolve20(result);
30581
29478
  };
30582
29479
  child.on("error", (err) => settle({ exitCode: 1, stdout: "", stderr: err.message }));
30583
29480
  child.stdout.on("data", (d) => {
@@ -31778,13 +30675,13 @@ function PrerequisitesScreen({
31778
30675
  const driver = {
31779
30676
  ...base,
31780
30677
  emit: (event) => setEvents((current) => [...current, event]),
31781
- confirm: (question, defaultYes = true) => new Promise((resolve22) => {
30678
+ confirm: (question, defaultYes = true) => new Promise((resolve20) => {
31782
30679
  setConfirm({
31783
30680
  question,
31784
30681
  defaultYes,
31785
30682
  resolve: (answer) => {
31786
30683
  setConfirm(null);
31787
- resolve22(answer);
30684
+ resolve20(answer);
31788
30685
  }
31789
30686
  });
31790
30687
  })
@@ -31859,8 +30756,8 @@ function SetupScreen({
31859
30756
  useEffect21(() => {
31860
30757
  if (startedRef.current) return;
31861
30758
  startedRef.current = true;
31862
- const runScreen = (build) => new Promise((resolve22) => {
31863
- setScreen(build(resolve22));
30759
+ const runScreen = (build) => new Promise((resolve20) => {
30760
+ setScreen(build(resolve20));
31864
30761
  });
31865
30762
  void (async () => {
31866
30763
  const results = [];
@@ -32038,9 +30935,9 @@ var init_command8 = __esm({
32038
30935
  function rank(p) {
32039
30936
  if (p === "typed-slot") return 1;
32040
30937
  if (p === "structural") return 2;
32041
- if (p === "manifest") return 3;
32042
- if (p === "doc") return 4;
32043
- if (p.startsWith("adapter:")) return 5;
30938
+ if (p === "call-site") return 3;
30939
+ if (p === "manifest") return 4;
30940
+ if (p === "doc") return 5;
32044
30941
  return 6;
32045
30942
  }
32046
30943
  function mergeEdges(all) {
@@ -32076,65 +30973,6 @@ var init_merge_edges = __esm({
32076
30973
  }
32077
30974
  });
32078
30975
 
32079
- // packages/experience-design-system-cli-legacy/src/analyze/composition/parse-map-edges.ts
32080
- function parseMapEdges(raw, opts) {
32081
- const edges = [];
32082
- const warnings = [];
32083
- const { componentNames } = opts;
32084
- for (const line of raw.split("\n")) {
32085
- const trimmed = line.trim();
32086
- if (!trimmed.startsWith("{")) continue;
32087
- let obj;
32088
- try {
32089
- obj = JSON.parse(trimmed);
32090
- } catch {
32091
- warnings.push(`unparseable line: ${trimmed.slice(0, 120)}`);
32092
- continue;
32093
- }
32094
- if (typeof obj !== "object" || obj === null || !("tool" in obj)) continue;
32095
- const rec = obj;
32096
- if (!VALID_MAP_TOOL_NAMES.has(rec.tool)) {
32097
- warnings.push(`unknown tool: ${String(rec.tool)}`);
32098
- continue;
32099
- }
32100
- if (typeof rec.parent !== "string" || !rec.parent || typeof rec.child !== "string" || !rec.child) {
32101
- warnings.push("map_edge missing parent/child \u2014 skipped");
32102
- continue;
32103
- }
32104
- const { parent, child } = rec;
32105
- if (!componentNames.has(parent)) {
32106
- warnings.push(`map_edge names unknown component (parent): ${parent} \u2014 skipped`);
32107
- continue;
32108
- }
32109
- if (!componentNames.has(child)) {
32110
- warnings.push(`map_edge names unknown component (child): ${child} \u2014 skipped`);
32111
- continue;
32112
- }
32113
- const edge = { parent, child, provenance: "agent" };
32114
- if (typeof rec.slot === "string" && rec.slot) {
32115
- edge.slot = rec.slot;
32116
- }
32117
- if (rec.confidence !== void 0) {
32118
- if (typeof rec.confidence === "number" && rec.confidence >= 1 && rec.confidence <= 5) {
32119
- edge.confidence = rec.confidence;
32120
- } else {
32121
- warnings.push(
32122
- `map_edge (${parent}\u2192${child}): invalid confidence ${String(rec.confidence)} \u2014 edge kept without confidence`
32123
- );
32124
- }
32125
- }
32126
- edges.push(edge);
32127
- }
32128
- return { edges, warnings };
32129
- }
32130
- var VALID_MAP_TOOL_NAMES;
32131
- var init_parse_map_edges = __esm({
32132
- "packages/experience-design-system-cli-legacy/src/analyze/composition/parse-map-edges.ts"() {
32133
- "use strict";
32134
- VALID_MAP_TOOL_NAMES = /* @__PURE__ */ new Set(["map_edge"]);
32135
- }
32136
- });
32137
-
32138
30976
  // packages/experience-design-system-cli-legacy/src/analyze/composition/apply-mapping.ts
32139
30977
  function applyMapping(components, edges) {
32140
30978
  const warnings = [];
@@ -32194,44 +31032,9 @@ var init_apply_mapping = __esm({
32194
31032
  }
32195
31033
  });
32196
31034
 
32197
- // packages/experience-design-system-cli-legacy/src/analyze/composition/prompt-loader.ts
32198
- import { existsSync as existsSync10, readFileSync as readFileSync10 } from "node:fs";
32199
- import { dirname as dirname17, join as join27, resolve as resolve19 } from "node:path";
32200
- import { fileURLToPath as fileURLToPath3 } from "node:url";
32201
- function resolvePromptPath(fileName) {
32202
- const thisDir = dirname17(fileURLToPath3(import.meta.url));
32203
- let dir = thisDir;
32204
- for (; ; ) {
32205
- const candidate = join27(dir, "prompts");
32206
- if (existsSync10(candidate)) return join27(candidate, fileName);
32207
- const parent = resolve19(dir, "..");
32208
- if (parent === dir) {
32209
- throw new Error(
32210
- `prompt file missing from CLI installation (could not locate prompts/ directory from: ${thisDir})`
32211
- );
32212
- }
32213
- dir = parent;
32214
- }
32215
- }
32216
- function loadPrompt(fileName) {
32217
- const path = resolvePromptPath(fileName);
32218
- try {
32219
- return readFileSync10(path, "utf8");
32220
- } catch {
32221
- throw new Error(`prompt file missing from CLI installation \u2014 try reinstalling the CLI (looked for: ${path})`);
32222
- }
32223
- }
32224
- var init_prompt_loader = __esm({
32225
- "packages/experience-design-system-cli-legacy/src/analyze/composition/prompt-loader.ts"() {
32226
- "use strict";
32227
- }
32228
- });
32229
-
32230
31035
  // packages/experience-design-system-cli-legacy/src/analyze/composition/resolve-mapping.ts
32231
- async function resolveMapping(input) {
32232
- const componentNames = new Set(input.components.map((c2) => c2.name));
31036
+ function resolveMapping(input) {
32233
31037
  const collected = [];
32234
- const agentWarnings = [];
32235
31038
  for (const c2 of input.components) {
32236
31039
  for (const slot of c2.slots) {
32237
31040
  for (const child of slot.allowedComponents ?? []) {
@@ -32249,17 +31052,41 @@ async function resolveMapping(input) {
32249
31052
  if (input.extraEdges) {
32250
31053
  collected.push(...input.extraEdges);
32251
31054
  }
31055
+ for (const evidence of input.sourceCallSiteEvidence ?? []) {
31056
+ collected.push({
31057
+ parent: evidence.parent,
31058
+ child: evidence.child,
31059
+ ...evidence.slot ? { slot: evidence.slot } : {},
31060
+ citation: { sourcePath: evidence.sourcePath, startLine: evidence.startLine, endLine: evidence.endLine },
31061
+ provenance: "call-site"
31062
+ });
31063
+ }
32252
31064
  const coveredParents = new Set(collected.map((e) => e.parent));
32253
31065
  const residueParents = input.components.map((c2) => c2.name).filter((n) => !coveredParents.has(n));
32254
- const shouldRunAgent = input.forceAgent || residueParents.length > 0 && input.files.length > 0;
32255
- if (shouldRunAgent) {
32256
- const prompt = input.buildPrompt ? input.buildPrompt(input.files, [...componentNames]) : defaultPrompt(input.files, [...componentNames], input.promptOverride);
32257
- const raw = await input.runAgentFn({ prompt, files: input.files }) ?? "";
32258
- const parsed = parseMapEdges(raw, { componentNames });
32259
- collected.push(...parsed.edges);
32260
- agentWarnings.push(...parsed.warnings);
32261
- }
31066
+ const debug = getDebugLogger();
31067
+ const countByProvenance = (edges) => {
31068
+ const counts = {};
31069
+ for (const edge of edges) counts[edge.provenance] = (counts[edge.provenance] ?? 0) + 1;
31070
+ return counts;
31071
+ };
31072
+ debug.event("analyze", "composition.pre-merge", {
31073
+ edgeCountsByProvenance: countByProvenance(collected),
31074
+ coveredParents: [...coveredParents].sort(),
31075
+ residueParents,
31076
+ sourceCallSiteAccepted: input.sourceCallSiteEvidence?.length ?? 0,
31077
+ sourceCallSiteRejected: input.sourceCallSiteRejections?.length ?? 0
31078
+ });
32262
31079
  const merged = mergeEdges(collected);
31080
+ debug.event("analyze", "composition.merged", {
31081
+ edgeCountsByProvenance: countByProvenance(merged.edges),
31082
+ conflicts: merged.conflicts,
31083
+ edges: merged.edges.map((edge) => ({
31084
+ parent: edge.parent,
31085
+ child: edge.child,
31086
+ slot: edge.slot ?? null,
31087
+ provenance: edge.provenance
31088
+ }))
31089
+ });
32263
31090
  const base = input.components.map((c2) => ({
32264
31091
  ...c2,
32265
31092
  slots: c2.slots.map((s) => {
@@ -32268,127 +31095,32 @@ async function resolveMapping(input) {
32268
31095
  })
32269
31096
  }));
32270
31097
  const applied = applyMapping(base, merged.edges);
31098
+ debug.event("analyze", "composition.applied", {
31099
+ slots: applied.components.flatMap(
31100
+ (component) => component.slots.filter((slot) => (slot.allowedComponents?.length ?? 0) > 0).map((slot) => ({ component: component.name, slot: slot.name, allowedComponents: slot.allowedComponents }))
31101
+ ),
31102
+ warnings: applied.warnings
31103
+ });
32271
31104
  return {
32272
31105
  components: applied.components,
32273
31106
  edges: merged.edges,
32274
31107
  conflicts: merged.conflicts,
32275
- warnings: [...agentWarnings, ...applied.warnings]
31108
+ warnings: applied.warnings,
31109
+ sourceCallSiteEvidence: [...input.sourceCallSiteEvidence ?? []],
31110
+ sourceCallSiteRejections: [...input.sourceCallSiteRejections ?? []]
32276
31111
  };
32277
31112
  }
32278
- function defaultPrompt(files, componentNames, promptOverride) {
32279
- const fileBlocks = files.map((f) => `--- ${f.path} ---
32280
- ${f.content}`).join("\n\n");
32281
- const instruction = promptOverride?.trim() ? promptOverride.trim() : loadPrompt("composition-edges.md").trim();
32282
- return [
32283
- instruction,
32284
- "",
32285
- 'Emit one JSON object per line, each: {"tool":"map_edge","parent":"<Name>","child":"<Name>","slot"?:"<slot>","confidence"?:1-5,"reason":"<cite the file + declaration>"}.',
32286
- "Use ONLY these exact component names (an edge naming anything else is dropped):",
32287
- componentNames.join(", "),
32288
- "",
32289
- "Candidate files:",
32290
- fileBlocks
32291
- ].join("\n");
32292
- }
32293
31113
  var init_resolve_mapping = __esm({
32294
31114
  "packages/experience-design-system-cli-legacy/src/analyze/composition/resolve-mapping.ts"() {
32295
31115
  "use strict";
32296
31116
  init_merge_edges();
32297
- init_parse_map_edges();
32298
31117
  init_apply_mapping();
32299
- init_prompt_loader();
32300
- }
32301
- });
32302
-
32303
- // packages/experience-design-system-cli-legacy/src/analyze/composition/resolve-mapping-cli.ts
32304
- function resolveCompositionSources(opts) {
32305
- return {
32306
- forceAgent: opts.compositionRefresh === true || opts.noCache === true
32307
- };
32308
- }
32309
- var init_resolve_mapping_cli = __esm({
32310
- "packages/experience-design-system-cli-legacy/src/analyze/composition/resolve-mapping-cli.ts"() {
32311
- "use strict";
32312
- }
32313
- });
32314
-
32315
- // packages/experience-design-system-cli-legacy/src/analyze/composition/candidate-files.ts
32316
- function matchReason(file) {
32317
- const segments = file.path.split("/").filter((s) => s !== "");
32318
- for (const pattern of CANDIDATE_NAME_PATTERNS) {
32319
- if (segments.some((seg) => pattern.test(seg))) {
32320
- return `name:${pattern.source.toLowerCase()}`;
32321
- }
32322
- }
32323
- for (const marker of CANDIDATE_CONTENT_MARKERS) {
32324
- if (file.content.includes(marker)) return `content:${marker}`;
32325
- }
32326
- return void 0;
32327
- }
32328
- function selectCandidateFiles(files) {
32329
- const selected = [];
32330
- const seen = /* @__PURE__ */ new Set();
32331
- for (const file of files) {
32332
- if (seen.has(file.path)) continue;
32333
- const reason = matchReason(file);
32334
- if (reason === void 0) continue;
32335
- seen.add(file.path);
32336
- selected.push({ path: file.path, content: file.content, reason });
32337
- }
32338
- return selected;
32339
- }
32340
- function capCandidatesToPromptBudget(files, budget = PROMPT_CANDIDATE_TOKEN_BUDGET) {
32341
- const ordered = [...files].sort((a, b) => a.content.length - b.content.length || a.path.localeCompare(b.path));
32342
- const kept = [];
32343
- const dropped = [];
32344
- let spent = 0;
32345
- for (const file of ordered) {
32346
- const cost = tokenCost(file);
32347
- if (spent + cost > budget) {
32348
- dropped.push(file);
32349
- continue;
32350
- }
32351
- kept.push(file);
32352
- spent += cost;
32353
- }
32354
- return { kept, dropped };
32355
- }
32356
- function tokenCost(file) {
32357
- return Math.ceil(file.content.length / CHARS_PER_TOKEN);
32358
- }
32359
- var CANDIDATE_NAME_PATTERNS, CANDIDATE_CONTENT_MARKERS, PROMPT_CANDIDATE_TOKEN_BUDGET, CHARS_PER_TOKEN;
32360
- var init_candidate_files = __esm({
32361
- "packages/experience-design-system-cli-legacy/src/analyze/composition/candidate-files.ts"() {
32362
- "use strict";
32363
- CANDIDATE_NAME_PATTERNS = [/mapping/i, /meta/i, /registry/i, /schema/i, /composition/i];
32364
- CANDIDATE_CONTENT_MARKERS = [
32365
- "requiredParent",
32366
- "withParentType",
32367
- "allowedTagNames",
32368
- "createContext",
32369
- "MappingContext",
32370
- "allowedComponents"
32371
- ];
32372
- PROMPT_CANDIDATE_TOKEN_BUDGET = 8e4;
32373
- CHARS_PER_TOKEN = 4;
32374
- }
32375
- });
32376
-
32377
- // packages/experience-design-system-cli-legacy/src/analyze/composition/composition-cache-key.ts
32378
- function buildCompositionInputHash(input) {
32379
- const fileDigest = input.files.map((f) => `${f.path} ${hashContent(f.content)}`).sort().join("");
32380
- return hashContent(`agent:${input.agent}
32381
- ${fileDigest}`);
32382
- }
32383
- var init_composition_cache_key = __esm({
32384
- "packages/experience-design-system-cli-legacy/src/analyze/composition/composition-cache-key.ts"() {
32385
- "use strict";
32386
- init_cache_keys();
31118
+ init_debug_logger();
32387
31119
  }
32388
31120
  });
32389
31121
 
32390
31122
  // packages/experience-design-system-cli-legacy/src/analyze/composition/manifest-doc-evidence.ts
32391
- import { dirname as dirname18 } from "node:path";
31123
+ import { dirname as dirname17 } from "node:path";
32392
31124
  function kebabToPascal2(name) {
32393
31125
  return name.split("-").filter(Boolean).map((seg) => seg.charAt(0).toUpperCase() + seg.slice(1)).join("");
32394
31126
  }
@@ -32438,8 +31170,8 @@ function collectAgentsDocEdges(files, components, componentNames) {
32438
31170
  const seen = /* @__PURE__ */ new Set();
32439
31171
  for (const file of files) {
32440
31172
  if (!file.path.endsWith("AGENTS.md")) continue;
32441
- const docDir = dirname18(file.path);
32442
- const parent = components.find((c2) => c2.sourcePath && dirname18(c2.sourcePath) === docDir)?.name;
31173
+ const docDir = dirname17(file.path);
31174
+ const parent = components.find((c2) => c2.sourcePath && dirname17(c2.sourcePath) === docDir)?.name;
32443
31175
  if (!parent || !componentNames.has(parent)) continue;
32444
31176
  for (const line of file.content.split("\n")) {
32445
31177
  const lower = line.toLowerCase();
@@ -32469,12 +31201,172 @@ var init_manifest_doc_evidence = __esm({
32469
31201
  }
32470
31202
  });
32471
31203
 
32472
- // packages/experience-design-system-cli-legacy/src/analyze/extract-command.ts
32473
- import { mkdir as mkdir6, readdir as readdir3, readFile as readFile19, stat as stat6 } from "node:fs/promises";
32474
- import { isAbsolute as isAbsolute2, join as join28, relative as relative2, resolve as resolve20 } from "node:path";
32475
- function resolveExtractNoCache(opts) {
32476
- return opts.noCache === true || opts.cache === false;
31204
+ // packages/experience-design-system-cli-legacy/src/analyze/composition/source-call-site-evidence.ts
31205
+ import { Node as Node49, Project as Project11, SyntaxKind as SyntaxKind15 } from "ts-morph";
31206
+ function collectSourceCallSiteEvidence(files, components) {
31207
+ const componentNames = new Set(components.map((component) => component.name));
31208
+ const componentsBySource = /* @__PURE__ */ new Map();
31209
+ for (const component of components) {
31210
+ const sourcePath = component.sourcePath ?? component.source;
31211
+ const siblings = componentsBySource.get(sourcePath) ?? [];
31212
+ siblings.push(component);
31213
+ componentsBySource.set(sourcePath, siblings);
31214
+ }
31215
+ const project = new Project11({
31216
+ compilerOptions: { jsx: 1, target: 99, module: 99, moduleResolution: 100, skipLibCheck: true, allowJs: true },
31217
+ skipAddingFilesFromTsConfig: true
31218
+ });
31219
+ const sourceFiles = new Map(
31220
+ files.map((file) => [file.path, project.createSourceFile(file.path, file.content, { overwrite: true })])
31221
+ );
31222
+ const accepted = [];
31223
+ const rejected = [];
31224
+ for (const [sourcePath, parents] of componentsBySource) {
31225
+ const sourceFile = sourceFiles.get(sourcePath);
31226
+ if (!sourceFile) continue;
31227
+ const boundNames = collectBoundNames(sourceFile);
31228
+ for (const parent of parents) {
31229
+ for (const jsxElement of [
31230
+ ...sourceFile.getDescendantsOfKind(SyntaxKind15.JsxSelfClosingElement),
31231
+ ...sourceFile.getDescendantsOfKind(SyntaxKind15.JsxElement)
31232
+ ]) {
31233
+ const tagName = Node49.isJsxSelfClosingElement(jsxElement) ? jsxElement.getTagNameNode().getText() : jsxElement.getOpeningElement().getTagNameNode().getText();
31234
+ const candidate = tagName.split(".").at(-1) ?? tagName;
31235
+ if (candidate === parent.name || isIntrinsicTag(candidate)) continue;
31236
+ const lines = sourceExcerpt(sourceFile, jsxElement);
31237
+ if (!componentNames.has(candidate)) {
31238
+ rejected.push({ parent: parent.name, candidate, ...lines, reason: "unknown-component" });
31239
+ continue;
31240
+ }
31241
+ if (!boundNames.has(tagName) && !boundNames.has(candidate)) {
31242
+ rejected.push({ parent: parent.name, candidate, ...lines, reason: "unbound-component" });
31243
+ continue;
31244
+ }
31245
+ accepted.push({ parent: parent.name, child: candidate, ...lines, kind: "jsx-render" });
31246
+ }
31247
+ }
31248
+ }
31249
+ for (const sourceFile of sourceFiles.values()) {
31250
+ collectCallerSlotEvidence(sourceFile, componentNames, collectBoundNames(sourceFile), accepted, rejected);
31251
+ }
31252
+ const verifiedPairs = new Set(accepted.map((evidence) => `${evidence.parent}\0${evidence.child}`));
31253
+ for (const component of components) {
31254
+ const candidates = component.slots.flatMap((slot) => [
31255
+ ...slot.allowedComponents ?? [],
31256
+ ...slot.structuralAllowedComponents ?? []
31257
+ ]);
31258
+ for (const candidate of candidates) {
31259
+ if (verifiedPairs.has(`${component.name}\0${candidate}`)) continue;
31260
+ rejected.push({
31261
+ parent: component.name,
31262
+ candidate,
31263
+ sourcePath: component.sourcePath ?? component.source,
31264
+ reason: "no-call-site"
31265
+ });
31266
+ }
31267
+ }
31268
+ return {
31269
+ accepted: dedupeEvidence(accepted),
31270
+ rejected: dedupeRejections(rejected)
31271
+ };
31272
+ }
31273
+ function collectCallerSlotEvidence(sourceFile, componentNames, boundNames, accepted, rejected) {
31274
+ for (const parentElement of sourceFile.getDescendantsOfKind(SyntaxKind15.JsxElement)) {
31275
+ const parentTag = parentElement.getOpeningElement().getTagNameNode().getText();
31276
+ const parent = parentTag.split(".").at(-1) ?? parentTag;
31277
+ if (!componentNames.has(parent) || !boundNames.has(parentTag)) continue;
31278
+ for (const childNode of parentElement.getJsxChildren()) {
31279
+ if (!Node49.isJsxElement(childNode) && !Node49.isJsxSelfClosingElement(childNode)) {
31280
+ if (Node49.isJsxText(childNode) && childNode.getText().trim()) {
31281
+ const lines2 = sourceExcerpt(sourceFile, childNode);
31282
+ rejected.push({ parent, candidate: "<text>", ...lines2, reason: "text-only-child" });
31283
+ }
31284
+ continue;
31285
+ }
31286
+ const childTag = Node49.isJsxElement(childNode) ? childNode.getOpeningElement().getTagNameNode().getText() : childNode.getTagNameNode().getText();
31287
+ const child = childTag.split(".").at(-1) ?? childTag;
31288
+ if (isIntrinsicTag(child)) continue;
31289
+ const lines = sourceExcerpt(sourceFile, childNode);
31290
+ if (!componentNames.has(child)) {
31291
+ rejected.push({ parent, candidate: child, ...lines, reason: "unknown-component" });
31292
+ continue;
31293
+ }
31294
+ if (!boundNames.has(childTag) && !boundNames.has(child)) {
31295
+ rejected.push({ parent, candidate: child, ...lines, reason: "unbound-component" });
31296
+ continue;
31297
+ }
31298
+ const slotAttribute = Node49.isJsxElement(childNode) ? childNode.getOpeningElement().getAttribute("slot") : childNode.getAttribute("slot");
31299
+ const slotValue = slotAttribute && Node49.isJsxAttribute(slotAttribute) ? slotAttribute.getInitializer() : void 0;
31300
+ const slot = slotValue && Node49.isStringLiteral(slotValue) ? slotValue.getLiteralValue() : void 0;
31301
+ accepted.push({ parent, child, ...slot ? { slot } : {}, ...lines, kind: "jsx-render" });
31302
+ }
31303
+ }
31304
+ }
31305
+ function collectBoundNames(sourceFile) {
31306
+ const names = /* @__PURE__ */ new Set();
31307
+ for (const declaration of sourceFile.getImportDeclarations()) {
31308
+ const defaultImport = declaration.getDefaultImport();
31309
+ if (defaultImport) names.add(defaultImport.getText());
31310
+ const namespaceImport = declaration.getNamespaceImport();
31311
+ if (namespaceImport) names.add(namespaceImport.getText());
31312
+ for (const namedImport of declaration.getNamedImports()) {
31313
+ names.add((namedImport.getAliasNode() ?? namedImport.getNameNode()).getText());
31314
+ }
31315
+ }
31316
+ for (const declaration of sourceFile.getVariableDeclarations()) names.add(declaration.getName());
31317
+ for (const declaration of sourceFile.getFunctions()) {
31318
+ if (declaration.getName()) names.add(declaration.getName());
31319
+ }
31320
+ for (const declaration of sourceFile.getClasses()) {
31321
+ if (declaration.getName()) names.add(declaration.getName());
31322
+ }
31323
+ return names;
31324
+ }
31325
+ function sourceExcerpt(sourceFile, node) {
31326
+ const startLine = node.getStartLineNumber();
31327
+ const endLine = node.getEndLineNumber();
31328
+ const lines = sourceFile.getFullText().split("\n");
31329
+ return {
31330
+ sourcePath: sourceFile.getFilePath(),
31331
+ startLine,
31332
+ endLine,
31333
+ excerpt: lines.slice(startLine - 1, endLine).join("\n").trim()
31334
+ };
31335
+ }
31336
+ function isIntrinsicTag(tagName) {
31337
+ return /^[a-z]/.test(tagName) || tagName.includes("-");
32477
31338
  }
31339
+ function dedupeEvidence(evidence) {
31340
+ const seen = /* @__PURE__ */ new Set();
31341
+ return evidence.filter((item) => {
31342
+ const key = `${item.parent}\0${item.child}\0${item.slot ?? ""}\0${item.sourcePath}\0${item.startLine}`;
31343
+ if (seen.has(key)) return false;
31344
+ seen.add(key);
31345
+ return true;
31346
+ }).sort(
31347
+ (left, right) => `${left.parent}\0${left.child}\0${left.sourcePath}\0${left.startLine}`.localeCompare(
31348
+ `${right.parent}\0${right.child}\0${right.sourcePath}\0${right.startLine}`
31349
+ )
31350
+ );
31351
+ }
31352
+ function dedupeRejections(rejections) {
31353
+ const seen = /* @__PURE__ */ new Set();
31354
+ return rejections.filter((item) => {
31355
+ const key = `${item.parent}\0${item.candidate}\0${item.sourcePath}\0${item.startLine}`;
31356
+ if (seen.has(key)) return false;
31357
+ seen.add(key);
31358
+ return true;
31359
+ });
31360
+ }
31361
+ var init_source_call_site_evidence = __esm({
31362
+ "packages/experience-design-system-cli-legacy/src/analyze/composition/source-call-site-evidence.ts"() {
31363
+ "use strict";
31364
+ }
31365
+ });
31366
+
31367
+ // packages/experience-design-system-cli-legacy/src/analyze/extract-command.ts
31368
+ import { mkdir as mkdir6, readdir as readdir3, readFile as readFile18, stat as stat6 } from "node:fs/promises";
31369
+ import { isAbsolute as isAbsolute2, join as join27, relative as relative2, resolve as resolve18 } from "node:path";
32478
31370
  function isDenylistedNoiseFile(name) {
32479
31371
  return DENYLISTED_EXACT_FILE_NAMES.has(name) || DENYLISTED_FILE_NAME_PATTERNS.some((pattern) => pattern.test(name));
32480
31372
  }
@@ -32488,12 +31380,12 @@ async function retryDatabaseWrite(operation, attempts = 8) {
32488
31380
  } catch (error) {
32489
31381
  const message = error instanceof Error ? error.message : String(error);
32490
31382
  if (!/database is locked|database is busy/i.test(message) || attempt >= attempts) throw error;
32491
- await new Promise((resolve22) => setTimeout(resolve22, Math.min(250 * attempt, 2e3)));
31383
+ await new Promise((resolve20) => setTimeout(resolve20, Math.min(250 * attempt, 2e3)));
32492
31384
  }
32493
31385
  }
32494
31386
  }
32495
31387
  function resolveFromProjectRoot(projectRoot, inputPath) {
32496
- return isAbsolute2(inputPath) ? inputPath : resolve20(projectRoot, inputPath);
31388
+ return isAbsolute2(inputPath) ? inputPath : resolve18(projectRoot, inputPath);
32497
31389
  }
32498
31390
  async function pathExists4(path) {
32499
31391
  return Boolean(await stat6(path).catch(() => null));
@@ -32504,7 +31396,7 @@ async function collectSourceFiles(directory, onProgress) {
32504
31396
  const entries = await readdir3(currentDirectory, { withFileTypes: true });
32505
31397
  const subdirs = [];
32506
31398
  for (const entry of entries) {
32507
- const fullPath = join28(currentDirectory, entry.name);
31399
+ const fullPath = join27(currentDirectory, entry.name);
32508
31400
  if (entry.isDirectory()) {
32509
31401
  if (!IGNORED_DIRECTORY_NAMES.has(entry.name)) {
32510
31402
  subdirs.push(fullPath);
@@ -32531,12 +31423,6 @@ async function collectSourceFiles(directory, onProgress) {
32531
31423
  await visit(directory);
32532
31424
  return files.sort();
32533
31425
  }
32534
- function resolveCompositionAgentName(flagValue) {
32535
- if (flagValue && isAgentName(flagValue)) return flagValue;
32536
- const env = process.env["EDS_COMPOSITION_AGENT"];
32537
- if (env && isAgentName(env)) return env;
32538
- return DEFAULT_AGENT_NAME;
32539
- }
32540
31426
  async function readCandidateFiles(components, extraFiles = []) {
32541
31427
  const paths = new Set(extraFiles);
32542
31428
  for (const c2 of components) {
@@ -32546,7 +31432,7 @@ async function readCandidateFiles(components, extraFiles = []) {
32546
31432
  await Promise.all(
32547
31433
  [...paths].map(async (p) => {
32548
31434
  try {
32549
- const content = await readFile19(p, "utf8");
31435
+ const content = await readFile18(p, "utf8");
32550
31436
  out.push({ path: p, content });
32551
31437
  } catch {
32552
31438
  }
@@ -32555,21 +31441,11 @@ async function readCandidateFiles(components, extraFiles = []) {
32555
31441
  return out;
32556
31442
  }
32557
31443
  function registerInternalExtractCommand(program) {
32558
- 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(
31444
+ 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(
32559
31445
  "--resolve-unreachable <mode>",
32560
31446
  "Retry pass for unresolved Svelte Props types: 'auto' (default), 'always', or 'never'",
32561
31447
  "auto"
32562
- ).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(
32563
- "--prompt <stage=value>",
32564
- "Override a stage prompt (repeatable). value is a file path or literal text, e.g. --prompt composition=./p.md",
32565
- (v, acc) => [...acc, v],
32566
- []
32567
- );
32568
- addAgentModelOptions(extractCmd, {
32569
- includeModel: false,
32570
- agentDescription: "Coding agent for composition mapping resolution (claude|codex|opencode|cursor)"
32571
- }).action(async (opts) => {
32572
- const noCache = resolveExtractNoCache(opts);
31448
+ ).action(async (opts) => {
32573
31449
  const resolveUnreachable = (() => {
32574
31450
  const v = opts.resolveUnreachable ?? "auto";
32575
31451
  if (v !== "auto" && v !== "always" && v !== "never") {
@@ -32579,16 +31455,8 @@ function registerInternalExtractCommand(program) {
32579
31455
  }
32580
31456
  return v;
32581
31457
  })();
32582
- if (opts.bedrock) {
32583
- const bedrockAgent = resolveCompositionAgentName(opts.agent);
32584
- if (!agentSupportsBedrock(bedrockAgent)) {
32585
- process.stderr.write(`Error: --bedrock is not supported for --agent ${bedrockAgent}
32586
- `);
32587
- process.exit(1);
32588
- }
32589
- }
32590
- const projectRoot = resolve20(opts.project);
32591
- const outDir = join28(projectRoot, ".contentful");
31458
+ const projectRoot = resolve18(opts.project);
31459
+ const outDir = join27(projectRoot, ".contentful");
32592
31460
  let sourceDirectory;
32593
31461
  if (opts.dir !== void 0) {
32594
31462
  sourceDirectory = resolveFromProjectRoot(projectRoot, opts.dir);
@@ -32611,50 +31479,16 @@ function registerInternalExtractCommand(program) {
32611
31479
  process.stderr.write(`progress=scan-done:${sourceFiles.length}
32612
31480
  `);
32613
31481
  }
32614
- const extractionCacheDb = openPipelineDb();
32615
- let extraction;
32616
- let extractionCacheHits = 0;
32617
- try {
32618
- const cacheVersion = await getCliCacheVersion();
32619
- const cachedByPath = /* @__PURE__ */ new Map();
32620
- if (!noCache && sourceFiles.length > 0) {
32621
- const hashes = await Promise.all(
32622
- sourceFiles.map(async (filePath) => [filePath, await hashFile(filePath)])
32623
- );
32624
- for (const [filePath, fileHash] of hashes) {
32625
- cachedByPath.set(filePath, lookupExtractCache(extractionCacheDb, fileHash, cacheVersion));
32626
- }
32627
- }
32628
- const allFilesCached = !noCache && sourceFiles.length > 0 && sourceFiles.every((filePath) => cachedByPath.get(filePath) !== null);
32629
- if (allFilesCached) {
32630
- const cachedComponents = sourceFiles.flatMap((filePath) => cachedByPath.get(filePath).components);
32631
- extractionCacheHits = sourceFiles.length;
32632
- extraction = { components: cachedComponents, warnings: [], exclusions: [] };
31482
+ const extraction = await extractComponents(
31483
+ sourceFiles,
31484
+ ({ filesProcessed, componentsFound }) => {
32633
31485
  if (!process.stdout.isTTY) {
32634
- process.stderr.write(
32635
- `progress=extract:${sourceFiles.length}/${sourceFiles.length}:${cachedComponents.length}
32636
- `
32637
- );
32638
- }
32639
- getDebugLogger().event("analyze", "extract.cache-hit", {
32640
- files: sourceFiles.length,
32641
- components: cachedComponents.length
32642
- });
32643
- } else {
32644
- extraction = await extractComponents(
32645
- sourceFiles,
32646
- ({ filesProcessed, componentsFound }) => {
32647
- if (!process.stdout.isTTY) {
32648
- process.stderr.write(`progress=extract:${filesProcessed}/${sourceFiles.length}:${componentsFound}
31486
+ process.stderr.write(`progress=extract:${filesProcessed}/${sourceFiles.length}:${componentsFound}
32649
31487
  `);
32650
- }
32651
- },
32652
- { resolveUnreachable, projectRoot }
32653
- );
32654
- }
32655
- } finally {
32656
- extractionCacheDb.close();
32657
- }
31488
+ }
31489
+ },
31490
+ { resolveUnreachable, projectRoot }
31491
+ );
32658
31492
  await mkdir6(outDir, { recursive: true });
32659
31493
  const db = openPipelineDb();
32660
31494
  const { sessionId: sessionId2 } = getOrCreateSession(db, void 0, void 0, {
@@ -32669,25 +31503,6 @@ function registerInternalExtractCommand(program) {
32669
31503
  const stepId = createStep(db, sessionId2, "analyze extract", {
32670
31504
  project: projectRoot
32671
31505
  });
32672
- if (extractionCacheHits === 0 && !noCache) {
32673
- const cacheVersion = await getCliCacheVersion();
32674
- const componentsBySourcePath = /* @__PURE__ */ new Map();
32675
- for (const component of extraction.components) {
32676
- if (!component.sourcePath) continue;
32677
- const components = componentsBySourcePath.get(component.sourcePath) ?? [];
32678
- components.push(component);
32679
- componentsBySourcePath.set(component.sourcePath, components);
32680
- }
32681
- for (const filePath of sourceFiles) {
32682
- storeExtractCache(
32683
- db,
32684
- filePath,
32685
- await hashFile(filePath),
32686
- cacheVersion,
32687
- componentsBySourcePath.get(filePath) ?? []
32688
- );
32689
- }
32690
- }
32691
31506
  const classifiedComponents = extraction.components.map(preClassifyComponent);
32692
31507
  for (const exclusion of extraction.exclusions ?? []) {
32693
31508
  getDebugLogger().event("filter", "extract.excluded", { ...exclusion });
@@ -32711,28 +31526,9 @@ function registerInternalExtractCommand(program) {
32711
31526
  storeRawComponents(db, sessionId2, validatedComponents);
32712
31527
  process.stdout.write(`session=${sessionId2}
32713
31528
  `);
31529
+ let sourceCallSiteEvidence = [];
31530
+ let sourceCallSiteRejections = [];
32714
31531
  {
32715
- const sources = resolveCompositionSources({
32716
- ...opts,
32717
- noCache
32718
- });
32719
- const { overrides: promptOverrides, errors: promptErrors } = parsePromptOverrides(opts.prompt ?? []);
32720
- for (const err of promptErrors) {
32721
- process.stderr.write(`Error: ${err}
32722
- `);
32723
- process.exit(1);
32724
- }
32725
- let compositionPrompt;
32726
- const compositionOverride = promptOverrides.get("composition");
32727
- if (compositionOverride) {
32728
- try {
32729
- compositionPrompt = await resolvePromptOverride(compositionOverride);
32730
- } catch (e) {
32731
- process.stderr.write(`Error: ${e instanceof Error ? e.message : String(e)}
32732
- `);
32733
- process.exit(1);
32734
- }
32735
- }
32736
31532
  {
32737
31533
  const emitCompositionProgress = (phase) => {
32738
31534
  if (!process.stdout.isTTY) process.stderr.write(`progress=composition:${phase}
@@ -32740,62 +31536,18 @@ function registerInternalExtractCommand(program) {
32740
31536
  };
32741
31537
  emitCompositionProgress("resolving");
32742
31538
  const allFiles = await readCandidateFiles(validatedComponents, sourceFiles);
32743
- const selectedCandidates = selectCandidateFiles(allFiles).map((c2) => ({ path: c2.path, content: c2.content }));
32744
- const capped = capCandidatesToPromptBudget(selectedCandidates);
32745
- const promptFiles = capped.kept;
32746
- if (capped.dropped.length > 0) {
32747
- process.stderr.write(
32748
- `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.
32749
- `
32750
- );
32751
- }
32752
31539
  const runtimeFiles = allFiles.map((c2) => ({ path: c2.path, content: c2.content }));
32753
- const resolverAgent = resolveCompositionAgentName(opts.agent);
32754
31540
  const componentNameSet = new Set(validatedComponents.map((c2) => c2.name));
32755
- const cacheVersion = await getCliCacheVersion();
32756
- let lastAgentExitCode = 0;
32757
- const spawnAgent = async (prompt) => {
32758
- const res = await runAgent({
32759
- agent: resolverAgent,
32760
- prompt,
32761
- timeoutMs: 12e4,
32762
- promptViaStdin: true,
32763
- onDebugEvent: (name, payload) => getDebugLogger().event("agent", name, payload)
32764
- });
32765
- lastAgentExitCode = res.exitCode;
32766
- if (res.exitCode !== 0 && res.stderr.trim()) {
32767
- process.stderr.write(`Warning: composition \u2014 agent exited ${res.exitCode}: ${res.stderr.trim()}
32768
- `);
32769
- }
32770
- return res.stdout;
32771
- };
32772
31541
  const manifestDocEdges = collectManifestDocEdges(runtimeFiles, validatedComponents, componentNameSet);
32773
31542
  const extraEdges = manifestDocEdges;
32774
- const agentCacheKey = buildCompositionInputHash({
32775
- files: promptFiles,
32776
- agent: resolverAgent
32777
- });
32778
- const result = await resolveMapping({
31543
+ const sourceCallSites = collectSourceCallSiteEvidence(runtimeFiles, validatedComponents);
31544
+ sourceCallSiteEvidence = sourceCallSites.accepted;
31545
+ sourceCallSiteRejections = sourceCallSites.rejected;
31546
+ const result = resolveMapping({
32779
31547
  components: validatedComponents,
32780
31548
  ...extraEdges.length > 0 ? { extraEdges } : {},
32781
- forceAgent: sources.forceAgent,
32782
- files: promptFiles,
32783
- ...compositionPrompt ? { promptOverride: compositionPrompt } : {},
32784
- runAgentFn: async ({ prompt }) => {
32785
- if (!noCache && !opts.compositionRefresh) {
32786
- const cached = lookupCompositionCache(db, agentCacheKey, cacheVersion);
32787
- if (cached !== null) {
32788
- emitCompositionProgress("cache-hit");
32789
- return cached;
32790
- }
32791
- }
32792
- emitCompositionProgress(`agent:${resolverAgent}`);
32793
- const stdout = await spawnAgent(prompt);
32794
- if (lastAgentExitCode === 0) {
32795
- storeCompositionCache(db, agentCacheKey, cacheVersion, stdout);
32796
- }
32797
- return stdout;
32798
- }
31549
+ sourceCallSiteEvidence,
31550
+ sourceCallSiteRejections
32799
31551
  });
32800
31552
  emitCompositionProgress("done");
32801
31553
  for (const w of result.warnings) process.stderr.write(`Warning: composition \u2014 ${w}
@@ -32825,7 +31577,13 @@ function registerInternalExtractCommand(program) {
32825
31577
  sessionId2,
32826
31578
  sourceFiles.map((f) => relative2(projectRoot, f))
32827
31579
  );
32828
- await retryDatabaseWrite(() => updateStep(db, stepId, "complete", { sessionId: sessionId2 }));
31580
+ await retryDatabaseWrite(
31581
+ () => updateStep(db, stepId, "complete", {
31582
+ sessionId: sessionId2,
31583
+ compositionEvidence: JSON.stringify(sourceCallSiteEvidence),
31584
+ compositionRejections: JSON.stringify(sourceCallSiteRejections)
31585
+ })
31586
+ );
32829
31587
  enrichCommandResult({ extracted_component_count: validatedComponents.length });
32830
31588
  db.close();
32831
31589
  const allWarnings = [...extraction.warnings, ...filterWarnings];
@@ -32847,18 +31605,12 @@ var SCANNED_FILE_EXTENSIONS, DENYLIST_GATED_EXTENSIONS, DENYLISTED_EXACT_FILE_NA
32847
31605
  var init_extract_command = __esm({
32848
31606
  "packages/experience-design-system-cli-legacy/src/analyze/extract-command.ts"() {
32849
31607
  "use strict";
32850
- init_agent_model_options();
32851
31608
  init_src2();
32852
31609
  init_db();
32853
- init_cache_keys();
32854
31610
  init_cycle_detection();
32855
31611
  init_resolve_mapping();
32856
- init_resolve_mapping_cli();
32857
- init_candidate_files();
32858
- init_composition_cache_key();
32859
31612
  init_manifest_doc_evidence();
32860
- init_prompt_overrides();
32861
- init_src();
31613
+ init_source_call_site_evidence();
32862
31614
  init_analytics();
32863
31615
  init_debug_logger();
32864
31616
  SCANNED_FILE_EXTENSIONS = /* @__PURE__ */ new Set([".astro", ".js", ".jsx", ".svelte", ".ts", ".tsx", ".vue"]);
@@ -32952,9 +31704,9 @@ __export(program_exports, {
32952
31704
  runBuild: () => runBuild
32953
31705
  });
32954
31706
  import { spawn as spawn7 } from "node:child_process";
32955
- import { fileURLToPath as fileURLToPath4 } from "node:url";
32956
- import { dirname as dirname19, join as join29, resolve as resolve21 } from "node:path";
32957
- import { readFileSync as readFileSync11 } from "node:fs";
31707
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
31708
+ import { dirname as dirname18, join as join28, resolve as resolve19 } from "node:path";
31709
+ import { readFileSync as readFileSync10 } from "node:fs";
32958
31710
  import { Command } from "commander";
32959
31711
  async function runBuild(opts) {
32960
31712
  return new Promise((resolvePromise) => {
@@ -32983,7 +31735,7 @@ function resolveBedrockFromAncestors(actionCommand) {
32983
31735
  }
32984
31736
  function registerBuildCommand(program) {
32985
31737
  program.command("build").description("Rebuild from source and re-link exo/experiences binaries to this build").helpOption(false).action(async () => {
32986
- const pkgRoot = resolve21(dirname19(fileURLToPath4(import.meta.url)), "..", "..");
31738
+ const pkgRoot = resolve19(dirname18(fileURLToPath3(import.meta.url)), "..", "..");
32987
31739
  process.stderr.write("\u2699 Building from source...\n");
32988
31740
  const { exitCode } = await runBuild({
32989
31741
  spawnFn: () => spawn7("pnpm", ["build"], { cwd: pkgRoot, stdio: "inherit" }),
@@ -33053,7 +31805,7 @@ var init_program = __esm({
33053
31805
  init_analytics();
33054
31806
  init_credentials_store();
33055
31807
  init_cli_path();
33056
- pkg3 = JSON.parse(readFileSync11(join29(findPkgRoot(), "package.json"), "utf8"));
31808
+ pkg3 = JSON.parse(readFileSync10(join28(findPkgRoot(), "package.json"), "utf8"));
33057
31809
  }
33058
31810
  });
33059
31811