@c4a/context-cli 0.7.104 → 0.7.105

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -40810,7 +40810,7 @@ var getSourceType = (sourceDefinition) => {
40810
40810
  }), captureLark = (definition) => {
40811
40811
  const sourceDefinition = bindSourceType(definition.source, "lark", "captureLark source");
40812
40812
  const sourceId = getSourceName(sourceDefinition);
40813
- for (const key of ["images", "gifs"]) {
40813
+ for (const key of ["images", "gifs", "files", "whiteboards"]) {
40814
40814
  const value = definition.resources?.[key];
40815
40815
  if (value !== undefined && value !== "bundle" && value !== "reference-only") {
40816
40816
  throw new TypeError(`captureLark resources.${key} must be bundle or reference-only`);
@@ -40836,6 +40836,8 @@ var getSourceType = (sourceDefinition) => {
40836
40836
  resources: {
40837
40837
  ...definition.resources?.images === undefined ? {} : { images: definition.resources.images },
40838
40838
  ...definition.resources?.gifs === undefined ? {} : { gifs: definition.resources.gifs },
40839
+ ...definition.resources?.files === undefined ? {} : { files: definition.resources.files },
40840
+ ...definition.resources?.whiteboards === undefined ? {} : { whiteboards: definition.resources.whiteboards },
40839
40841
  videos: definition.resources?.videos ?? "reference-only",
40840
40842
  maxBytesPerResource,
40841
40843
  maxTotalBytes
@@ -86148,6 +86150,7 @@ function materializationItem(resource) {
86148
86150
  };
86149
86151
  }
86150
86152
  function createLarkCaptureReport(input) {
86153
+ const budgetExceeded = input.resourceMaterialization.items.some((item) => item.reason_code === "image-budget-exceeded");
86151
86154
  const descriptors = new Map(input.resources.map((resource) => [resourceKey2(resource), resource]));
86152
86155
  return {
86153
86156
  schema_version: LARK_CAPTURE_REPORT_SCHEMA_VERSION,
@@ -86161,9 +86164,22 @@ function createLarkCaptureReport(input) {
86161
86164
  attributes: descriptor?.attributes ?? {}
86162
86165
  };
86163
86166
  }),
86164
- ...input.access === undefined ? {} : { access: input.access }
86167
+ ...input.access === undefined ? {} : { access: input.access },
86168
+ ...budgetExceeded && input.resourceBudget !== undefined ? { resource_budget: {
86169
+ maxBytesPerResource: input.resourceBudget.maxBytesPerResource,
86170
+ maxTotalBytes: input.resourceBudget.maxTotalBytes
86171
+ } } : {}
86165
86172
  };
86166
86173
  }
86174
+ function parseResourceBudget(value) {
86175
+ if (value === undefined)
86176
+ return;
86177
+ const positive = (field) => typeof field === "number" && Number.isSafeInteger(field) && field > 0;
86178
+ if (!isRecord10(value) || !positive(value.maxBytesPerResource) || !positive(value.maxTotalBytes)) {
86179
+ throw new TypeError("Lark capture report resource_budget must hold positive maxBytesPerResource and maxTotalBytes");
86180
+ }
86181
+ return { maxBytesPerResource: value.maxBytesPerResource, maxTotalBytes: value.maxTotalBytes };
86182
+ }
86167
86183
  function parseAccess(value) {
86168
86184
  if (value === undefined)
86169
86185
  return;
@@ -86227,6 +86243,7 @@ function parseLarkCaptureReport(value) {
86227
86243
  throw new TypeError("Lark capture report resource_materialization is required");
86228
86244
  }
86229
86245
  const access4 = parseAccess(value.access);
86246
+ const resourceBudget = parseResourceBudget(value.resource_budget);
86230
86247
  return {
86231
86248
  schema_version: LARK_CAPTURE_REPORT_SCHEMA_VERSION,
86232
86249
  fidelity,
@@ -86236,7 +86253,8 @@ function parseLarkCaptureReport(value) {
86236
86253
  ...enriched[index2]?.title === undefined ? {} : { title: enriched[index2].title },
86237
86254
  attributes: enriched[index2]?.attributes ?? {}
86238
86255
  })),
86239
- ...access4 === undefined ? {} : { access: access4 }
86256
+ ...access4 === undefined ? {} : { access: access4 },
86257
+ ...resourceBudget === undefined ? {} : { resource_budget: resourceBudget }
86240
86258
  };
86241
86259
  }
86242
86260
  function captureReportMaterialization(report) {
@@ -107949,8 +107967,10 @@ var init_larkDocxXml = __esm(() => {
107949
107967
  });
107950
107968
 
107951
107969
  // src/lib/larkResourceScheduler.ts
107970
+ import { readdir as readdir26, rm as rm27 } from "node:fs/promises";
107971
+ import { join as join117 } from "node:path";
107952
107972
  import { setTimeout as delay } from "node:timers/promises";
107953
- function throttle(value, depth = 0) {
107973
+ function structured(value, match, depth = 0) {
107954
107974
  if (depth > 6 || value === null)
107955
107975
  return false;
107956
107976
  if (typeof value === "string") {
@@ -107958,7 +107978,7 @@ function throttle(value, depth = 0) {
107958
107978
  if (start2 < 0)
107959
107979
  return false;
107960
107980
  try {
107961
- return throttle(JSON.parse(value.slice(start2)), depth + 1);
107981
+ return structured(JSON.parse(value.slice(start2)), match, depth + 1);
107962
107982
  } catch {
107963
107983
  return false;
107964
107984
  }
@@ -107966,9 +107986,35 @@ function throttle(value, depth = 0) {
107966
107986
  if (typeof value !== "object")
107967
107987
  return false;
107968
107988
  const record4 = value;
107969
- if ([record4.code, record4.status, record4.status_code].some((code3) => String(code3) === "429") || record4.type === "rate_limit" || record4.subtype === "rate_limited")
107989
+ if (match(record4))
107990
+ return true;
107991
+ return [record4.error, record4.message, record4.cause].some((entry) => structured(entry, match, depth + 1));
107992
+ }
107993
+ function failureText(result) {
107994
+ if (result.exitCode !== 0)
107995
+ return `${result.stderr}
107996
+ ${result.stdout}`;
107997
+ const trimmed = result.stdout.trim();
107998
+ if (!trimmed.startsWith("{"))
107999
+ return;
108000
+ try {
108001
+ const envelope = JSON.parse(trimmed);
108002
+ return envelope?.ok === false ? JSON.stringify(envelope.error ?? envelope) : undefined;
108003
+ } catch {
108004
+ return;
108005
+ }
108006
+ }
108007
+ function isLarkResourceTransient(result) {
108008
+ if (result.exitCode === null)
108009
+ return true;
108010
+ const text12 = failureText(result);
108011
+ if (text12 === undefined || isLarkResourceThrottled(result))
108012
+ return false;
108013
+ if (structured(text12, (record4) => codes2(record4).some((code3) => TRANSIENT_STATUS.has(code3))))
107970
108014
  return true;
107971
- return [record4.error, record4.message, record4.cause].some((entry) => throttle(entry, depth + 1));
108015
+ if (structured(text12, (record4) => codes2(record4).some((code3) => PERMANENT_STATUS.has(code3)) || PERMANENT_TYPES.has(String(record4.type))))
108016
+ return false;
108017
+ return TRANSIENT_TEXT.test(text12);
107972
108018
  }
107973
108019
  function isLarkResourceThrottled(result) {
107974
108020
  return throttle(result.stderr) || throttle(result.stdout);
@@ -107996,13 +108042,19 @@ function retryAfter(value, now2, depth = 0) {
107996
108042
  const own5 = Number.isFinite(milliseconds) && milliseconds > 0 ? milliseconds : Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : typeof raw === "string" ? Math.max(0, Date.parse(raw) - now2) || 0 : 0;
107997
108043
  return Math.max(own5, ...[record4.error, record4.cause, record4.message].map((entry) => retryAfter(entry, now2, depth + 1)));
107998
108044
  }
108045
+ async function emptyDirectory(path3) {
108046
+ for (const entry of await readdir26(path3))
108047
+ await rm27(join117(path3, entry), { recursive: true, force: true });
108048
+ }
107999
108049
  function createLarkResourceScheduler(runner2, options = {}) {
108000
108050
  const now2 = options.now ?? Date.now;
108001
108051
  const sleep2 = options.sleep ?? delay;
108052
+ const random = options.random ?? Math.random;
108002
108053
  let concurrency = 4;
108003
108054
  let active = 0;
108004
108055
  let blockedUntil = 0;
108005
108056
  let successes = 0;
108057
+ let lastTransientCut = Number.NEGATIVE_INFINITY;
108006
108058
  let exhausted;
108007
108059
  const waiters = [];
108008
108060
  const wake2 = () => {
@@ -108028,33 +108080,54 @@ function createLarkResourceScheduler(runner2, options = {}) {
108028
108080
  }
108029
108081
  };
108030
108082
  return async (args, commandOptions) => {
108031
- for (let attempt = 0;; attempt++) {
108083
+ let throttled = 0;
108084
+ let transient = 0;
108085
+ for (;; ) {
108032
108086
  if (exhausted)
108033
108087
  return exhausted;
108034
108088
  await acquire();
108089
+ let result;
108035
108090
  try {
108036
108091
  if (exhausted)
108037
108092
  return exhausted;
108038
- const result = await runner2(args, commandOptions);
108039
- if (!isLarkResourceThrottled(result)) {
108040
- if (result.exitCode === 0 && ++successes >= 8) {
108041
- concurrency = Math.min(4, concurrency + 1);
108042
- successes = 0;
108043
- }
108044
- return result;
108093
+ if (throttled + transient > 0 && commandOptions?.scratchDirectory && commandOptions.cwd !== undefined) {
108094
+ await emptyDirectory(commandOptions.cwd);
108045
108095
  }
108096
+ result = await runner2(args, commandOptions);
108097
+ } finally {
108098
+ active--;
108099
+ wake2();
108100
+ }
108101
+ if (isLarkResourceThrottled(result)) {
108046
108102
  successes = 0;
108047
108103
  concurrency = Math.max(1, Math.floor(concurrency / 2));
108048
- const wait = Math.max(1000 * 2 ** attempt, retryAfter(result.stderr, now2()), retryAfter(result.stdout, now2()));
108104
+ const wait = Math.max(1000 * 2 ** throttled, retryAfter(result.stderr, now2()), retryAfter(result.stdout, now2()));
108049
108105
  blockedUntil = Math.max(blockedUntil, now2() + Math.min(wait, 30000));
108050
- if (attempt >= 3 || wait > 30000) {
108106
+ if (throttled >= 3 || wait > 30000) {
108051
108107
  exhausted = result;
108052
108108
  return result;
108053
108109
  }
108054
- } finally {
108055
- active--;
108056
- wake2();
108110
+ throttled++;
108111
+ continue;
108057
108112
  }
108113
+ if (isLarkResourceTransient(result)) {
108114
+ successes = 0;
108115
+ if (transient >= TRANSIENT_RETRIES)
108116
+ return result;
108117
+ if (now2() - lastTransientCut >= TRANSIENT_CUT_WINDOW_MS) {
108118
+ concurrency = Math.max(1, Math.floor(concurrency / 2));
108119
+ lastTransientCut = now2();
108120
+ }
108121
+ const base = 1000 * 3 ** transient;
108122
+ transient++;
108123
+ await sleep2(Math.round(base * (0.75 + random() * 0.5)));
108124
+ continue;
108125
+ }
108126
+ if (failureText(result) === undefined && ++successes >= 8) {
108127
+ concurrency = Math.min(4, concurrency + 1);
108128
+ successes = 0;
108129
+ }
108130
+ return result;
108058
108131
  }
108059
108132
  };
108060
108133
  }
@@ -108065,7 +108138,35 @@ async function forEachLarkResource(items, visit4) {
108065
108138
  await visit4(items[next2++]);
108066
108139
  }));
108067
108140
  }
108068
- var init_larkResourceScheduler = () => {};
108141
+ var throttle = (value) => structured(value, (record4) => [record4.code, record4.status, record4.status_code].some((code3) => ["429", "99991400"].includes(String(code3))) || record4.type === "rate_limit" || record4.subtype === "rate_limited"), codes2 = (record4) => [record4.code, record4.status, record4.status_code].filter((code3) => code3 !== undefined && code3 !== null).map(String), TRANSIENT_STATUS, PERMANENT_STATUS, PERMANENT_TYPES, TRANSIENT_TEXT, TRANSIENT_RETRIES = 3, TRANSIENT_CUT_WINDOW_MS = 5000;
108142
+ var init_larkResourceScheduler = __esm(() => {
108143
+ TRANSIENT_STATUS = new Set(["502", "503", "504"]);
108144
+ PERMANENT_STATUS = new Set(["400", "401", "403", "404", "500", "2890003", "3380004", "99991672"]);
108145
+ PERMANENT_TYPES = new Set(["authorization", "authentication", "validation"]);
108146
+ TRANSIENT_TEXT = new RegExp([
108147
+ String.raw`(?:HTTP[/\s\d.]*\s|status(?:[ _]code)?[:=\s]+|code[:=\s]+)(?:502|503|504)\b`,
108148
+ String.raw`\b(?:502|503|504)\s+(?:bad gateway|service unavailable|gateway time-?out)`,
108149
+ "bad gateway",
108150
+ "service unavailable",
108151
+ "gateway time-?out",
108152
+ "request time-?out",
108153
+ "timed out",
108154
+ "deadline exceeded",
108155
+ "i/o timeout",
108156
+ String.raw`client\.timeout`,
108157
+ "timeout exceeded",
108158
+ "ETIMEDOUT",
108159
+ "ECONNRESET",
108160
+ "ECONNABORTED",
108161
+ "EPIPE",
108162
+ "EAI_AGAIN",
108163
+ "connection (?:reset|refused|closed)",
108164
+ "socket hang up",
108165
+ "unexpected EOF",
108166
+ "network is unreachable",
108167
+ "TLS handshake timeout"
108168
+ ].join("|"), "iu");
108169
+ });
108069
108170
 
108070
108171
  // src/lib/larkResourceCommand.ts
108071
108172
  function hasMissingScope(value, depth = 0) {
@@ -108177,19 +108278,20 @@ var init_larkResourceCommand = __esm(() => {
108177
108278
  });
108178
108279
 
108179
108280
  // src/lib/larkMediaDownload.ts
108180
- import { readdir as readdir26, rm as rm27 } from "node:fs/promises";
108181
- import { join as join117 } from "node:path";
108281
+ import { readdir as readdir27, rm as rm28 } from "node:fs/promises";
108282
+ import { join as join118 } from "node:path";
108182
108283
  async function downloadLarkMedia(input) {
108284
+ const options = { cwd: input.cwd, scratchDirectory: true, ...input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs } };
108183
108285
  const shared = ["--as", input.identity, "--token", input.token, "--output", "./resource", "--format", "json"];
108184
108286
  try {
108185
- await runLarkResourceCommand(input.runner, ["docs", "+media-download", ...shared, "--type", input.type, "--overwrite"], { cwd: input.cwd });
108287
+ await runLarkResourceCommand(input.runner, ["docs", "+media-download", ...shared, "--type", input.type, "--overwrite"], options);
108186
108288
  return "original";
108187
108289
  } catch (error) {
108188
108290
  if (!input.allowPreview || !isLarkResourcePermissionDenied(error))
108189
108291
  throw error;
108190
- for (const entry of await readdir26(input.cwd))
108191
- await rm27(join117(input.cwd, entry), { recursive: true, force: true });
108192
- await runLarkResourceCommand(input.runner, ["docs", "+media-preview", ...shared], { cwd: input.cwd });
108292
+ for (const entry of await readdir27(input.cwd))
108293
+ await rm28(join118(input.cwd, entry), { recursive: true, force: true });
108294
+ await runLarkResourceCommand(input.runner, ["docs", "+media-preview", ...shared], options);
108193
108295
  return "preview";
108194
108296
  }
108195
108297
  }
@@ -108198,9 +108300,9 @@ var init_larkMediaDownload = __esm(() => {
108198
108300
  });
108199
108301
 
108200
108302
  // src/lib/larkWhiteboardExport.ts
108201
- import { mkdtemp as mkdtemp5, readFile as readFile95, rm as rm28 } from "node:fs/promises";
108303
+ import { mkdtemp as mkdtemp5, readFile as readFile95, rm as rm29 } from "node:fs/promises";
108202
108304
  import { tmpdir as tmpdir2 } from "node:os";
108203
- import { join as join118 } from "node:path";
108305
+ import { join as join119 } from "node:path";
108204
108306
  function stableJson2(value) {
108205
108307
  if (value === undefined)
108206
108308
  return "null";
@@ -108230,7 +108332,7 @@ function canonicalWhiteboardPayload(value) {
108230
108332
  };
108231
108333
  }
108232
108334
  async function exportLarkWhiteboardRaw(runner2, identity2, token) {
108233
- const tempRoot = await mkdtemp5(join118(tmpdir2(), "context-lark-whiteboard-"));
108335
+ const tempRoot = await mkdtemp5(join119(tmpdir2(), "context-lark-whiteboard-"));
108234
108336
  try {
108235
108337
  await runLarkResourceCommand(runner2, [
108236
108338
  "whiteboard",
@@ -108246,12 +108348,12 @@ async function exportLarkWhiteboardRaw(runner2, identity2, token) {
108246
108348
  "--overwrite",
108247
108349
  "--format",
108248
108350
  "json"
108249
- ], { cwd: tempRoot });
108250
- const rawPayload = JSON.parse(await readFile95(join118(tempRoot, "raw.json"), "utf8"));
108351
+ ], { cwd: tempRoot, scratchDirectory: true });
108352
+ const rawPayload = JSON.parse(await readFile95(join119(tempRoot, "raw.json"), "utf8"));
108251
108353
  return Buffer.from(`${stableJson2(canonicalWhiteboardPayload(rawPayload))}
108252
108354
  `, "utf8");
108253
108355
  } finally {
108254
- await rm28(tempRoot, { recursive: true, force: true });
108356
+ await rm29(tempRoot, { recursive: true, force: true });
108255
108357
  }
108256
108358
  }
108257
108359
  var init_larkWhiteboardExport = __esm(() => {
@@ -108278,16 +108380,39 @@ function omitLarkImage(resource, policy, items, replacements, mediaType, failure
108278
108380
  });
108279
108381
  return true;
108280
108382
  }
108281
- var LarkResourceBudgetError;
108383
+ function omitLarkResourceByPolicy(resource, policy, items, replacements) {
108384
+ const excluded = resource.kind === "file" ? policy.files === "reference-only" : (resource.kind === "whiteboard" || resource.kind === "diagram" && resource.inline_content !== true) && policy.whiteboards === "reference-only";
108385
+ if (!excluded)
108386
+ return false;
108387
+ const label2 = resource.kind === "file" ? "File" : resource.kind === "diagram" ? "Diagram" : "Whiteboard";
108388
+ const title2 = (resource.title ?? label2.toLowerCase()).replace(/[\r\n<>]/gu, " ");
108389
+ replacements.set(resource.locator, `> ${label2} omitted: ${title2}. Excluded by selected policy. See the source document. <!-- ${resource.locator} -->`);
108390
+ items.push({
108391
+ kind: resource.kind,
108392
+ locator: resource.locator,
108393
+ status: "reference-only",
108394
+ required: false,
108395
+ asset_paths: [],
108396
+ reason_code: resource.kind === "file" ? "file-excluded-by-policy" : "whiteboard-excluded-by-policy",
108397
+ reason: `${label2} bytes were not retained; the selected resource policy preserves a placeholder and source reference`
108398
+ });
108399
+ return true;
108400
+ }
108401
+ var LarkResourceBudgetError, LARK_POLICY_EXCLUSION_REASON_CODES;
108282
108402
  var init_larkImagePolicy = __esm(() => {
108283
108403
  LarkResourceBudgetError = class LarkResourceBudgetError extends Error {
108284
108404
  };
108405
+ LARK_POLICY_EXCLUSION_REASON_CODES = new Set([
108406
+ "image-excluded-by-policy",
108407
+ "file-excluded-by-policy",
108408
+ "whiteboard-excluded-by-policy"
108409
+ ]);
108285
108410
  });
108286
108411
 
108287
108412
  // src/lib/larkResourceMaterialization.ts
108288
108413
  import { createHash as createHash36 } from "node:crypto";
108289
- import { mkdtemp as mkdtemp6, readFile as readFile96, readdir as readdir27, rm as rm29 } from "node:fs/promises";
108290
- import { extname as extname13, join as join119 } from "node:path";
108414
+ import { mkdtemp as mkdtemp6, readFile as readFile96, readdir as readdir28, rm as rm30 } from "node:fs/promises";
108415
+ import { extname as extname13, join as join120 } from "node:path";
108291
108416
  import { tmpdir as tmpdir3 } from "node:os";
108292
108417
  function countByKind(items, status) {
108293
108418
  const counts2 = new Map;
@@ -108395,17 +108520,17 @@ async function downloadedFile(input) {
108395
108520
  const bytes = await readFile96(input.localPath);
108396
108521
  return { path: input.localPath, bytes, mediaType: mediaTypeFor(input.localPath, bytes), representation: "original" };
108397
108522
  }
108398
- const tempRoot = await mkdtemp6(join119(tmpdir3(), "context-lark-resource-"));
108523
+ const tempRoot = await mkdtemp6(join120(tmpdir3(), "context-lark-resource-"));
108399
108524
  try {
108400
108525
  const representation = await downloadLarkMedia({ ...input, cwd: tempRoot });
108401
- const entries2 = (await readdir27(tempRoot, { withFileTypes: true })).filter((entry) => entry.isFile());
108526
+ const entries2 = (await readdir28(tempRoot, { withFileTypes: true })).filter((entry) => entry.isFile());
108402
108527
  if (entries2.length !== 1)
108403
108528
  throw new Error(`media download produced ${entries2.length} files, expected exactly one`);
108404
108529
  const path3 = entries2[0]?.name ?? "resource.bin";
108405
- const bytes = await readFile96(join119(tempRoot, path3));
108530
+ const bytes = await readFile96(join120(tempRoot, path3));
108406
108531
  return { path: path3, bytes, mediaType: mediaTypeFor(path3, bytes), representation };
108407
108532
  } finally {
108408
- await rm29(tempRoot, { recursive: true, force: true });
108533
+ await rm30(tempRoot, { recursive: true, force: true });
108409
108534
  }
108410
108535
  }
108411
108536
  function parseCsv(value) {
@@ -108474,9 +108599,9 @@ async function sheetMaterialization(resource, runner2, identity2) {
108474
108599
  const sheetId = resource.attributes["sheet-id"];
108475
108600
  if (token === undefined || sheetId === undefined)
108476
108601
  throw new Error("embedded Sheet requires token and sheet-id");
108477
- const tempRoot = await mkdtemp6(join119(tmpdir3(), "context-lark-sheet-"));
108602
+ const tempRoot = await mkdtemp6(join120(tmpdir3(), "context-lark-sheet-"));
108478
108603
  try {
108479
- const outputPath = join119(tempRoot, "sheet.json");
108604
+ const outputPath = join120(tempRoot, "sheet.json");
108480
108605
  const stdout = await runLarkResourceCommand(runner2, [
108481
108606
  "sheets",
108482
108607
  "+csv-get",
@@ -108491,7 +108616,7 @@ async function sheetMaterialization(resource, runner2, identity2) {
108491
108616
  "./sheet.json",
108492
108617
  "--format",
108493
108618
  "json"
108494
- ], { cwd: tempRoot });
108619
+ ], { cwd: tempRoot, scratchDirectory: true });
108495
108620
  const receipt2 = jsonPayload(stdout);
108496
108621
  if (findBooleanField(receipt2, "truncated") === true || findBooleanField(receipt2, "complete") === false) {
108497
108622
  throw new Error("embedded Sheet read was truncated");
@@ -108518,7 +108643,7 @@ ${markdownTable2(parseCsv(csv))}
108518
108643
  [CSV snapshot](${sourceAssetTarget(path3)}) <!-- ${resource.locator} -->`
108519
108644
  };
108520
108645
  } finally {
108521
- await rm29(tempRoot, { recursive: true, force: true });
108646
+ await rm30(tempRoot, { recursive: true, force: true });
108522
108647
  }
108523
108648
  }
108524
108649
  function basePageRecords(value) {
@@ -108738,7 +108863,9 @@ function assertBudget(asset, policy, total) {
108738
108863
  }
108739
108864
  }
108740
108865
  async function materializeLarkResources(input) {
108741
- input = { ...input, runner: createLarkResourceScheduler(input.runner) };
108866
+ const raw = input.runner;
108867
+ const timed = (args, options) => raw(args, { ...options, timeoutMs: options?.timeoutMs ?? RESOURCE_TIMEOUT_MS });
108868
+ input = { ...input, runner: createLarkResourceScheduler(timed) };
108742
108869
  const assets = [];
108743
108870
  const replacements = new Map;
108744
108871
  const items = [];
@@ -108753,6 +108880,10 @@ async function materializeLarkResources(input) {
108753
108880
  const required = REQUIRED_KINDS.has(resource.kind);
108754
108881
  if (omitLarkImage(resource, input.policy, items, replacements))
108755
108882
  return;
108883
+ if (omitLarkResourceByPolicy(resource, input.policy, items, replacements))
108884
+ return;
108885
+ if (resource.kind === "image" && input.budgetExcluded?.has(resource.locator) && omitLarkImage(resource, input.policy, items, replacements, undefined, "The earlier capture of this revision skipped it for exceeding the resource budget; it was not downloaded again"))
108886
+ return;
108756
108887
  try {
108757
108888
  if (resource.kind === "diagram" && resource.inline_content === true) {
108758
108889
  replacements.set(resource.locator, "");
@@ -108809,7 +108940,7 @@ async function materializeLarkResources(input) {
108809
108940
  throw new Error("synced reference nesting exceeds 4 levels");
108810
108941
  if (input.resolveSyncedReference === undefined)
108811
108942
  throw new Error("synced reference resolver is unavailable");
108812
- const projected = await input.resolveSyncedReference(resource);
108943
+ const projected = await input.resolveSyncedReference(resource, input.runner);
108813
108944
  const digest8 = resourceDigest(resource);
108814
108945
  const asset2 = {
108815
108946
  path: `materialized/synced-reference/${digest8}.md`,
@@ -108833,12 +108964,16 @@ async function materializeLarkResources(input) {
108833
108964
  const token = resourceToken(resource);
108834
108965
  if (token === undefined)
108835
108966
  throw new Error(`${resource.kind} has no downloadable token`);
108836
- const downloaded = await downloadedFile({
108967
+ const preloaded = reusable.get(key);
108968
+ reusable.delete(key);
108969
+ const reused = preloaded ?? (depth > 0 && (resource.kind === "image" || resource.kind === "file") ? await input.reuse?.(resource, identity2) : undefined);
108970
+ const downloaded = reused ?? await downloadedFile({
108837
108971
  runner: input.runner,
108838
108972
  identity: identity2,
108839
108973
  token,
108840
108974
  type: "media",
108841
108975
  allowPreview: resource.kind === "image",
108976
+ timeoutMs: resource.kind === "image" ? RESOURCE_TIMEOUT_MS : LARGE_RESOURCE_TIMEOUT_MS,
108842
108977
  ...input.mediaFiles?.[token] === undefined ? {} : { localPath: input.mediaFiles[token] }
108843
108978
  });
108844
108979
  if (omitLarkImage(resource, input.policy, items, replacements, downloaded.mediaType))
@@ -108887,7 +109022,20 @@ async function materializeLarkResources(input) {
108887
109022
  });
108888
109023
  }
108889
109024
  };
108890
- await forEachLarkResource(input.resources.filter((resource) => resource.kind !== "synced-reference"), (resource) => materialize(resource, 0));
109025
+ const reusable = new Map;
109026
+ if (input.reuse !== undefined) {
109027
+ for (const resource of input.resources) {
109028
+ if (resource.kind === "image" ? input.policy.images === "reference-only" || input.budgetExcluded?.has(resource.locator) : resource.kind !== "file" || input.policy.files === "reference-only")
109029
+ continue;
109030
+ const found = await input.reuse(resource, identity2);
109031
+ if (found !== undefined)
109032
+ reusable.set(`${resource.kind}\x00${resource.locator}`, found);
109033
+ }
109034
+ }
109035
+ const leaves = input.resources.filter((resource) => resource.kind !== "synced-reference");
109036
+ for (const resource of leaves.filter((resource2) => reusable.has(`${resource2.kind}\x00${resource2.locator}`)))
109037
+ await materialize(resource, 0);
109038
+ await forEachLarkResource(leaves.filter((resource) => !reusable.has(`${resource.kind}\x00${resource.locator}`)), (resource) => materialize(resource, 0));
108891
109039
  for (const resource of input.resources.filter((resource2) => resource2.kind === "synced-reference"))
108892
109040
  await materialize(resource, 0);
108893
109041
  items.sort((a2, b) => a2.locator.localeCompare(b.locator) || a2.kind.localeCompare(b.kind));
@@ -108917,7 +109065,7 @@ function applyLarkResourceReplacements(markdown, resources, replacements) {
108917
109065
  }
108918
109066
  return output;
108919
109067
  }
108920
- var REQUIRED_KINDS, MEDIA_TYPES_BY_EXTENSION;
109068
+ var RESOURCE_TIMEOUT_MS = 120000, LARGE_RESOURCE_TIMEOUT_MS = 300000, REQUIRED_KINDS, MEDIA_TYPES_BY_EXTENSION;
108921
109069
  var init_larkResourceMaterialization = __esm(() => {
108922
109070
  init_larkResourceScheduler();
108923
109071
  init_larkMediaDownload();
@@ -109114,6 +109262,13 @@ var init_larkReadIdentity = __esm(() => {
109114
109262
 
109115
109263
  // src/lib/feishu.ts
109116
109264
  import { spawn as spawn6 } from "node:child_process";
109265
+ function sameLarkRevision(earlier, revisionId, rawContentHash) {
109266
+ if (earlier === undefined)
109267
+ return false;
109268
+ if (revisionId !== undefined || earlier.revisionId !== undefined)
109269
+ return revisionId === earlier.revisionId;
109270
+ return rawContentHash !== undefined && rawContentHash === earlier.rawContentHash;
109271
+ }
109117
109272
  async function detectDocsFetchCapabilities(runner2) {
109118
109273
  const result = await runner2(["docs", "+fetch", "--help"]).catch(() => ({
109119
109274
  stdout: "",
@@ -109507,24 +109662,27 @@ async function fetchFeishuDocSnapshot(input, runner2 = defaultRunner) {
109507
109662
  };
109508
109663
  }
109509
109664
  const resources = [...new Map([...projection?.resources ?? [], ...larkMarkdownImageResources(body2)].map((resource) => [resource.locator, resource])).values()];
109665
+ const policy = {
109666
+ ...DEFAULT_RESOURCE_POLICY,
109667
+ ...input.resourcePolicy
109668
+ };
109510
109669
  if (resources.length) {
109511
- const policy = {
109512
- ...DEFAULT_RESOURCE_POLICY,
109513
- ...input.resourcePolicy
109514
- };
109670
+ const earlier = sameLarkRevision(input.reuseResources, revisionId, projection?.rawContentHash) ? input.reuseResources : undefined;
109515
109671
  const materialized = await materializeLarkResources({
109516
109672
  resources,
109517
109673
  runner: runner2,
109518
109674
  ...input.prefetched?.mediaFiles === undefined ? {} : { mediaFiles: input.prefetched.mediaFiles },
109675
+ ...earlier === undefined ? {} : { reuse: earlier.load },
109676
+ ...earlier?.budgetExcluded?.identity === accessIdentity ? { budgetExcluded: earlier.budgetExcluded.locators } : {},
109519
109677
  policy,
109520
109678
  identity: accessIdentity,
109521
- resolveSyncedReference: async (resource) => {
109679
+ resolveSyncedReference: async (resource, scheduled) => {
109522
109680
  const sourceToken = resource.attributes["src-token"];
109523
109681
  const blockId = resource.attributes["src-block-id"];
109524
109682
  if (sourceToken === undefined || blockId === undefined) {
109525
109683
  throw new LarkCliError("synced reference requires src-token and src-block-id", 0, "");
109526
109684
  }
109527
- const synced = await fetchDocsResponse({ url: sourceToken }, docsFetchPlan, runner2, accessIdentity);
109685
+ const synced = await fetchDocsResponse({ url: sourceToken }, docsFetchPlan, scheduled, accessIdentity);
109528
109686
  if (synced.contentFormat !== "xml") {
109529
109687
  throw new LarkCliError("synced reference source did not return XML", 0, "");
109530
109688
  }
@@ -109550,7 +109708,8 @@ async function fetchFeishuDocSnapshot(input, runner2 = defaultRunner) {
109550
109708
  fidelity,
109551
109709
  resourceMaterialization,
109552
109710
  resources,
109553
- access: access7
109711
+ access: access7,
109712
+ resourceBudget: { maxBytesPerResource: policy.maxBytesPerResource, maxTotalBytes: policy.maxTotalBytes }
109554
109713
  }));
109555
109714
  if (title2 !== undefined && title2.length > 0 && !/^#\s/.test(body2)) {
109556
109715
  return {
@@ -109585,12 +109744,28 @@ async function readPrefetchedLarkDocument(url, prefetched) {
109585
109744
  }, prefetched.identity);
109586
109745
  }
109587
109746
  var LARK_BIN = "lark-cli", MAX_FETCH_PAGES = 50, MAX_STRUCTURAL_FETCH_ATTEMPTS = 2, LarkCliNotInstalledError, LarkCliError, defaultRunner = (args, options) => new Promise((resolve8, reject) => {
109747
+ const timeoutMs = options?.timeoutMs;
109748
+ const group = timeoutMs !== undefined && process.platform !== "win32";
109588
109749
  const child = spawn6(process.env.CONTEXT_LARK_CLI_BIN?.trim() || LARK_BIN, args, {
109589
109750
  ...options?.cwd === undefined ? {} : { cwd: options.cwd },
109751
+ ...group ? { detached: true } : {},
109590
109752
  stdio: ["ignore", "pipe", "pipe"]
109591
109753
  });
109592
109754
  let stdout = "";
109593
109755
  let stderr = "";
109756
+ let timedOut = false;
109757
+ const timer2 = timeoutMs === undefined ? undefined : setTimeout(() => {
109758
+ if (child.exitCode !== null || child.signalCode !== null)
109759
+ return;
109760
+ timedOut = true;
109761
+ try {
109762
+ if (group && child.pid)
109763
+ process.kill(-child.pid, "SIGKILL");
109764
+ else
109765
+ child.kill("SIGKILL");
109766
+ } catch {}
109767
+ }, timeoutMs);
109768
+ timer2?.unref();
109594
109769
  child.stdout.on("data", (chunk) => {
109595
109770
  stdout += chunk.toString("utf8");
109596
109771
  });
@@ -109598,14 +109773,23 @@ var LARK_BIN = "lark-cli", MAX_FETCH_PAGES = 50, MAX_STRUCTURAL_FETCH_ATTEMPTS =
109598
109773
  stderr += chunk.toString("utf8");
109599
109774
  });
109600
109775
  child.on("error", (err) => {
109776
+ if (timer2 !== undefined)
109777
+ clearTimeout(timer2);
109601
109778
  if (err.code === "ENOENT") {
109602
109779
  reject(new LarkCliNotInstalledError);
109603
109780
  return;
109604
109781
  }
109605
109782
  reject(err);
109606
109783
  });
109784
+ child.on("exit", () => {
109785
+ if (timer2 !== undefined)
109786
+ clearTimeout(timer2);
109787
+ });
109607
109788
  child.on("close", (code3) => {
109608
- resolve8({ stdout, stderr, exitCode: code3 });
109789
+ if (timer2 !== undefined)
109790
+ clearTimeout(timer2);
109791
+ resolve8(timedOut ? { stdout, stderr: `${stderr}${stderr.length ? `
109792
+ ` : ""}${LARK_BIN} ${args.slice(0, 2).join(" ")} timed out after ${Math.round(timeoutMs / 1000)} s`, exitCode: null } : { stdout, stderr, exitCode: code3 });
109609
109793
  });
109610
109794
  }), DEFAULT_RESOURCE_POLICY, docsFetchCapabilitiesCache;
109611
109795
  var init_feishu = __esm(() => {
@@ -109668,13 +109852,20 @@ var init_sensitiveSourceLiteral = __esm(() => {
109668
109852
  // src/project/larkSnapshotBundle.ts
109669
109853
  import { createHash as createHash37 } from "node:crypto";
109670
109854
  import { lstat as lstat16, mkdir as mkdir39, readFile as readFile97, realpath as realpath15, rename as rename10, writeFile as writeFile30 } from "node:fs/promises";
109671
- import { basename as basename9, dirname as dirname47, isAbsolute as isAbsolute19, join as join120, relative as relative31, resolve as resolve37, sep as sep10 } from "node:path";
109855
+ import { basename as basename9, dirname as dirname47, isAbsolute as isAbsolute19, join as join121, relative as relative31, resolve as resolve37, sep as sep10 } from "node:path";
109672
109856
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
109673
109857
  function normalizedSnapshotResourcePolicy(policy) {
109674
- return { ...policy, images: policy.images ?? "bundle", gifs: policy.gifs ?? "bundle" };
109858
+ const { files, whiteboards, ...rest } = policy;
109859
+ return {
109860
+ ...rest,
109861
+ images: policy.images ?? "bundle",
109862
+ gifs: policy.gifs ?? "bundle",
109863
+ ...files === "reference-only" ? { files } : {},
109864
+ ...whiteboards === "reference-only" ? { whiteboards } : {}
109865
+ };
109675
109866
  }
109676
109867
  function assertSnapshotResourcePolicy(snapshot, expected) {
109677
- if (!isDeepStrictEqual2(snapshot.resourcePolicy, normalizedSnapshotResourcePolicy(expected))) {
109868
+ if (!isDeepStrictEqual2(normalizedSnapshotResourcePolicy(snapshot.resourcePolicy), normalizedSnapshotResourcePolicy(expected))) {
109678
109869
  throw new ContextError(ExitCode.UserError, "Saved Lark snapshot was captured with a different resource policy; import did not reinterpret or refetch its resources", {
109679
109870
  reason_code: "lark.snapshot-policy-mismatch",
109680
109871
  captured_policy: snapshot.resourcePolicy,
@@ -109709,7 +109900,7 @@ async function readFileEntry(root2, entry) {
109709
109900
  const parts = safePath(entry.path).split("/");
109710
109901
  let current3 = root2;
109711
109902
  for (const [index3, part] of parts.entries()) {
109712
- current3 = join120(current3, part);
109903
+ current3 = join121(current3, part);
109713
109904
  const stat11 = await lstat16(current3);
109714
109905
  if (stat11.isSymbolicLink() || (index3 === parts.length - 1 ? !stat11.isFile() : !stat11.isDirectory())) {
109715
109906
  throw larkSnapshotError(`Snapshot entry is not a regular file: ${entry.path}`, "path-invalid");
@@ -109778,13 +109969,13 @@ async function writeLarkSnapshotBundle(input) {
109778
109969
  };
109779
109970
  schema2.parse(manifest);
109780
109971
  for (const [path3, bytes] of files) {
109781
- await mkdir39(dirname47(join120(root2, path3)), { recursive: true });
109782
- await writeFile30(join120(root2, path3), bytes, { flag: "wx", mode: 384 });
109972
+ await mkdir39(dirname47(join121(root2, path3)), { recursive: true });
109973
+ await writeFile30(join121(root2, path3), bytes, { flag: "wx", mode: 384 });
109783
109974
  }
109784
109975
  await validateBundle(root2, manifest);
109785
- await writeFile30(join120(root2, `${FILE2}.pending`), `${JSON.stringify(manifest, null, 2)}
109976
+ await writeFile30(join121(root2, `${FILE2}.pending`), `${JSON.stringify(manifest, null, 2)}
109786
109977
  `, { flag: "wx", mode: 384 });
109787
- await rename10(join120(root2, `${FILE2}.pending`), join120(root2, FILE2));
109978
+ await rename10(join121(root2, `${FILE2}.pending`), join121(root2, FILE2));
109788
109979
  return manifest;
109789
109980
  }
109790
109981
  async function validateBundle(root2, manifest) {
@@ -109843,22 +110034,27 @@ async function validateBundle(root2, manifest) {
109843
110034
  throw larkSnapshotError(`Resource report references a missing asset: ${path3}`);
109844
110035
  }
109845
110036
  }
109846
- return { url: manifest.url, capturedAt: manifest.captured_at, resourcePolicy: manifest.resource_policy, fetched: {
109847
- markdown,
109848
- assets,
109849
- accessIdentity: manifest.access_identity,
109850
- identityFallback: false,
109851
- access: report.access ?? { identity: manifest.access_identity },
109852
- ...manifest.title === undefined ? {} : { title: manifest.title },
109853
- ...manifest.revision_id === undefined ? {} : { revisionId: manifest.revision_id },
109854
- fidelity: report.fidelity,
109855
- resourceMaterialization: { ...materialization, items: materialization.items.map((item) => ({ ...item, kind: item.kind })) }
109856
- } };
110037
+ return {
110038
+ url: manifest.url,
110039
+ capturedAt: manifest.captured_at,
110040
+ resourcePolicy: normalizedSnapshotResourcePolicy(manifest.resource_policy),
110041
+ fetched: {
110042
+ markdown,
110043
+ assets,
110044
+ accessIdentity: manifest.access_identity,
110045
+ identityFallback: false,
110046
+ access: report.access ?? { identity: manifest.access_identity },
110047
+ ...manifest.title === undefined ? {} : { title: manifest.title },
110048
+ ...manifest.revision_id === undefined ? {} : { revisionId: manifest.revision_id },
110049
+ fidelity: report.fidelity,
110050
+ resourceMaterialization: { ...materialization, items: materialization.items.map((item) => ({ ...item, kind: item.kind })) }
110051
+ }
110052
+ };
109857
110053
  }
109858
110054
  async function readLarkSnapshotBundle(directory, target) {
109859
110055
  try {
109860
110056
  const root2 = await assertSnapshotDirectory(directory);
109861
- const path3 = join120(root2, FILE2);
110057
+ const path3 = join121(root2, FILE2);
109862
110058
  const stat11 = await lstat16(path3);
109863
110059
  if (stat11.isSymbolicLink() || !stat11.isFile())
109864
110060
  throw larkSnapshotError("Snapshot receipt must be a regular file", "path-invalid");
@@ -109886,8 +110082,8 @@ async function reserveSnapshotDirectory(directory, workspaceRoot) {
109886
110082
  ancestor = dirname47(ancestor);
109887
110083
  }
109888
110084
  }
109889
- const parent2 = join120(ancestor, ...missing2);
109890
- const output = join120(parent2, basename9(requested));
110085
+ const parent2 = join121(ancestor, ...missing2);
110086
+ const output = join121(parent2, basename9(requested));
109891
110087
  const { findContextProjectRoot: findContextProjectRoot2 } = await Promise.resolve().then(() => (init_workspace(), exports_workspace));
109892
110088
  const owner = findContextProjectRoot2(parent2)?.projectRoot ?? workspaceRoot;
109893
110089
  if (owner !== undefined) {
@@ -109924,6 +110120,8 @@ var init_larkSnapshotBundle = __esm(() => {
109924
110120
  policySchema = exports_external.object({
109925
110121
  images: exports_external.enum(["bundle", "reference-only"]),
109926
110122
  gifs: exports_external.enum(["bundle", "reference-only"]),
110123
+ files: exports_external.enum(["bundle", "reference-only"]).optional(),
110124
+ whiteboards: exports_external.enum(["bundle", "reference-only"]).optional(),
109927
110125
  videos: exports_external.enum(["bundle", "reference-only"]),
109928
110126
  maxBytesPerResource: exports_external.number().int().positive(),
109929
110127
  maxTotalBytes: exports_external.number().int().positive()
@@ -109961,8 +110159,9 @@ var init_larkSnapshotBundle = __esm(() => {
109961
110159
 
109962
110160
  // src/project/documentCaptureLark.ts
109963
110161
  import { createHash as createHash38 } from "node:crypto";
109964
- import { readdir as readdir28, readFile as readFile98 } from "node:fs/promises";
109965
- import { basename as basename10, extname as extname14, join as join121 } from "node:path";
110162
+ import { readdir as readdir29, readFile as readFile98 } from "node:fs/promises";
110163
+ import { basename as basename10, extname as extname14, join as join122 } from "node:path";
110164
+ import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
109966
110165
  function titleFromMarkdown2(markdown, fallbackPath) {
109967
110166
  const heading2 = markdown.split(`
109968
110167
  `).find((line) => /^#\s+\S/u.test(line));
@@ -109989,7 +110188,7 @@ async function fileContentMatches(path3, content3) {
109989
110188
  }
109990
110189
  }
109991
110190
  function sourceManifestPath2(entry) {
109992
- return entry.snapshot?.manifest ?? join121(entry.materializedAt, "manifest.json");
110191
+ return entry.snapshot?.manifest ?? join122(entry.materializedAt, "manifest.json");
109993
110192
  }
109994
110193
  function larkRuntimeError(message, detail) {
109995
110194
  return new ContextError(ExitCode.ExternalToolError, message, {
@@ -110121,13 +110320,57 @@ function assetManifestEntry(asset, assetRoot) {
110121
110320
  ...asset.bytes !== undefined ? { bytes: asset.bytes } : {}
110122
110321
  };
110123
110322
  }
110323
+ function earlierLarkResources(projectRoot, materializedAt, manifest, budgetExcluded) {
110324
+ const byResource = new Map;
110325
+ for (const asset of manifest.assets ?? []) {
110326
+ const source2 = asset.source;
110327
+ if (asset.role !== "evidence" || source2?.kind !== "image" && source2?.kind !== "file" || !source2.locator || !source2.identity || !asset.content_hash || !asset.media_type)
110328
+ continue;
110329
+ byResource.set(`${source2.kind}\x00${source2.locator}`, asset);
110330
+ }
110331
+ if (byResource.size === 0 && budgetExcluded === undefined)
110332
+ return;
110333
+ const revisionId = manifest.metadata?.source?.revisionId;
110334
+ const rawContentHash = manifest.assets?.find((asset) => asset.source?.kind === "lark-docx-xml")?.source?.raw_content_hash;
110335
+ return {
110336
+ ...revisionId === undefined ? {} : { revisionId },
110337
+ ...rawContentHash === undefined ? {} : { rawContentHash },
110338
+ ...budgetExcluded === undefined ? {} : { budgetExcluded },
110339
+ load: async (resource, identity2) => {
110340
+ const asset = byResource.get(`${resource.kind}\x00${resource.locator}`);
110341
+ if (asset === undefined || asset.source?.identity !== identity2)
110342
+ return;
110343
+ let bytes;
110344
+ try {
110345
+ bytes = await readFile98(join122(projectRoot, materializedAt, asset.path));
110346
+ } catch {
110347
+ return;
110348
+ }
110349
+ if (computeDocumentContentHash(bytes) !== asset.content_hash)
110350
+ return;
110351
+ return {
110352
+ path: asset.path,
110353
+ bytes,
110354
+ mediaType: asset.media_type,
110355
+ representation: asset.source.representation === "preview" ? "preview" : "original"
110356
+ };
110357
+ }
110358
+ };
110359
+ }
110360
+ function budgetExcludedImages(report, policy) {
110361
+ const budget = report?.resource_budget;
110362
+ if (budget === undefined || report?.access === undefined || policy.maxBytesPerResource > budget.maxBytesPerResource || policy.maxTotalBytes > budget.maxTotalBytes)
110363
+ return;
110364
+ const locators = new Set(report.resources.filter((item) => item.kind === "image" && item.reason_code === "image-budget-exceeded").map((item) => item.locator));
110365
+ return locators.size === 0 ? undefined : { identity: report.access.identity, locators };
110366
+ }
110124
110367
  async function listSnapshotAssetFiles(root2, assetRoot) {
110125
- const assetsRoot = join121(root2, assetRoot);
110368
+ const assetsRoot = join122(root2, assetRoot);
110126
110369
  const files = [];
110127
110370
  const visit4 = async (dir, prefix = assetRoot) => {
110128
110371
  let entries2;
110129
110372
  try {
110130
- entries2 = await readdir28(dir, { withFileTypes: true });
110373
+ entries2 = await readdir29(dir, { withFileTypes: true });
110131
110374
  } catch (error) {
110132
110375
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
110133
110376
  return;
@@ -110135,7 +110378,7 @@ async function listSnapshotAssetFiles(root2, assetRoot) {
110135
110378
  }
110136
110379
  for (const entry of entries2) {
110137
110380
  const relPath = `${prefix}/${entry.name}`;
110138
- const absolutePath = join121(dir, entry.name);
110381
+ const absolutePath = join122(dir, entry.name);
110139
110382
  if (entry.isDirectory()) {
110140
110383
  await visit4(absolutePath, relPath);
110141
110384
  continue;
@@ -110150,7 +110393,7 @@ async function listSnapshotAssetFiles(root2, assetRoot) {
110150
110393
  }
110151
110394
  async function staleSnapshotAssetPaths(input) {
110152
110395
  const existingPaths = await listSnapshotAssetFiles(input.materializedAtAbsPath, input.assetRoot);
110153
- return existingPaths.filter((path3) => !input.currentPaths.has(path3)).map((path3) => join121(input.materializedAtAbsPath, path3));
110396
+ return existingPaths.filter((path3) => !input.currentPaths.has(path3)).map((path3) => join122(input.materializedAtAbsPath, path3));
110154
110397
  }
110155
110398
  function normalizeLarkError(error, sourceName) {
110156
110399
  if (error instanceof ContextError)
@@ -110214,7 +110457,7 @@ async function runCaptureLarkPhaseUnlocked(input) {
110214
110457
  const target = larkTarget(entry);
110215
110458
  const manifestPath = sourceManifestPath2(entry);
110216
110459
  const materializedAt = entry.materializedAt;
110217
- const materializedAtAbsPath = join121(input.projectRoot, materializedAt);
110460
+ const materializedAtAbsPath = join122(input.projectRoot, materializedAt);
110218
110461
  const { current: currentManifestFile, previous: previousManifest, recovery } = await readDocumentManifestForCapture({
110219
110462
  projectRoot: input.projectRoot,
110220
110463
  manifestPath,
@@ -110224,7 +110467,16 @@ async function runCaptureLarkPhaseUnlocked(input) {
110224
110467
  const fingerprint = previousManifest === null || larkSnapshotIdentityDiagnostic(entry, previousManifest) !== null ? undefined : await larkSnapshotFingerprint(input.projectRoot, materializedAt, previousManifest);
110225
110468
  const refresh = input.refreshSources?.includes(`lark:${resolved.sourceName}`) === true;
110226
110469
  const previousRevision = (fingerprint === undefined ? undefined : await checkedLarkRevision(input.projectRoot, resolved.sourceName, fingerprint)) ?? previousManifest?.metadata?.source?.revisionId;
110227
- const unchangedRevisionId = !refresh && !input.prefetched && !recovery && Object.entries(input.phase.resources ?? {}).every(([key, value]) => value === DEFAULT_RESOURCE_POLICY[key]) && previousManifest?.normalizer_version === LARK_DOCUMENT_NORMALIZER_VERSION && fingerprint !== undefined ? previousRevision : undefined;
110470
+ const unchangedRevisionId = !refresh && !input.prefetched && !recovery && isDeepStrictEqual3(normalizedSnapshotResourcePolicy({ ...DEFAULT_RESOURCE_POLICY, ...input.phase.resources }), normalizedSnapshotResourcePolicy(DEFAULT_RESOURCE_POLICY)) && previousManifest?.normalizer_version === LARK_DOCUMENT_NORMALIZER_VERSION && fingerprint !== undefined ? previousRevision : undefined;
110471
+ let reuseResources;
110472
+ if (previousManifest !== null && !recovery && !input.prefetched && larkSnapshotIdentityDiagnostic(entry, previousManifest) === null) {
110473
+ try {
110474
+ const report = readDocumentSnapshotCaptureReport({ projectRoot: input.projectRoot, materializedAt, manifest: previousManifest });
110475
+ if (documentSnapshotFidelityState(previousManifest, report).resourceMaterialization?.status === "error") {
110476
+ reuseResources = earlierLarkResources(input.projectRoot, materializedAt, previousManifest, budgetExcludedImages(report, { ...DEFAULT_RESOURCE_POLICY, ...input.phase.resources }));
110477
+ }
110478
+ } catch {}
110479
+ }
110228
110480
  await beginFormatOnlyUpdate(input.projectRoot);
110229
110481
  let unchangedAccess;
110230
110482
  if (typeof unchangedRevisionId === "string" && previousManifest !== null) {
@@ -110246,6 +110498,7 @@ async function runCaptureLarkPhaseUnlocked(input) {
110246
110498
  url: target.value,
110247
110499
  resourcePolicy: input.phase.resources,
110248
110500
  requireCompleteBody: true,
110501
+ ...reuseResources === undefined ? {} : { reuseResources },
110249
110502
  ...typeof unchangedRevisionId === "string" ? { unchangedRevisionId } : {},
110250
110503
  ...unchangedAccess === undefined ? {} : { unchangedAccess },
110251
110504
  accessEvents,
@@ -110312,7 +110565,7 @@ async function runCaptureLarkPhaseUnlocked(input) {
110312
110565
  manifest: previousManifest
110313
110566
  }));
110314
110567
  let lost = fetched.resourceMaterialization.items.filter((item) => previous3.resourceMaterialization?.items.some((old) => old.kind === item.kind && old.locator === item.locator && old.status === "materialized" && (item.status !== "materialized" || item.reason_code === "document.resource.preview" && old.reason_code !== "document.resource.preview")));
110315
- degraded = lost.filter((item) => item.status === "materialized" || isNonBlockingDocumentResourceFailureReasonCode(item.reason_code));
110568
+ degraded = lost.filter((item) => item.status === "materialized" || isNonBlockingDocumentResourceFailureReasonCode(item.reason_code) || LARK_POLICY_EXCLUSION_REASON_CODES.has(item.reason_code ?? ""));
110316
110569
  lost = lost.filter((item) => !degraded.includes(item));
110317
110570
  if (lost.length)
110318
110571
  throw new ContextError(ExitCode.WorkspaceStateError, "Previously captured resources were degraded; the existing snapshot was preserved. Check resource policy and access before retrying the explicit refresh.", {
@@ -110361,7 +110614,7 @@ async function runCaptureLarkPhaseUnlocked(input) {
110361
110614
  title: title2,
110362
110615
  locator
110363
110616
  }];
110364
- const manifestAbsPath = join121(input.projectRoot, manifestPath);
110617
+ const manifestAbsPath = join122(input.projectRoot, manifestPath);
110365
110618
  const manifest = createDocumentSnapshotManifest({
110366
110619
  sourceType: "lark",
110367
110620
  sourceName: resolved.sourceName,
@@ -110391,13 +110644,13 @@ async function runCaptureLarkPhaseUnlocked(input) {
110391
110644
  const cacheDiagnostics = [];
110392
110645
  try {
110393
110646
  const requestedWrites = [{
110394
- path: join121(materializedAtAbsPath, documentPath),
110647
+ path: join122(materializedAtAbsPath, documentPath),
110395
110648
  bytes: normalized
110396
110649
  }];
110397
110650
  for (const asset of assets) {
110398
110651
  if (asset.bytes !== undefined) {
110399
110652
  requestedWrites.push({
110400
- path: join121(materializedAtAbsPath, asset.entry.path),
110653
+ path: join122(materializedAtAbsPath, asset.entry.path),
110401
110654
  bytes: asset.bytes
110402
110655
  });
110403
110656
  }
@@ -110431,7 +110684,7 @@ async function runCaptureLarkPhaseUnlocked(input) {
110431
110684
  if (relativePath in capturedFiles)
110432
110685
  continue;
110433
110686
  try {
110434
- capturedFiles[relativePath] = `sha256:${createHash38("sha256").update(await readFile98(join121(input.projectRoot, relativePath))).digest("hex")}`;
110687
+ capturedFiles[relativePath] = `sha256:${createHash38("sha256").update(await readFile98(join122(input.projectRoot, relativePath))).digest("hex")}`;
110435
110688
  } catch (error) {
110436
110689
  if (error.code === "ENOENT")
110437
110690
  capturedFiles[relativePath] = null;
@@ -110440,7 +110693,7 @@ async function runCaptureLarkPhaseUnlocked(input) {
110440
110693
  }
110441
110694
  }
110442
110695
  await applyAtomicFileBatch({
110443
- transactionRoot: join121(input.projectRoot, ".tmp", "context-runtime", "capture-transactions"),
110696
+ transactionRoot: join122(input.projectRoot, ".tmp", "context-runtime", "capture-transactions"),
110444
110697
  writes,
110445
110698
  removals
110446
110699
  });
@@ -110548,6 +110801,7 @@ var init_documentCaptureLark = __esm(() => {
110548
110801
  init_writeLock();
110549
110802
  init_sensitiveSourceLiteral();
110550
110803
  init_larkSnapshotBundle();
110804
+ init_larkImagePolicy();
110551
110805
  init_larkCaptureFreshness();
110552
110806
  init_documentSnapshotFidelity();
110553
110807
  init_formatOnlyUpdate();
@@ -110625,8 +110879,8 @@ __export(exports_writeLockRecovery, {
110625
110879
  recoverWriterLock: () => recoverWriterLock,
110626
110880
  inspectWriterLock: () => inspectWriterLock
110627
110881
  });
110628
- import { lstat as lstat17, mkdir as mkdir41, readFile as readFile104, readdir as readdir29, rename as rename11, rmdir as rmdir2 } from "node:fs/promises";
110629
- import { join as join126 } from "node:path";
110882
+ import { lstat as lstat17, mkdir as mkdir41, readFile as readFile104, readdir as readdir30, rename as rename11, rmdir as rmdir2 } from "node:fs/promises";
110883
+ import { join as join127 } from "node:path";
110630
110884
  import { createHash as createHash40, randomUUID as randomUUID8 } from "node:crypto";
110631
110885
  async function inspectWriterLock(root2) {
110632
110886
  const path3 = await safeProjectTarget(root2, lockRelative);
@@ -110677,19 +110931,19 @@ async function recoverWriterLock(input) {
110677
110931
  };
110678
110932
  if (input.plan_digest !== revision)
110679
110933
  throw new Error("Writer lock or transactions changed; preview recovery again.");
110680
- const path3 = join126(input.projectRoot, lockRelative);
110681
- const guard = join126(path3, ".recovery");
110934
+ const path3 = join127(input.projectRoot, lockRelative);
110935
+ const guard = join127(path3, ".recovery");
110682
110936
  await mkdir41(guard);
110683
110937
  let archived = false;
110684
110938
  try {
110685
110939
  const current3 = await inspectWriterLock(input.projectRoot);
110686
110940
  if (current3?.digest !== before.digest || current3.process_state !== "not-running")
110687
110941
  throw new Error("Writer lock changed or owner resumed; keep the lock.");
110688
- const names = await readdir29(path3);
110942
+ const names = await readdir30(path3);
110689
110943
  if (names.some((name3) => name3 !== "owner.json" && name3 !== ".recovery"))
110690
110944
  throw new Error("Unexpected lock contents; preserve for diagnosis.");
110691
110945
  const archive = `.tmp/context-runtime/locks/recovered-write-${randomUUID8()}.lock`;
110692
- await rename11(path3, join126(input.projectRoot, archive));
110946
+ await rename11(path3, join127(input.projectRoot, archive));
110693
110947
  archived = true;
110694
110948
  const receipts = await withProjectWriteLock(input.projectRoot, "recover-writer-transactions", async () => {
110695
110949
  if (JSON.stringify(await recoveryJournals(input.projectRoot)) !== JSON.stringify(journals)) {
@@ -110722,8 +110976,8 @@ __export(exports_taskRecovery, {
110722
110976
  RECOVERY_COMMAND: () => RECOVERY_COMMAND
110723
110977
  });
110724
110978
  import { existsSync as existsSync32 } from "node:fs";
110725
- import { basename as basename11, dirname as dirname50, join as join127 } from "node:path";
110726
- import { lstat as lstat18, readdir as readdir30, readFile as readFile105 } from "node:fs/promises";
110979
+ import { basename as basename11, dirname as dirname50, join as join128 } from "node:path";
110980
+ import { lstat as lstat18, readdir as readdir31, readFile as readFile105 } from "node:fs/promises";
110727
110981
  async function recoveryText(root2, path3) {
110728
110982
  const target = await safeProjectTarget(root2, path3);
110729
110983
  try {
@@ -110740,7 +110994,7 @@ async function recoveryJournals(root2) {
110740
110994
  await safeProjectTarget(root2, path3);
110741
110995
  let stat11;
110742
110996
  try {
110743
- stat11 = await lstat18(join127(root2, path3));
110997
+ stat11 = await lstat18(join128(root2, path3));
110744
110998
  } catch (error) {
110745
110999
  if (error.code === "ENOENT")
110746
111000
  return;
@@ -110751,7 +111005,7 @@ async function recoveryJournals(root2) {
110751
111005
  if (stat11.isDirectory()) {
110752
111006
  if (depth > 3)
110753
111007
  throw new TypeError("Unexpected transaction directory depth; preserve it for diagnosis.");
110754
- for (const name3 of (await readdir30(join127(root2, path3))).sort())
111008
+ for (const name3 of (await readdir31(join128(root2, path3))).sort())
110755
111009
  await visit4(`${path3}/${name3}`, depth + 1);
110756
111010
  } else if (stat11.isFile())
110757
111011
  entries2.push({ path: path3, digest: indexerProtocolDigest(await recoveryText(root2, path3)) });
@@ -110763,8 +111017,8 @@ function recoveryResources() {
110763
111017
  try {
110764
111018
  const root2 = dirname50(contextWorkflowProviderPath());
110765
111019
  const resources = {
110766
- skill: join127(root2, "skills/recover-workspace/SKILL.md"),
110767
- issue_template: join127(root2, "resources/templates/recovery-issue.md")
111020
+ skill: join128(root2, "skills/recover-workspace/SKILL.md"),
111021
+ issue_template: join128(root2, "resources/templates/recovery-issue.md")
110768
111022
  };
110769
111023
  if (!Object.values(resources).every((path3) => existsSync32(path3)))
110770
111024
  throw new Error("Recovery resources are absent from this Provider.");
@@ -110880,7 +111134,7 @@ __export(exports_taskLocalSourceAdjustment, {
110880
111134
  adjustLocalRevisionSources: () => adjustLocalRevisionSources
110881
111135
  });
110882
111136
  import { readFile as readFile106 } from "node:fs/promises";
110883
- import { join as join128 } from "node:path";
111137
+ import { join as join129 } from "node:path";
110884
111138
  async function adjustLocalRevisionSources(root2, input) {
110885
111139
  const { readMaintenance: readMaintenance2 } = await Promise.resolve().then(() => (init_maintenanceStorage(), exports_maintenanceStorage));
110886
111140
  if ((await readMaintenance2(root2)).active && await readProductionStage(root2))
@@ -110926,7 +111180,7 @@ async function adjustLocalRevisionSources(root2, input) {
110926
111180
  if (input.refresh && (!current3.refresh_sources || indexerProtocolDigest([...current3.refresh_sources].sort()) !== indexerProtocolDigest([...selected].sort()))) {
110927
111181
  throw new TypeError("No matching acquisition adjustment exists. Run task adjust without refresh first.");
110928
111182
  }
110929
- const raw = await readFile106(join128(root2, await revisionStoragePath(root2)), "utf8");
111183
+ const raw = await readFile106(join129(root2, await revisionStoragePath(root2)), "utf8");
110930
111184
  let next2;
110931
111185
  const discardIds = new Set;
110932
111186
  if (!refresh) {
@@ -111041,7 +111295,7 @@ ${input.instruction}` : revision.instruction
111041
111295
  content: content3
111042
111296
  }];
111043
111297
  if (discardIds.size > 0) {
111044
- const ledger = await readFile106(join128(root2, CANDIDATE_LEDGER_FILE), "utf8").catch((error) => {
111298
+ const ledger = await readFile106(join129(root2, CANDIDATE_LEDGER_FILE), "utf8").catch((error) => {
111045
111299
  if (error.code === "ENOENT")
111046
111300
  return;
111047
111301
  throw error;
@@ -111389,7 +111643,7 @@ __export(exports_approvedRevisionSubmission, {
111389
111643
  prepareApprovedRevisionSubmission: () => prepareApprovedRevisionSubmission,
111390
111644
  completeApprovedRevisionSubmission: () => completeApprovedRevisionSubmission
111391
111645
  });
111392
- import { join as join130 } from "node:path";
111646
+ import { join as join131 } from "node:path";
111393
111647
  function paused(message, managed, authorities = []) {
111394
111648
  return new ContextError(ExitCode.WorkspaceStateError, message, {
111395
111649
  category: ErrorCategory.WorkspaceStateInvalid,
@@ -111444,9 +111698,9 @@ async function prepareApprovedRevisionSubmission(input) {
111444
111698
  const { route, requests, contexts, issued } = await issueRevisionBatch(input);
111445
111699
  const stage = stageId(issued);
111446
111700
  const directory = productionAgentDirectory(stage);
111447
- await atomicWriteFile(await safeProjectTarget(input.projectRoot, join130(directory, "issued.json")), JSON.stringify(issued));
111701
+ await atomicWriteFile(await safeProjectTarget(input.projectRoot, join131(directory, "issued.json")), JSON.stringify(issued));
111448
111702
  for (const [index3, request] of requests.entries()) {
111449
- await atomicWriteFile(await safeProjectTarget(input.projectRoot, join130(directory, `${issued.tasks[index3].task}.input.json`)), JSON.stringify({
111703
+ await atomicWriteFile(await safeProjectTarget(input.projectRoot, join131(directory, `${issued.tasks[index3].task}.input.json`)), JSON.stringify({
111450
111704
  stage: "approved-revision",
111451
111705
  revision: request.revision,
111452
111706
  instruction: request.instruction,
@@ -111461,7 +111715,7 @@ async function prepareApprovedRevisionSubmission(input) {
111461
111715
  tasks: issued.tasks.map((task, index3) => ({
111462
111716
  ...task,
111463
111717
  path: requests[index3].target.path,
111464
- task_input: join130(directory, `${task.task}.input.json`)
111718
+ task_input: join131(directory, `${task.task}.input.json`)
111465
111719
  })),
111466
111720
  submission: { stage, tasks: issued.tasks.map((task) => ({ task: task.task, input: task.input, edits: `${task.task}.edits.json` })) },
111467
111721
  next_action: {
@@ -111830,7 +112084,7 @@ __export(exports_managedDocumentRename, {
111830
112084
  renameManagedDocument: () => renameManagedDocument
111831
112085
  });
111832
112086
  import { readFile as readFile117 } from "node:fs/promises";
111833
- import { join as join142, posix as posix15 } from "node:path";
112087
+ import { join as join143, posix as posix15 } from "node:path";
111834
112088
  async function optionalText3(path3) {
111835
112089
  try {
111836
112090
  return await readFile117(path3, "utf8");
@@ -111917,7 +112171,7 @@ async function renameManagedDocument(input) {
111917
112171
  if (path3.split("/").includes("..") || path3.startsWith("/"))
111918
112172
  throw new TypeError("Source references contain an unsafe knowledge path; repair it before renaming.");
111919
112173
  await safeProjectTarget(input.projectRoot, path3);
111920
- const before = await optionalText3(join142(input.projectRoot, path3));
112174
+ const before = await optionalText3(join143(input.projectRoot, path3));
111921
112175
  if (before === undefined)
111922
112176
  continue;
111923
112177
  let after;
@@ -112075,7 +112329,7 @@ var init_originalRevisionsCommand = __esm(() => {
112075
112329
 
112076
112330
  // src/cli.ts
112077
112331
  import { existsSync as existsSync41, realpathSync as realpathSync3 } from "node:fs";
112078
- import { dirname as dirname57, join as join148 } from "node:path";
112332
+ import { dirname as dirname57, join as join149 } from "node:path";
112079
112333
  import { fileURLToPath as fileURLToPath12, pathToFileURL as pathToFileURL3 } from "node:url";
112080
112334
 
112081
112335
  // ../../node_modules/.bun/commander@11.1.0/node_modules/commander/esm.mjs
@@ -116856,14 +117110,14 @@ function compactJsonResult(result, verbose) {
116856
117110
  // src/project/runLog.ts
116857
117111
  import { randomUUID as randomUUID6 } from "node:crypto";
116858
117112
  import { mkdir as mkdir40, writeFile as writeFile31 } from "node:fs/promises";
116859
- import { dirname as dirname48, join as join122 } from "node:path";
117113
+ import { dirname as dirname48, join as join123 } from "node:path";
116860
117114
  var createPhaseRunId = () => {
116861
117115
  const timestamp = new Date().toISOString().replace(/[-:.TZ]/gu, "");
116862
117116
  return `run_${timestamp}_${randomUUID6().slice(0, 8)}`;
116863
117117
  };
116864
117118
  async function writePhaseRunLog(input) {
116865
- const relPath = join122(".tmp", "context-runtime", "runs", `${input.runId}.json`);
116866
- const absPath = join122(input.projectRoot, relPath);
117119
+ const relPath = join123(".tmp", "context-runtime", "runs", `${input.runId}.json`);
117120
+ const absPath = join123(input.projectRoot, relPath);
116867
117121
  await mkdir40(dirname48(absPath), { recursive: true });
116868
117122
  await writeFile31(absPath, `${JSON.stringify({
116869
117123
  run_id: input.runId,
@@ -118112,7 +118366,7 @@ init_durableSingleFileTransaction();
118112
118366
  init_reviewShared();
118113
118367
  import { existsSync as existsSync30 } from "node:fs";
118114
118368
  import { readFile as readFile99 } from "node:fs/promises";
118115
- import { join as join123 } from "node:path";
118369
+ import { join as join124 } from "node:path";
118116
118370
  function existingTimestamp(markdown) {
118117
118371
  if (markdown === undefined)
118118
118372
  return;
@@ -118139,7 +118393,7 @@ async function prepareApprovedPage(input) {
118139
118393
  next: "Refresh the current production or article revision, then reopen Review before approval."
118140
118394
  });
118141
118395
  }
118142
- const relPath = join123("knowledge", input.record.path);
118396
+ const relPath = join124("knowledge", input.record.path);
118143
118397
  const existingView = findApprovedPageForArticleId(input.record.indexer_candidate.artifact_ref, input.approvedPageIndex);
118144
118398
  const previousPath = input.record.approved_revision?.previous_path;
118145
118399
  if (previousPath !== undefined && (!isSafeKnowledgeTargetPath(previousPath.split("/")[0], previousPath) || previousPath.includes("\\")))
@@ -118154,13 +118408,13 @@ async function prepareApprovedPage(input) {
118154
118408
  next: "Resolve the approved page path migration explicitly before approving this candidate."
118155
118409
  });
118156
118410
  }
118157
- const absPath = join123(input.projectRoot, relPath);
118411
+ const absPath = join124(input.projectRoot, relPath);
118158
118412
  const existing = existsSync30(absPath) ? await readFile99(absPath, "utf8") : undefined;
118159
118413
  let previous3;
118160
118414
  if (previousPath !== undefined) {
118161
118415
  if (existing !== undefined || existingView?.relPath !== `knowledge/${previousPath}`)
118162
118416
  throw new TypeError("Page move destination or original identity changed; refresh its revision.");
118163
- previous3 = { path: `knowledge/${previousPath}`, content: await readFile99(join123(input.projectRoot, "knowledge", previousPath), "utf8") };
118417
+ previous3 = { path: `knowledge/${previousPath}`, content: await readFile99(join124(input.projectRoot, "knowledge", previousPath), "utf8") };
118164
118418
  }
118165
118419
  if (input.record.approved_revision !== undefined) {
118166
118420
  const base = previous3?.content ?? existing;
@@ -118207,7 +118461,7 @@ async function prepareApprovedPage(input) {
118207
118461
  }
118208
118462
  async function readProjectFileMaybe(projectRoot, relPath) {
118209
118463
  try {
118210
- return await readFile99(join123(projectRoot, relPath), "utf8");
118464
+ return await readFile99(join124(projectRoot, relPath), "utf8");
118211
118465
  } catch (error) {
118212
118466
  if (error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT") {
118213
118467
  return;
@@ -118428,7 +118682,7 @@ async function applyReviewDecisions(input) {
118428
118682
  });
118429
118683
  }
118430
118684
  seenApprovedIds.set(approvedRef, row.candidate_id);
118431
- const approvedPath = join123("knowledge", row.path);
118685
+ const approvedPath = join124("knowledge", row.path);
118432
118686
  const previousPathCandidate = seenApprovedPaths.get(knowledgeTargetPathKey(approvedPath));
118433
118687
  if (previousPathCandidate !== undefined) {
118434
118688
  throw new ContextError(ExitCode.UserError, `multiple approved review decisions target the same knowledge path: ${approvedPath}`, {
@@ -118478,7 +118732,7 @@ async function applyReviewDecisions(input) {
118478
118732
  for (const path3 of approvedPageIndex.byRelPath.keys()) {
118479
118733
  if (pagesToWrite.some((page) => page.relPath === path3 || page.previous?.path === path3))
118480
118734
  continue;
118481
- const before = await readFile99(join123(input.projectRoot, path3), "utf8");
118735
+ const before = await readFile99(join124(input.projectRoot, path3), "utf8");
118482
118736
  const local = path3.replace(/^knowledge\//u, "");
118483
118737
  const after = moveKnowledgeLinkTargets2(before, local, local, moved);
118484
118738
  navigationTargets.push(reviewFileTarget({ path: path3, baseContent: before, targetContent: after }));
@@ -118569,12 +118823,12 @@ init_candidateLedger();
118569
118823
 
118570
118824
  // src/project/localHtmlReport.ts
118571
118825
  import { execFile as execFile18 } from "node:child_process";
118572
- import { isAbsolute as isAbsolute20, join as join124 } from "node:path";
118826
+ import { isAbsolute as isAbsolute20, join as join125 } from "node:path";
118573
118827
  import { pathToFileURL as pathToFileURL2 } from "node:url";
118574
118828
  import { promisify as promisify15 } from "node:util";
118575
118829
  var execFileAsync4 = promisify15(execFile18);
118576
118830
  function htmlReportReference(input) {
118577
- const absolutePath = isAbsolute20(input.path) ? input.path : join124(input.projectRoot, input.path);
118831
+ const absolutePath = isAbsolute20(input.path) ? input.path : join125(input.projectRoot, input.path);
118578
118832
  return {
118579
118833
  format: "html",
118580
118834
  path: input.path,
@@ -119763,7 +120017,7 @@ init_maintenanceStorage();
119763
120017
  init_productionFeedback();
119764
120018
  import { randomUUID as randomUUID7 } from "node:crypto";
119765
120019
  import { readFile as readFile103 } from "node:fs/promises";
119766
- import { join as join125 } from "node:path";
120020
+ import { join as join126 } from "node:path";
119767
120021
  async function beginProductionRevision(input) {
119768
120022
  return withProductionFeedback({ operation: "revision" }, () => withProjectWriteLock(input.projectRoot, "production-revision", async () => {
119769
120023
  await recoverDurableMultiFileTransactions(input.projectRoot);
@@ -119802,7 +120056,7 @@ async function beginProductionRevision(input) {
119802
120056
  const formal = approved.byPath.get(path3);
119803
120057
  if (!prior && !formal)
119804
120058
  throw invalid3("Write the current task first; there is no article draft to revise yet.");
119805
- const markdown = prior?.body ?? await readFile103(await safeProjectTarget(input.projectRoot, join125("knowledge", path3)), "utf8");
120059
+ const markdown = prior?.body ?? await readFile103(await safeProjectTarget(input.projectRoot, join126("knowledge", path3)), "utf8");
119806
120060
  const sections = prior?.indexer_candidate.sections.map((section) => ({ id: section.section_key, references: section.references })) ?? formal?.sections;
119807
120061
  const sources = [];
119808
120062
  for (const source2 of owner.sources) {
@@ -120340,7 +120594,7 @@ function registerVersionCommands(program2) {
120340
120594
 
120341
120595
  // src/commands/translateCommands.ts
120342
120596
  init_workspace();
120343
- import { isAbsolute as isAbsolute22, join as join129 } from "node:path";
120597
+ import { isAbsolute as isAbsolute22, join as join130 } from "node:path";
120344
120598
  init_status();
120345
120599
  init_workflowCommandOptions();
120346
120600
  init_workflowExecutionContext();
@@ -120434,7 +120688,7 @@ function registerTranslateCommands(program2) {
120434
120688
  readFailureNext: "Check the input path",
120435
120689
  parseFailureNext: "Use valid YAML or JSON"
120436
120690
  }));
120437
- const saved = await submitSiteTranslation(root2, await projectPackages(root2), value, (file) => isAbsolute22(file) ? file : join129(root2, file));
120691
+ const saved = await submitSiteTranslation(root2, await projectPackages(root2), value, (file) => isAbsolute22(file) ? file : join130(root2, file));
120438
120692
  write(await withWorkflow(root2, { outcome: "submitted", ...saved }));
120439
120693
  });
120440
120694
  command3.command("skip").description("Publish the current pending translations in the primary language").requiredOption("--digest <digest>", "expected_digest from context translate prepare").option("--format <format>", "json", "json").action(async (options) => {
@@ -120532,7 +120786,7 @@ init_workflowRouteOutput();
120532
120786
  var import_yaml57 = __toESM(require_dist(), 1);
120533
120787
  import { Buffer as Buffer5 } from "node:buffer";
120534
120788
  import { createHash as createHash41 } from "node:crypto";
120535
- import { join as join131 } from "node:path";
120789
+ import { join as join132 } from "node:path";
120536
120790
  var INLINE_LIMIT = 16 * 1024;
120537
120791
  function record4(value) {
120538
120792
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
@@ -120558,8 +120812,8 @@ async function prepareActionCompletionOutput(input) {
120558
120812
  if (production && Buffer5.byteLength(full) <= INLINE_LIMIT)
120559
120813
  return input.result;
120560
120814
  const digest8 = createHash41("sha256").update(full).digest("hex");
120561
- const root2 = join131(input.projectRoot, ".tmp/context-runtime/action-results");
120562
- const resultFile = join131(root2, `${digest8}.json`);
120815
+ const root2 = join132(input.projectRoot, ".tmp/context-runtime/action-results");
120816
+ const resultFile = join132(root2, `${digest8}.json`);
120563
120817
  await atomicWriteFile(resultFile, full);
120564
120818
  if (production)
120565
120819
  return {
@@ -120841,9 +121095,9 @@ function registerProjectActionCommands(program2) {
120841
121095
  // src/commands/cleanClaudePluginCache.ts
120842
121096
  init_cliFeedback();
120843
121097
  import { existsSync as existsSync33 } from "node:fs";
120844
- import { readdir as readdir31, rm as rm30 } from "node:fs/promises";
121098
+ import { readdir as readdir32, rm as rm31 } from "node:fs/promises";
120845
121099
  import { homedir } from "node:os";
120846
- import { join as join132 } from "node:path";
121100
+ import { join as join133 } from "node:path";
120847
121101
  var ORPHAN_MARKER = ".orphaned_at";
120848
121102
  var CLAUDE_PLUGIN_CACHE_ROOT_ENV = "C4A_CLAUDE_PLUGIN_CACHE_ROOT";
120849
121103
  var CLAUDE_PLUGIN_CACHE_HOME_ENV = "C4A_CLAUDE_PLUGIN_CACHE_HOME";
@@ -120856,40 +121110,40 @@ async function cleanClaudePluginCache(opts = {}) {
120856
121110
  lines.push("· claude plugin cache: missing — nothing to clean");
120857
121111
  return { lines, removed, scanned };
120858
121112
  }
120859
- const marketplaces = await readdir31(cacheRoot, { withFileTypes: true });
121113
+ const marketplaces = await readdir32(cacheRoot, { withFileTypes: true });
120860
121114
  for (const mp of marketplaces) {
120861
121115
  if (!mp.isDirectory())
120862
121116
  continue;
120863
- const mpDir = join132(cacheRoot, mp.name);
120864
- const plugins = await readdir31(mpDir, { withFileTypes: true });
121117
+ const mpDir = join133(cacheRoot, mp.name);
121118
+ const plugins = await readdir32(mpDir, { withFileTypes: true });
120865
121119
  for (const pl of plugins) {
120866
121120
  if (!pl.isDirectory())
120867
121121
  continue;
120868
- const plDir = join132(mpDir, pl.name);
120869
- const versions = await readdir31(plDir, { withFileTypes: true });
121122
+ const plDir = join133(mpDir, pl.name);
121123
+ const versions = await readdir32(plDir, { withFileTypes: true });
120870
121124
  for (const ver of versions) {
120871
121125
  if (!ver.isDirectory())
120872
121126
  continue;
120873
121127
  scanned += 1;
120874
- const verDir = join132(plDir, ver.name);
120875
- const markerPath = join132(verDir, ORPHAN_MARKER);
121128
+ const verDir = join133(plDir, ver.name);
121129
+ const markerPath = join133(verDir, ORPHAN_MARKER);
120876
121130
  if (!existsSync33(markerPath))
120877
121131
  continue;
120878
121132
  const label2 = `${mp.name}/${pl.name}/${ver.name}`;
120879
121133
  if (opts.dryRun) {
120880
121134
  lines.push(` - would remove: ${label2}`);
120881
121135
  } else {
120882
- await rm30(verDir, { recursive: true, force: true });
121136
+ await rm31(verDir, { recursive: true, force: true });
120883
121137
  removed += 1;
120884
121138
  lines.push(` ✓ removed: ${label2}`);
120885
121139
  }
120886
121140
  }
120887
121141
  if (!opts.dryRun && await isEmptyDir(plDir)) {
120888
- await rm30(plDir, { recursive: true, force: true });
121142
+ await rm31(plDir, { recursive: true, force: true });
120889
121143
  }
120890
121144
  }
120891
121145
  if (!opts.dryRun && await isEmptyDir(mpDir)) {
120892
- await rm30(mpDir, { recursive: true, force: true });
121146
+ await rm31(mpDir, { recursive: true, force: true });
120893
121147
  }
120894
121148
  }
120895
121149
  if (scanned === 0) {
@@ -120904,11 +121158,11 @@ function resolveClaudePluginCacheRoot(opts) {
120904
121158
  if (explicitRoot)
120905
121159
  return explicitRoot;
120906
121160
  const home = opts.home ?? process.env[CLAUDE_PLUGIN_CACHE_HOME_ENV] ?? homedir();
120907
- return join132(home, ".claude", "plugins", "cache");
121161
+ return join133(home, ".claude", "plugins", "cache");
120908
121162
  }
120909
121163
  async function isEmptyDir(dir) {
120910
121164
  try {
120911
- const entries2 = await readdir31(dir);
121165
+ const entries2 = await readdir32(dir);
120912
121166
  return entries2.length === 0;
120913
121167
  } catch {
120914
121168
  return false;
@@ -120958,7 +121212,7 @@ init_repoSourceRegistry();
120958
121212
  init_writeLock();
120959
121213
  import { execFile as execFile19 } from "node:child_process";
120960
121214
  import { existsSync as existsSync34 } from "node:fs";
120961
- import { lstat as lstat19, mkdir as mkdir42, readlink as readlink3, realpath as realpath16, rm as rm31, symlink as symlink5 } from "node:fs/promises";
121215
+ import { lstat as lstat19, mkdir as mkdir42, readlink as readlink3, realpath as realpath16, rm as rm32, symlink as symlink5 } from "node:fs/promises";
120962
121216
  import { basename as basename12, dirname as dirname51, isAbsolute as isAbsolute23, relative as relative34, resolve as resolve43 } from "node:path";
120963
121217
  import { promisify as promisify16 } from "node:util";
120964
121218
  var execFileAsync5 = promisify16(execFile19);
@@ -121151,13 +121405,13 @@ async function cloneCheckout(input) {
121151
121405
  try {
121152
121406
  await clone(cloneArgs);
121153
121407
  } catch (first) {
121154
- await rm31(target, { recursive: true, force: true });
121408
+ await rm32(target, { recursive: true, force: true });
121155
121409
  try {
121156
121410
  if (first instanceof GitProgressError && first.kind !== "failed")
121157
121411
  throw first;
121158
121412
  await clone(["clone", "--no-checkout", "--depth=1", input.remote, target]);
121159
121413
  } catch (error) {
121160
- await rm31(target, { recursive: true, force: true });
121414
+ await rm32(target, { recursive: true, force: true });
121161
121415
  const detail = error instanceof Error ? error.message : String(error);
121162
121416
  throw new ContextError(ExitCode.ExternalToolError, `cannot clone registered repository: ${input.remote}`, {
121163
121417
  category: ErrorCategory.ExternalToolFailed,
@@ -121184,7 +121438,7 @@ async function cloneCheckout(input) {
121184
121438
  await verifyCheckout({ checkout: target, remote: input.remote, ref: input.ref, subpaths: input.subpaths });
121185
121439
  return target;
121186
121440
  } catch (error) {
121187
- await rm31(target, { recursive: true, force: true });
121441
+ await rm32(target, { recursive: true, force: true });
121188
121442
  throw error;
121189
121443
  }
121190
121444
  }
@@ -121200,7 +121454,7 @@ async function bindLocalAlias(input) {
121200
121454
  const actualReal = await realpath16(actual).catch(() => null);
121201
121455
  if (actualReal !== null && actualReal === await realpath16(input.checkout))
121202
121456
  return;
121203
- await rm31(alias);
121457
+ await rm32(alias);
121204
121458
  } else {
121205
121459
  const actual = await realpath16(alias);
121206
121460
  if (actual === await realpath16(input.checkout))
@@ -121309,7 +121563,7 @@ init_src2();
121309
121563
  init_documentCapture();
121310
121564
  import { existsSync as existsSync35 } from "node:fs";
121311
121565
  import { readFile as readFile108 } from "node:fs/promises";
121312
- import { join as join134 } from "node:path";
121566
+ import { join as join135 } from "node:path";
121313
121567
 
121314
121568
  // src/project/sourceCommandViews.ts
121315
121569
  init_fileSourceOrigins();
@@ -121317,7 +121571,7 @@ init_documentSiteDetection();
121317
121571
  init_workspace();
121318
121572
  init_documentBatchManifest();
121319
121573
  import { readFile as readFile107 } from "node:fs/promises";
121320
- import { join as join133 } from "node:path";
121574
+ import { join as join134 } from "node:path";
121321
121575
  function repoSourceAgentView(source2) {
121322
121576
  return {
121323
121577
  id: source2.id ?? source2.name,
@@ -121382,7 +121636,7 @@ async function fileSourceAgentViewWithNextAction(input) {
121382
121636
  };
121383
121637
  }
121384
121638
  function documentSourceManifestPath(source2) {
121385
- return source2.snapshot?.manifest ?? join133(source2.materializedAt, "manifest.json");
121639
+ return source2.snapshot?.manifest ?? join134(source2.materializedAt, "manifest.json");
121386
121640
  }
121387
121641
  async function fileSourceDocumentSiteHint(input) {
121388
121642
  const detection = await detectDocumentSiteFiles({
@@ -121392,7 +121646,7 @@ async function fileSourceDocumentSiteHint(input) {
121392
121646
  let snapshotConfigured = false;
121393
121647
  const manifest = documentSourceManifestPath(input.source);
121394
121648
  try {
121395
- const parsed = parseDocumentSnapshotForSource(JSON.parse(await readFile107(join133(input.projectRoot, manifest), "utf8")), input.source.name);
121649
+ const parsed = parseDocumentSnapshotForSource(JSON.parse(await readFile107(join134(input.projectRoot, manifest), "utf8")), input.source.name);
121396
121650
  snapshotConfigured = manifestUsesMdxJsonDocs(parsed);
121397
121651
  } catch {
121398
121652
  snapshotConfigured = false;
@@ -121425,11 +121679,11 @@ async function larkSourceAgentViewWithNextAction(input) {
121425
121679
  init_documentBatchManifest();
121426
121680
  init_documentSnapshotFidelity();
121427
121681
  function documentSourceManifestPath2(source2) {
121428
- return source2.snapshot?.manifest ?? join134(source2.materializedAt, "manifest.json");
121682
+ return source2.snapshot?.manifest ?? join135(source2.materializedAt, "manifest.json");
121429
121683
  }
121430
121684
  async function documentSnapshotState(input) {
121431
121685
  const manifest = documentSourceManifestPath2(input.source);
121432
- const manifestPath = join134(input.projectRoot, manifest);
121686
+ const manifestPath = join135(input.projectRoot, manifest);
121433
121687
  if (!existsSync35(manifestPath)) {
121434
121688
  return {
121435
121689
  snapshotReady: false,
@@ -121508,7 +121762,7 @@ async function documentSnapshotState(input) {
121508
121762
  const missing2 = [
121509
121763
  ...parsed.files.map((file) => file.path),
121510
121764
  ...(parsed.assets ?? []).filter((asset) => asset.content_hash !== undefined).map((asset) => asset.path)
121511
- ].find((path3) => !existsSync35(join134(input.projectRoot, input.source.materializedAt, path3)));
121765
+ ].find((path3) => !existsSync35(join135(input.projectRoot, input.source.materializedAt, path3)));
121512
121766
  if (missing2 !== undefined) {
121513
121767
  return {
121514
121768
  snapshotReady: false,
@@ -121610,7 +121864,7 @@ init_exitCode();
121610
121864
  var import_yaml59 = __toESM(require_dist(), 1);
121611
121865
  import { createHash as createHash42 } from "node:crypto";
121612
121866
  import { readFile as readFile109, realpath as realpath17 } from "node:fs/promises";
121613
- import { basename as basename13, extname as extname15, isAbsolute as isAbsolute24, join as join135, relative as relative35, resolve as resolve44 } from "node:path";
121867
+ import { basename as basename13, extname as extname15, isAbsolute as isAbsolute24, join as join136, relative as relative35, resolve as resolve44 } from "node:path";
121614
121868
  init_writeLock();
121615
121869
  var SOURCE_NAME_PATTERN3 = /^[a-z0-9][a-z0-9._-]*$/u;
121616
121870
  function isDateSourceNamespace(value) {
@@ -121706,7 +121960,7 @@ function assertSafeFileInclude(value) {
121706
121960
  }
121707
121961
  async function readRegistryDocument(projectRoot2, registryPath2) {
121708
121962
  try {
121709
- const content3 = await readFile109(join135(projectRoot2, registryPath2), "utf8");
121963
+ const content3 = await readFile109(join136(projectRoot2, registryPath2), "utf8");
121710
121964
  return content3.trim().length === 0 ? { sources: [] } : import_yaml59.default.parse(content3);
121711
121965
  } catch (error) {
121712
121966
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
@@ -121796,7 +122050,7 @@ function flatRawSource(sources, name3) {
121796
122050
  }
121797
122051
  async function ensureOriginInstallRootIgnored(projectRoot2, kind) {
121798
122052
  const line = `${fileSourceOriginInstallRoot(kind)}/`;
121799
- const path3 = join135(projectRoot2, ".gitignore");
122053
+ const path3 = join136(projectRoot2, ".gitignore");
121800
122054
  let current3 = "";
121801
122055
  try {
121802
122056
  current3 = await readFile109(path3, "utf8");
@@ -121897,7 +122151,7 @@ async function addFileSourceUnlocked(input) {
121897
122151
  sourceName: input.name
121898
122152
  });
121899
122153
  }
121900
- await atomicWriteFile(join135(input.projectRoot, DEFAULT_FILE_SOURCES_REGISTRY_PATH), import_yaml59.default.stringify({ sources: nextSources }));
122154
+ await atomicWriteFile(join136(input.projectRoot, DEFAULT_FILE_SOURCES_REGISTRY_PATH), import_yaml59.default.stringify({ sources: nextSources }));
121901
122155
  const gitignoreUpdated = origin !== undefined && await ensureOriginInstallRootIgnored(input.projectRoot, origin.kind);
121902
122156
  const updated = await loadSourcesRegistry({ rootDir: input.projectRoot });
121903
122157
  const entry = updated.files.find((source2) => source2.name === input.name || source2.id === input.name);
@@ -121958,7 +122212,7 @@ async function addLarkSourceUnlocked(input) {
121958
122212
  const record6 = entry2;
121959
122213
  return record6.name !== input.name && record6.id !== input.name;
121960
122214
  }), nextEntry];
121961
- await atomicWriteFile(join135(input.projectRoot, DEFAULT_LARK_SOURCES_REGISTRY_PATH), import_yaml59.default.stringify({ sources: nextSources }));
122215
+ await atomicWriteFile(join136(input.projectRoot, DEFAULT_LARK_SOURCES_REGISTRY_PATH), import_yaml59.default.stringify({ sources: nextSources }));
121962
122216
  const updated = await loadSourcesRegistry({ rootDir: input.projectRoot });
121963
122217
  const entry = updated.larks.find((source2) => source2.name === input.name || source2.id === input.name);
121964
122218
  if (entry === undefined) {
@@ -121991,14 +122245,14 @@ init_errors3();
121991
122245
  init_exitCode();
121992
122246
  var import_yaml60 = __toESM(require_dist(), 1);
121993
122247
  import { readFile as readFile110 } from "node:fs/promises";
121994
- import { join as join136 } from "node:path";
121995
- import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
122248
+ import { join as join137 } from "node:path";
122249
+ import { isDeepStrictEqual as isDeepStrictEqual4 } from "node:util";
121996
122250
  function identityKeys(entry) {
121997
122251
  return new Set([entry.name, entry.id]);
121998
122252
  }
121999
122253
  async function createLarkBatchRegistration(projectRoot2, namespace) {
122000
122254
  const registry2 = await loadSourcesRegistry({ rootDir: projectRoot2 });
122001
- const registryPath2 = join136(projectRoot2, DEFAULT_LARK_SOURCES_REGISTRY_PATH);
122255
+ const registryPath2 = join137(projectRoot2, DEFAULT_LARK_SOURCES_REGISTRY_PATH);
122002
122256
  let committedSources;
122003
122257
  try {
122004
122258
  const text12 = await readFile110(registryPath2, "utf8");
@@ -122102,7 +122356,7 @@ async function createLarkBatchRegistration(projectRoot2, namespace) {
122102
122356
  modules: [...modules.values()]
122103
122357
  };
122104
122358
  const nextSources = batchIndex < 0 ? [...committedSources, batch] : committedSources.map((source2, index3) => index3 === batchIndex ? batch : source2);
122105
- if (!isDeepStrictEqual3(nextSources, committedSources)) {
122359
+ if (!isDeepStrictEqual4(nextSources, committedSources)) {
122106
122360
  await atomicWriteFile(registryPath2, import_yaml60.default.stringify({ sources: nextSources }));
122107
122361
  committedSources = nextSources;
122108
122362
  if (batchIndex < 0)
@@ -122120,7 +122374,7 @@ init_errors3();
122120
122374
  init_exitCode();
122121
122375
  import { createHash as createHash43 } from "node:crypto";
122122
122376
  import { lstat as lstat20, readFile as readFile111 } from "node:fs/promises";
122123
- import { join as join137, resolve as resolve45 } from "node:path";
122377
+ import { join as join138, resolve as resolve45 } from "node:path";
122124
122378
  var INPUT_SCHEMA = "context.source-batch.input.v1";
122125
122379
  var STATE_SCHEMA = "context.source-batch.state.v1";
122126
122380
  var RUNTIME_PARTS = [".tmp", "context-runtime", "source-batches"];
@@ -122171,14 +122425,14 @@ function paths(projectRoot2, jobId) {
122171
122425
  throw journalError("source-batch-id-invalid", "Source batch checkpoint ID must contain exactly 32 lowercase hexadecimal characters.");
122172
122426
  }
122173
122427
  const directory = resolve45(projectRoot2, ...RUNTIME_PARTS, jobId);
122174
- return { inputPath: join137(directory, "input.json"), statePath: join137(directory, "state.json") };
122428
+ return { inputPath: join138(directory, "input.json"), statePath: join138(directory, "state.json") };
122175
122429
  }
122176
122430
  async function assertJournalPath(projectRoot2, jobId, filename) {
122177
122431
  paths(projectRoot2, jobId);
122178
122432
  let current3 = resolve45(projectRoot2);
122179
122433
  const parts = [...RUNTIME_PARTS, jobId, filename];
122180
122434
  for (const [index3, part] of parts.entries()) {
122181
- current3 = join137(current3, part);
122435
+ current3 = join138(current3, part);
122182
122436
  let stat11;
122183
122437
  try {
122184
122438
  stat11 = await lstat20(current3);
@@ -122910,13 +123164,13 @@ init_exitCode();
122910
123164
 
122911
123165
  // src/project/wikiDiscovery.ts
122912
123166
  import { mkdir as mkdir44 } from "node:fs/promises";
122913
- import { join as join139, relative as relative37 } from "node:path";
123167
+ import { join as join140, relative as relative37 } from "node:path";
122914
123168
 
122915
123169
  // src/project/wikiDiscoveryStore.ts
122916
123170
  init_atomicWrite();
122917
123171
  import { createHash as createHash44, randomUUID as randomUUID9 } from "node:crypto";
122918
- import { link as link2, lstat as lstat21, mkdir as mkdir43, readFile as readFile112, readdir as readdir32, rm as rm32, writeFile as writeFile33 } from "node:fs/promises";
122919
- import { join as join138, relative as relative36, resolve as resolve46, sep as sep11 } from "node:path";
123172
+ import { link as link2, lstat as lstat21, mkdir as mkdir43, readFile as readFile112, readdir as readdir33, rm as rm33, writeFile as writeFile33 } from "node:fs/promises";
123173
+ import { join as join139, relative as relative36, resolve as resolve46, sep as sep11 } from "node:path";
122920
123174
  function wikiDiscoveryDigest(value) {
122921
123175
  return createHash44("sha256").update(value).digest("hex");
122922
123176
  }
@@ -122930,7 +123184,7 @@ async function assertWikiDiscoveryPath(root2, path3) {
122930
123184
  throw new WikiDiscoveryError("unsafe-checkpoint-path", false, "Discovery checkpoint must stay inside its workspace");
122931
123185
  let current3 = base;
122932
123186
  for (const part of parts) {
122933
- current3 = join138(current3, part);
123187
+ current3 = join139(current3, part);
122934
123188
  try {
122935
123189
  if ((await lstat21(current3)).isSymbolicLink()) {
122936
123190
  throw new WikiDiscoveryError("unsafe-checkpoint-path", false, "Discovery checkpoint paths must not contain symbolic links");
@@ -122959,12 +123213,12 @@ async function saveWikiDiscoveryJson(path3, value) {
122959
123213
  }
122960
123214
  async function loadWikiDiscoveryReceipts(directory) {
122961
123215
  const result = new Map;
122962
- await assertWikiDiscoveryPath(directory, join138(directory, "pages"));
122963
- await mkdir43(join138(directory, "pages"), { recursive: true });
122964
- for (const file of await readdir32(join138(directory, "pages"))) {
123216
+ await assertWikiDiscoveryPath(directory, join139(directory, "pages"));
123217
+ await mkdir43(join139(directory, "pages"), { recursive: true });
123218
+ for (const file of await readdir33(join139(directory, "pages"))) {
122965
123219
  if (!/^[a-f0-9]{64}\.json$/u.test(file))
122966
123220
  continue;
122967
- const value = await readWikiDiscoveryJson(join138(directory, "pages", file));
123221
+ const value = await readWikiDiscoveryJson(join139(directory, "pages", file));
122968
123222
  if (!value || typeof value.parent_node_token !== "string" || value.page_token !== undefined && typeof value.page_token !== "string" || !["completed", "failed"].includes(value.status) || value.status === "completed" && (!value.page || !Array.isArray(value.page.nodes) || value.page.next_page_token !== undefined && typeof value.page.next_page_token !== "string") || value.status === "failed" && (!value.failure || typeof value.failure.retryable !== "boolean" || typeof value.failure.reason !== "string" || typeof value.failure.message !== "string") || `${wikiDiscoveryPageKey(value)}.json` !== file) {
122969
123223
  throw new WikiDiscoveryError("checkpoint-invalid", false, "Discovery page checkpoint is invalid; preserve it for inspection");
122970
123224
  }
@@ -122983,14 +123237,14 @@ function ownerRunning(pid) {
122983
123237
  }
122984
123238
  }
122985
123239
  async function acquireWikiDiscoveryLease(directory) {
122986
- const leases = join138(directory, "leases");
123240
+ const leases = join139(directory, "leases");
122987
123241
  await assertWikiDiscoveryPath(directory, leases);
122988
123242
  await mkdir43(leases, { recursive: true });
122989
123243
  for (let attempt = 0;attempt < 8; attempt++) {
122990
- const files = (await readdir32(leases)).filter((file) => /^\d{12}\.json$/u.test(file)).sort();
123244
+ const files = (await readdir33(leases)).filter((file) => /^\d{12}\.json$/u.test(file)).sort();
122991
123245
  const latest = files.at(-1);
122992
123246
  if (latest) {
122993
- const current3 = await readWikiDiscoveryJson(join138(leases, latest));
123247
+ const current3 = await readWikiDiscoveryJson(join139(leases, latest));
122994
123248
  if (!current3 || !Number.isSafeInteger(current3.pid) || current3.pid <= 0 || typeof current3.token !== "string" || typeof current3.released !== "boolean") {
122995
123249
  throw new WikiDiscoveryError("checkpoint-invalid", false, "Discovery lease is invalid; preserve it for inspection");
122996
123250
  }
@@ -122999,9 +123253,9 @@ async function acquireWikiDiscoveryLease(directory) {
122999
123253
  }
123000
123254
  }
123001
123255
  const sequence = latest ? Number(latest.slice(0, 12)) + 1 : 1;
123002
- const path3 = join138(leases, `${String(sequence).padStart(12, "0")}.json`);
123256
+ const path3 = join139(leases, `${String(sequence).padStart(12, "0")}.json`);
123003
123257
  const owner = { pid: process.pid, token: randomUUID9(), released: false };
123004
- const temporary = join138(leases, `.lease-${owner.token}`);
123258
+ const temporary = join139(leases, `.lease-${owner.token}`);
123005
123259
  await writeFile33(temporary, JSON.stringify(owner), { flag: "wx", mode: 384 });
123006
123260
  try {
123007
123261
  await link2(temporary, path3);
@@ -123010,7 +123264,7 @@ async function acquireWikiDiscoveryLease(directory) {
123010
123264
  continue;
123011
123265
  throw error;
123012
123266
  } finally {
123013
- await rm32(temporary, { force: true });
123267
+ await rm33(temporary, { force: true });
123014
123268
  }
123015
123269
  return async () => {
123016
123270
  await saveWikiDiscoveryJson(path3, { ...owner, released: true });
@@ -123126,7 +123380,7 @@ async function discoverLarkWiki(input) {
123126
123380
  throw new WikiDiscoveryError("invalid-concurrency", false, "Wiki concurrency must be an integer from 1 to 4");
123127
123381
  }
123128
123382
  const jobId = wikiDiscoveryDigest(url);
123129
- const directory = join139(input.projectRoot, ".tmp", "context-runtime", "wiki-discovery", jobId);
123383
+ const directory = join140(input.projectRoot, ".tmp", "context-runtime", "wiki-discovery", jobId);
123130
123384
  await assertWikiDiscoveryPath(input.projectRoot, directory);
123131
123385
  await mkdir44(directory, { recursive: true });
123132
123386
  const release = await acquireWikiDiscoveryLease(directory);
@@ -123138,7 +123392,7 @@ async function discoverLarkWiki(input) {
123138
123392
  }
123139
123393
  async function runDiscovery(input, job) {
123140
123394
  const { directory, url, identity: identity2 } = job;
123141
- const metadataPath = join139(directory, "job.json");
123395
+ const metadataPath = join140(directory, "job.json");
123142
123396
  let metadata = await readWikiDiscoveryJson(metadataPath);
123143
123397
  if (metadata && (metadata.protocol !== "context.wiki-discovery.v1" || metadata.url !== url || metadata.identity !== identity2)) {
123144
123398
  throw new WikiDiscoveryError("job-identity-mismatch", false, "Resume must preserve the discovery's original URL and identity");
@@ -123187,7 +123441,7 @@ async function runDiscovery(input, job) {
123187
123441
  }
123188
123442
  const key = wikiDiscoveryPageKey(cursor);
123189
123443
  try {
123190
- await saveWikiDiscoveryJson(join139(directory, "pages", `${key}.json`), receipt2);
123444
+ await saveWikiDiscoveryJson(join140(directory, "pages", `${key}.json`), receipt2);
123191
123445
  receipts.set(key, receipt2);
123192
123446
  } catch {
123193
123447
  checkpointError = "A discovery page could not be checkpointed; saved pages remain reusable and unsaved pages must be requested again";
@@ -123205,7 +123459,7 @@ async function finishDiscovery(input, state) {
123205
123459
  const { directory, url, identity: identity2, jobId, metadata, view } = state;
123206
123460
  let checkpointError = state.checkpointError;
123207
123461
  let status = input.signal?.aborted ? "paused" : checkpointError || view.pending.length || view.failed.length || !metadata.root ? "partial" : "completed";
123208
- const manifestPath = join139(directory, "manifest.json");
123462
+ const manifestPath = join140(directory, "manifest.json");
123209
123463
  try {
123210
123464
  await saveWikiDiscoveryJson(manifestPath, {
123211
123465
  protocol: "context.wiki-discovery.manifest.v1",
@@ -123385,8 +123639,8 @@ init_writeLock();
123385
123639
  var import_yaml63 = __toESM(require_dist(), 1);
123386
123640
  import { existsSync as existsSync36 } from "node:fs";
123387
123641
  import { createHash as createHash45 } from "node:crypto";
123388
- import { readFile as readFile113, readdir as readdir33, rm as rm33 } from "node:fs/promises";
123389
- import { isAbsolute as isAbsolute25, join as join140, relative as relative38, resolve as resolve47, sep as sep12 } from "node:path";
123642
+ import { readFile as readFile113, readdir as readdir34, rm as rm34 } from "node:fs/promises";
123643
+ import { isAbsolute as isAbsolute25, join as join141, relative as relative38, resolve as resolve47, sep as sep12 } from "node:path";
123390
123644
  function sourceIdentity(source2) {
123391
123645
  if (source2.kind === "source.collection")
123392
123646
  return;
@@ -123418,7 +123672,7 @@ function collectStrings(value, output) {
123418
123672
  }
123419
123673
  }
123420
123674
  async function yamlReferences(input) {
123421
- const absolutePath = join140(input.projectRoot, input.path);
123675
+ const absolutePath = join141(input.projectRoot, input.path);
123422
123676
  if (!existsSync36(absolutePath))
123423
123677
  return false;
123424
123678
  const parsed = import_yaml63.default.parse(await readFile113(absolutePath, "utf8"));
@@ -123567,7 +123821,7 @@ async function registryRemovalWrite(projectRoot2, source2) {
123567
123821
  const path3 = registryPath2(source2.type);
123568
123822
  if (path3 === null)
123569
123823
  return;
123570
- const absolutePath = join140(projectRoot2, path3);
123824
+ const absolutePath = join141(projectRoot2, path3);
123571
123825
  const document4 = existsSync36(absolutePath) ? import_yaml63.default.parse(await readFile113(absolutePath, "utf8")) : { sources: [] };
123572
123826
  return {
123573
123827
  path: absolutePath,
@@ -123586,7 +123840,7 @@ function safeManagedMaterializedPath(projectRoot2, source2) {
123586
123840
  return absolute;
123587
123841
  }
123588
123842
  function safeManagedManifestPath(projectRoot2, source2) {
123589
- const manifest = source2.manifest ?? join140(source2.materializedAt, "manifest.json");
123843
+ const manifest = source2.manifest ?? join141(source2.materializedAt, "manifest.json");
123590
123844
  if (isAbsolute25(manifest))
123591
123845
  throw unsafeOwnership(source2, manifest);
123592
123846
  const absolute = resolve47(projectRoot2, manifest);
@@ -123748,7 +124002,7 @@ function publicRemovalResult(plan, action) {
123748
124002
  };
123749
124003
  }
123750
124004
  async function pruneExtractRuntime(projectRoot2, source2) {
123751
- const fingerprintPath = join140(projectRoot2, ".tmp/context-runtime/extract/source-fingerprints.json");
124005
+ const fingerprintPath = join141(projectRoot2, ".tmp/context-runtime/extract/source-fingerprints.json");
123752
124006
  const removedPhaseIds = new Set;
123753
124007
  if (existsSync36(fingerprintPath)) {
123754
124008
  const parsed = JSON.parse(await readFile113(fingerprintPath, "utf8"));
@@ -123765,14 +124019,14 @@ async function pruneExtractRuntime(projectRoot2, source2) {
123765
124019
  await atomicWriteFile(fingerprintPath, `${JSON.stringify({ ...parsed, phases: next2 }, null, 2)}
123766
124020
  `);
123767
124021
  }
123768
- const phaseOwnershipPath = join140(projectRoot2, ".tmp/context-runtime/extract/custom-phase-candidates.json");
124022
+ const phaseOwnershipPath = join141(projectRoot2, ".tmp/context-runtime/extract/custom-phase-candidates.json");
123769
124023
  if (existsSync36(phaseOwnershipPath) && removedPhaseIds.size > 0) {
123770
124024
  const parsed = JSON.parse(await readFile113(phaseOwnershipPath, "utf8"));
123771
124025
  const phases = Object.fromEntries(Object.entries(parsed.phases ?? {}).filter(([phaseId]) => !removedPhaseIds.has(phaseId)));
123772
124026
  await atomicWriteFile(phaseOwnershipPath, `${JSON.stringify({ ...parsed, phases }, null, 2)}
123773
124027
  `);
123774
124028
  }
123775
- const symbolPath = join140(projectRoot2, ".tmp/context-runtime/extract/source-symbols.json");
124029
+ const symbolPath = join141(projectRoot2, ".tmp/context-runtime/extract/source-symbols.json");
123776
124030
  if (existsSync36(symbolPath)) {
123777
124031
  const parsed = JSON.parse(await readFile113(symbolPath, "utf8"));
123778
124032
  const symbols = Array.isArray(parsed.symbols) ? parsed.symbols.filter((entry) => entry === null || typeof entry !== "object" || Array.isArray(entry) || entry.source !== source2.name) : [];
@@ -123780,12 +124034,12 @@ async function pruneExtractRuntime(projectRoot2, source2) {
123780
124034
  await atomicWriteFile(symbolPath, `${JSON.stringify({ ...parsed, phaseFingerprints, symbols }, null, 2)}
123781
124035
  `);
123782
124036
  }
123783
- const snapshotRoot = join140(projectRoot2, ".tmp/context-runtime/extract/candidates");
124037
+ const snapshotRoot = join141(projectRoot2, ".tmp/context-runtime/extract/candidates");
123784
124038
  const visit4 = async (directory) => {
123785
124039
  if (!existsSync36(directory))
123786
124040
  return;
123787
- for (const entry of await readdir33(directory, { withFileTypes: true })) {
123788
- const path3 = join140(directory, entry.name);
124041
+ for (const entry of await readdir34(directory, { withFileTypes: true })) {
124042
+ const path3 = join141(directory, entry.name);
123789
124043
  if (entry.isDirectory()) {
123790
124044
  await visit4(path3);
123791
124045
  continue;
@@ -123796,7 +124050,7 @@ async function pruneExtractRuntime(projectRoot2, source2) {
123796
124050
  const parsed = JSON.parse(await readFile113(path3, "utf8"));
123797
124051
  const refs = Array.isArray(parsed.source_refs) ? parsed.source_refs : [];
123798
124052
  if (parsed.source === source2.name || refs.some((ref2) => typeof ref2 === "string" && stringReferencesSource(ref2, source2))) {
123799
- await rm33(path3, { force: true });
124053
+ await rm34(path3, { force: true });
123800
124054
  }
123801
124055
  } catch {}
123802
124056
  }
@@ -123835,7 +124089,7 @@ async function removeProjectSource(input) {
123835
124089
  });
123836
124090
  }
123837
124091
  await applyAtomicFileBatch({
123838
- transactionRoot: join140(input.projectRoot, ".tmp", "context-runtime", "source-remove-transactions"),
124092
+ transactionRoot: join141(input.projectRoot, ".tmp", "context-runtime", "source-remove-transactions"),
123839
124093
  writes: [...plan.registryWrite === undefined ? [] : [plan.registryWrite], ...plan.manifestWrite !== undefined ? [plan.manifestWrite] : []],
123840
124094
  removals: plan.absoluteRemovals
123841
124095
  });
@@ -124036,7 +124290,7 @@ init_sourceInputMutation();
124036
124290
  init_writeLock();
124037
124291
  import { execFile as execFile20 } from "node:child_process";
124038
124292
  import { promisify as promisify17 } from "node:util";
124039
- import { join as join141 } from "node:path";
124293
+ import { join as join142 } from "node:path";
124040
124294
  var exec6 = promisify17(execFile20);
124041
124295
  var requestSchema3 = exports_external.object({ type: exports_external.enum(["file", "lark"]), name: exports_external.string().min(1), commit: exports_external.string().min(1).optional() }).strict();
124042
124296
  async function restoreDocumentSnapshot(projectRoot2, value) {
@@ -124128,8 +124382,8 @@ async function restoreDocumentSnapshot(projectRoot2, value) {
124128
124382
  const removals = [...previous3?.files ?? [], ...previous3?.assets ?? []].map((file) => `${source2.materializedAt}/${file.path}`).filter((path3) => !selected.files.has(path3) && !renderDocumentManifestFile(next2).includes(path3.slice(source2.materializedAt.length + 1)));
124129
124383
  const removalTargets = await Promise.all(removals.map((path3) => safeProjectTarget(projectRoot2, path3)));
124130
124384
  await applyAtomicFileBatch({
124131
- transactionRoot: join141(projectRoot2, ".tmp/context-runtime/capture-transactions"),
124132
- writes: [...selected.files].map(([path3, bytes]) => ({ path: join141(projectRoot2, path3), bytes })).concat([
124385
+ transactionRoot: join142(projectRoot2, ".tmp/context-runtime/capture-transactions"),
124386
+ writes: [...selected.files].map(([path3, bytes]) => ({ path: join142(projectRoot2, path3), bytes })).concat([
124133
124387
  { path: manifestTarget, bytes: Buffer.from(renderDocumentManifestFile(next2)) }
124134
124388
  ]),
124135
124389
  removals: removalTargets
@@ -124663,8 +124917,8 @@ init_cliFeedback();
124663
124917
  init_exitCode();
124664
124918
  var import_yaml66 = __toESM(require_dist(), 1);
124665
124919
  import { constants as constants6, existsSync as existsSync37 } from "node:fs";
124666
- import { lstat as lstat22, open as open5, readdir as readdir34 } from "node:fs/promises";
124667
- import { dirname as dirname52, join as join143, resolve as resolve50 } from "node:path";
124920
+ import { lstat as lstat22, open as open5, readdir as readdir35 } from "node:fs/promises";
124921
+ import { dirname as dirname52, join as join144, resolve as resolve50 } from "node:path";
124668
124922
  import { fileURLToPath as fileURLToPath10 } from "node:url";
124669
124923
  function bundledSkillRoot() {
124670
124924
  const directory = dirname52(fileURLToPath10(import.meta.url));
@@ -124691,10 +124945,10 @@ async function listProductionSkills(root2) {
124691
124945
  }
124692
124946
  }
124693
124947
  async function readProductionSkills(root2) {
124694
- const entries2 = (await readdir34(root2, { withFileTypes: true })).filter((entry) => entry.isDirectory()).sort((a2, b) => a2.name < b.name ? -1 : a2.name > b.name ? 1 : 0);
124948
+ const entries2 = (await readdir35(root2, { withFileTypes: true })).filter((entry) => entry.isDirectory()).sort((a2, b) => a2.name < b.name ? -1 : a2.name > b.name ? 1 : 0);
124695
124949
  const skills = [];
124696
124950
  for (const directory of entries2) {
124697
- const entry = join143(root2, directory.name, "SKILL.md");
124951
+ const entry = join144(root2, directory.name, "SKILL.md");
124698
124952
  if (!(await lstat22(entry)).isFile())
124699
124953
  throw new TypeError(`Skill entry must be a regular file: ${entry}`);
124700
124954
  const handle3 = await open5(entry, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
@@ -125108,8 +125362,8 @@ init_cliFeedback();
125108
125362
  init_errors3();
125109
125363
  init_exitCode();
125110
125364
  import { createHash as createHash46 } from "node:crypto";
125111
- import { cp as cp3, lstat as lstat23, mkdir as mkdir45, mkdtemp as mkdtemp7, readFile as readFile119, readdir as readdir35, rename as rename12, rm as rm34, writeFile as writeFile34 } from "node:fs/promises";
125112
- import { dirname as dirname54, join as join144, resolve as resolve52 } from "node:path";
125365
+ import { cp as cp3, lstat as lstat23, mkdir as mkdir45, mkdtemp as mkdtemp7, readFile as readFile119, readdir as readdir36, rename as rename12, rm as rm35, writeFile as writeFile34 } from "node:fs/promises";
125366
+ import { dirname as dirname54, join as join145, resolve as resolve52 } from "node:path";
125113
125367
  var MARKER = ".context-skill-install.json";
125114
125368
  function conflict(path3) {
125115
125369
  throw new ContextError(ExitCode.UserError, `Local skill install conflict: ${path3}`, {
@@ -125137,10 +125391,10 @@ async function checkParents(path3) {
125137
125391
  async function digest9(root2) {
125138
125392
  const hash5 = createHash46("sha256");
125139
125393
  async function visit4(dir, prefix) {
125140
- for (const name3 of (await readdir35(dir)).sort()) {
125394
+ for (const name3 of (await readdir36(dir)).sort()) {
125141
125395
  if (!prefix && name3 === MARKER)
125142
125396
  continue;
125143
- const path3 = join144(dir, name3);
125397
+ const path3 = join145(dir, name3);
125144
125398
  const entry = await lstat23(path3);
125145
125399
  if (entry.isSymbolicLink())
125146
125400
  conflict(path3);
@@ -125159,7 +125413,7 @@ async function digest9(root2) {
125159
125413
  async function assertOwnedDirectory(target, existing) {
125160
125414
  if (!existing.isDirectory() || existing.isSymbolicLink())
125161
125415
  conflict(target);
125162
- const markerPath = join144(target, MARKER);
125416
+ const markerPath = join145(target, MARKER);
125163
125417
  if (!(await stat11(markerPath))?.isFile())
125164
125418
  conflict(target);
125165
125419
  let marker;
@@ -125175,24 +125429,24 @@ async function installLocalSkills(root2, path3, dryRun, agent) {
125175
125429
  if (!path3.trim())
125176
125430
  conflict("--local requires a non-empty path");
125177
125431
  const targetRoot = resolve52(path3);
125178
- const skillsRoot = join144(targetRoot, "skills");
125432
+ const skillsRoot = join145(targetRoot, "skills");
125179
125433
  await checkParents(skillsRoot);
125180
- const sourceRoot = join144(root2, "skills");
125434
+ const sourceRoot = join145(root2, "skills");
125181
125435
  const commandPlans = [];
125182
125436
  const commandEntries = new Set;
125183
125437
  if (agent === "claude" || agent === "cursor") {
125184
- for (const name3 of await readdir35(join144(root2, "claude", "commands"))) {
125438
+ for (const name3 of await readdir36(join145(root2, "claude", "commands"))) {
125185
125439
  if (name3.endsWith(".md"))
125186
125440
  commandEntries.add(name3.slice(0, -3));
125187
125441
  }
125188
- const commandsRoot = join144(targetRoot, "commands");
125442
+ const commandsRoot = join145(targetRoot, "commands");
125189
125443
  await checkParents(commandsRoot);
125190
- for (const entry of await readdir35(join144(root2, agent, "commands"), { withFileTypes: true })) {
125444
+ for (const entry of await readdir36(join145(root2, agent, "commands"), { withFileTypes: true })) {
125191
125445
  if (!entry.isFile() || !entry.name.endsWith(".md"))
125192
125446
  continue;
125193
- const content3 = await readFile119(join144(root2, agent, "commands", entry.name), "utf8");
125194
- const target = join144(commandsRoot, entry.name);
125195
- const marker = join144(commandsRoot, `.context-${entry.name}.json`);
125447
+ const content3 = await readFile119(join145(root2, agent, "commands", entry.name), "utf8");
125448
+ const target = join145(commandsRoot, entry.name);
125449
+ const marker = join145(commandsRoot, `.context-${entry.name}.json`);
125196
125450
  for (const file of [target, marker]) {
125197
125451
  const existing = await stat11(file);
125198
125452
  if (existing && (!existing.isFile() || existing.isSymbolicLink()))
@@ -125213,14 +125467,14 @@ async function installLocalSkills(root2, path3, dryRun, agent) {
125213
125467
  commandPlans.push({ name: entry.name, target, marker, content: content3, hash: createHash46("sha256").update(content3).digest("hex") });
125214
125468
  }
125215
125469
  if (!commandPlans.length)
125216
- conflict(join144(root2, agent, "commands"));
125470
+ conflict(join145(root2, agent, "commands"));
125217
125471
  }
125218
125472
  const plans = [];
125219
- for (const entry of (await readdir35(sourceRoot, { withFileTypes: true })).sort((a2, b) => a2.name.localeCompare(b.name))) {
125220
- if (!entry.isDirectory() || !await stat11(join144(sourceRoot, entry.name, "SKILL.md")))
125473
+ for (const entry of (await readdir36(sourceRoot, { withFileTypes: true })).sort((a2, b) => a2.name.localeCompare(b.name))) {
125474
+ if (!entry.isDirectory() || !await stat11(join145(sourceRoot, entry.name, "SKILL.md")))
125221
125475
  continue;
125222
- const source2 = join144(sourceRoot, entry.name);
125223
- const target = join144(skillsRoot, entry.name);
125476
+ const source2 = join145(sourceRoot, entry.name);
125477
+ const target = join145(skillsRoot, entry.name);
125224
125478
  if (commandEntries.has(entry.name) && !["context-plan", "context-repo-content"].includes(entry.name)) {
125225
125479
  if (await stat11(target))
125226
125480
  conflict(`${target} (use a fresh host directory to avoid duplicate command/skill entries)`);
@@ -125234,16 +125488,16 @@ async function installLocalSkills(root2, path3, dryRun, agent) {
125234
125488
  if (!plans.length)
125235
125489
  conflict(sourceRoot);
125236
125490
  const resourcePlans = [];
125237
- const resourcesRoot = join144(targetRoot, "resources");
125491
+ const resourcesRoot = join145(targetRoot, "resources");
125238
125492
  if (agent === "claude" || agent === "cursor") {
125239
- const resourceSource = join144(root2, agent, "resources");
125493
+ const resourceSource = join145(root2, agent, "resources");
125240
125494
  if (await stat11(resourceSource)) {
125241
125495
  await checkParents(resourcesRoot);
125242
- for (const entry of (await readdir35(resourceSource, { withFileTypes: true })).sort((a2, b) => a2.name.localeCompare(b.name))) {
125496
+ for (const entry of (await readdir36(resourceSource, { withFileTypes: true })).sort((a2, b) => a2.name.localeCompare(b.name))) {
125243
125497
  if (!entry.isDirectory())
125244
125498
  continue;
125245
- const source2 = join144(resourceSource, entry.name);
125246
- const target = join144(resourcesRoot, entry.name);
125499
+ const source2 = join145(resourceSource, entry.name);
125500
+ const target = join145(resourcesRoot, entry.name);
125247
125501
  const existing = await stat11(target);
125248
125502
  if (existing)
125249
125503
  await assertOwnedDirectory(target, existing);
@@ -125257,14 +125511,14 @@ async function installLocalSkills(root2, path3, dryRun, agent) {
125257
125511
  await mkdir45(resourcesRoot, { recursive: true });
125258
125512
  for (const plan of [...plans, ...resourcePlans]) {
125259
125513
  const resource = resourcePlans.includes(plan);
125260
- const staging = await mkdtemp7(join144(dirname54(plan.target), ".context-install-"));
125261
- const candidate = join144(staging, "candidate");
125262
- const previous3 = join144(staging, "previous");
125514
+ const staging = await mkdtemp7(join145(dirname54(plan.target), ".context-install-"));
125515
+ const candidate = join145(staging, "candidate");
125516
+ const previous3 = join145(staging, "previous");
125263
125517
  let moved = false;
125264
125518
  try {
125265
125519
  await cp3(plan.source, candidate, { recursive: true });
125266
125520
  if (!resource && (agent === "claude" || agent === "cursor" && ["context-plan", "context-repo-content"].includes(plan.name))) {
125267
- const skillFile = join144(candidate, "SKILL.md");
125521
+ const skillFile = join145(candidate, "SKILL.md");
125268
125522
  const content3 = await readFile119(skillFile, "utf8");
125269
125523
  const parts = /^(---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/.exec(content3);
125270
125524
  if (parts && (["context-plan", "context-repo-content"].includes(plan.name) || /^\s*context-public-entry:\s*["']?false["']?\s*$/mu.test(parts[2]))) {
@@ -125273,7 +125527,7 @@ async function installLocalSkills(root2, path3, dryRun, agent) {
125273
125527
  ${frontmatter2}${parts[3]}${content3.slice(parts[0].length)}`);
125274
125528
  }
125275
125529
  }
125276
- await writeFile34(join144(candidate, MARKER), JSON.stringify({ owner: "context-plugin-local", digest: await digest9(candidate) }) + `
125530
+ await writeFile34(join145(candidate, MARKER), JSON.stringify({ owner: "context-plugin-local", digest: await digest9(candidate) }) + `
125277
125531
  `);
125278
125532
  if (plan.exists) {
125279
125533
  await rename12(plan.target, previous3);
@@ -125286,7 +125540,7 @@ ${frontmatter2}${parts[3]}${content3.slice(parts[0].length)}`);
125286
125540
  await rename12(previous3, plan.target);
125287
125541
  throw error;
125288
125542
  }
125289
- await rm34(staging, { recursive: true, force: true });
125543
+ await rm35(staging, { recursive: true, force: true });
125290
125544
  } catch (error) {
125291
125545
  throw new ContextError(ExitCode.WorkspaceStateError, `Local skill installation failed: ${plan.target}`, {
125292
125546
  category: ErrorCategory.WorkspaceStateInvalid,
@@ -125297,13 +125551,13 @@ ${frontmatter2}${parts[3]}${content3.slice(parts[0].length)}`);
125297
125551
  }
125298
125552
  for (const command3 of commandPlans) {
125299
125553
  await mkdir45(dirname54(command3.target), { recursive: true });
125300
- const staging = await mkdtemp7(join144(dirname54(command3.target), ".context-install-"));
125301
- await writeFile34(join144(staging, "command"), command3.content);
125302
- await writeFile34(join144(staging, "marker"), JSON.stringify({ owner: "context-plugin-local", digest: command3.hash }) + `
125554
+ const staging = await mkdtemp7(join145(dirname54(command3.target), ".context-install-"));
125555
+ await writeFile34(join145(staging, "command"), command3.content);
125556
+ await writeFile34(join145(staging, "marker"), JSON.stringify({ owner: "context-plugin-local", digest: command3.hash }) + `
125303
125557
  `);
125304
- await rename12(join144(staging, "command"), command3.target);
125305
- await rename12(join144(staging, "marker"), command3.marker);
125306
- await rm34(staging, { recursive: true, force: true });
125558
+ await rename12(join145(staging, "command"), command3.target);
125559
+ await rename12(join145(staging, "marker"), command3.marker);
125560
+ await rm35(staging, { recursive: true, force: true });
125307
125561
  }
125308
125562
  }
125309
125563
  return formatFeedback({
@@ -125327,10 +125581,10 @@ init_cliFeedback();
125327
125581
  init_errors3();
125328
125582
  init_exitCode();
125329
125583
  import { lstat as lstat24 } from "node:fs/promises";
125330
- import { join as join145, resolve as resolve53 } from "node:path";
125584
+ import { join as join146, resolve as resolve53 } from "node:path";
125331
125585
  var HOST_DIRS = { claude: ".claude", cursor: ".cursor", codex: ".agents" };
125332
125586
  async function detectLocalAgent(agent, repo) {
125333
- const path3 = join145(repo, HOST_DIRS[agent]);
125587
+ const path3 = join146(repo, HOST_DIRS[agent]);
125334
125588
  try {
125335
125589
  const entry = await lstat24(path3);
125336
125590
  if (!entry.isDirectory() || entry.isSymbolicLink()) {
@@ -125355,7 +125609,7 @@ async function installAutoLocalSkills(root2, path3, dryRun, detect = detectLocal
125355
125609
  if (selectedAgent ? selectedAgent === "all" || agent === selectedAgent : await detect(agent, repo))
125356
125610
  agents.push(agent);
125357
125611
  }
125358
- const targets = agents.length ? agents.map((agent) => ({ agent, path: join145(repo, HOST_DIRS[agent]) })) : [{ path: join145(repo, ".agents") }];
125612
+ const targets = agents.length ? agents.map((agent) => ({ agent, path: join146(repo, HOST_DIRS[agent]) })) : [{ path: join146(repo, ".agents") }];
125359
125613
  const previews = [];
125360
125614
  for (const target of targets)
125361
125615
  previews.push(await installLocalSkills(root2, target.path, true, target.agent));
@@ -125388,7 +125642,7 @@ init_cliFeedback();
125388
125642
  init_errors3();
125389
125643
  init_exitCode();
125390
125644
  import { existsSync as existsSync40 } from "node:fs";
125391
- import { dirname as dirname56, join as join147, resolve as resolve54 } from "node:path";
125645
+ import { dirname as dirname56, join as join148, resolve as resolve54 } from "node:path";
125392
125646
  import { fileURLToPath as fileURLToPath11 } from "node:url";
125393
125647
 
125394
125648
  // src/project/pluginInstallTargets.ts
@@ -125397,9 +125651,9 @@ init_errors3();
125397
125651
  init_exitCode();
125398
125652
  import { execFile as execFile21 } from "node:child_process";
125399
125653
  import { existsSync as existsSync39 } from "node:fs";
125400
- import { cp as cp4, mkdir as mkdir46, readdir as readdir36, readFile as readFile120, rename as rename13, rm as rm35, writeFile as writeFile35 } from "node:fs/promises";
125654
+ import { cp as cp4, mkdir as mkdir46, readdir as readdir37, readFile as readFile120, rename as rename13, rm as rm36, writeFile as writeFile35 } from "node:fs/promises";
125401
125655
  import { homedir as homedir2 } from "node:os";
125402
- import { dirname as dirname55, join as join146 } from "node:path";
125656
+ import { dirname as dirname55, join as join147 } from "node:path";
125403
125657
  import { promisify as promisify18 } from "node:util";
125404
125658
  var execFileAsync6 = promisify18(execFile21);
125405
125659
  var MARKETPLACE_NAME = "c4a";
@@ -125453,23 +125707,23 @@ async function claudePluginInstalled(pluginId) {
125453
125707
  }
125454
125708
  }
125455
125709
  function codexHome() {
125456
- return process.env.CODEX_HOME?.trim() || join146(homedir2(), ".codex");
125710
+ return process.env.CODEX_HOME?.trim() || join147(homedir2(), ".codex");
125457
125711
  }
125458
125712
  function claudePluginCacheRoot() {
125459
125713
  const explicitRoot = process.env[CLAUDE_PLUGIN_CACHE_ROOT_ENV2]?.trim();
125460
125714
  if (explicitRoot)
125461
125715
  return explicitRoot;
125462
125716
  const home = process.env[CLAUDE_PLUGIN_CACHE_HOME_ENV2]?.trim() || homedir2();
125463
- return join146(home, ".claude", "plugins", "cache");
125717
+ return join147(home, ".claude", "plugins", "cache");
125464
125718
  }
125465
125719
  function sharedSkillsRoot() {
125466
- return process.env[SHARED_SKILLS_ROOT_ENV]?.trim() || join146(homedir2(), ".agents", "skills");
125720
+ return process.env[SHARED_SKILLS_ROOT_ENV]?.trim() || join147(homedir2(), ".agents", "skills");
125467
125721
  }
125468
125722
  function claudeSkillsRoot() {
125469
- return process.env[CLAUDE_SKILLS_ROOT_ENV]?.trim() || join146(homedir2(), ".claude", "skills");
125723
+ return process.env[CLAUDE_SKILLS_ROOT_ENV]?.trim() || join147(homedir2(), ".claude", "skills");
125470
125724
  }
125471
125725
  function cursorPluginRoot() {
125472
- return process.env[CURSOR_PLUGIN_ROOT_ENV]?.trim() || join146(homedir2(), ".cursor", "plugins", "local", PLUGIN_NAME);
125726
+ return process.env[CURSOR_PLUGIN_ROOT_ENV]?.trim() || join147(homedir2(), ".cursor", "plugins", "local", PLUGIN_NAME);
125473
125727
  }
125474
125728
  function blockHeader(line) {
125475
125729
  const match = line.match(/^\s*\[([^\]]+)\]\s*$/u);
@@ -125520,7 +125774,7 @@ function pruneLegacyCodexConfigContent(content3) {
125520
125774
  `), removed };
125521
125775
  }
125522
125776
  async function pruneLegacyCodexConfig(dryRun, steps) {
125523
- const configPath = join146(codexHome(), "config.toml");
125777
+ const configPath = join147(codexHome(), "config.toml");
125524
125778
  const current3 = await readFile120(configPath, "utf8").catch(() => "");
125525
125779
  if (!current3)
125526
125780
  return;
@@ -125537,10 +125791,10 @@ async function pruneLegacyCodexConfig(dryRun, steps) {
125537
125791
  }
125538
125792
  }
125539
125793
  async function pruneCodexPluginCacheForName(pluginName, keepVersion, dryRun, steps) {
125540
- const cacheRoot = join146(codexHome(), "plugins", "cache", MARKETPLACE_NAME, pluginName);
125794
+ const cacheRoot = join147(codexHome(), "plugins", "cache", MARKETPLACE_NAME, pluginName);
125541
125795
  if (!existsSync39(cacheRoot))
125542
125796
  return;
125543
- const versions = (await readdir36(cacheRoot, { withFileTypes: true }).catch(() => [])).filter((entry) => entry.isDirectory() && entry.name !== keepVersion).map((entry) => entry.name).sort();
125797
+ const versions = (await readdir37(cacheRoot, { withFileTypes: true }).catch(() => [])).filter((entry) => entry.isDirectory() && entry.name !== keepVersion).map((entry) => entry.name).sort();
125544
125798
  if (versions.length === 0)
125545
125799
  return;
125546
125800
  steps.push({
@@ -125549,7 +125803,7 @@ async function pruneCodexPluginCacheForName(pluginName, keepVersion, dryRun, ste
125549
125803
  status: dryRun ? "planned" : "ran"
125550
125804
  });
125551
125805
  if (!dryRun)
125552
- await Promise.all(versions.map((version3) => rm35(join146(cacheRoot, version3), { recursive: true, force: true })));
125806
+ await Promise.all(versions.map((version3) => rm36(join147(cacheRoot, version3), { recursive: true, force: true })));
125553
125807
  }
125554
125808
  async function pruneCodexPluginCache(currentVersion, dryRun, steps) {
125555
125809
  await pruneCodexPluginCacheForName(PLUGIN_NAME, currentVersion, dryRun, steps);
@@ -125559,7 +125813,7 @@ async function pruneCodexPluginCache(currentVersion, dryRun, steps) {
125559
125813
  }
125560
125814
  async function isEmptyDir2(dir) {
125561
125815
  try {
125562
- return (await readdir36(dir)).length === 0;
125816
+ return (await readdir37(dir)).length === 0;
125563
125817
  } catch {
125564
125818
  return false;
125565
125819
  }
@@ -125569,31 +125823,31 @@ async function pruneClaudeOrphanContextCache(dryRun, steps) {
125569
125823
  if (!existsSync39(cacheRoot))
125570
125824
  return;
125571
125825
  const removed = [];
125572
- const marketplaces = await readdir36(cacheRoot, { withFileTypes: true }).catch(() => []);
125826
+ const marketplaces = await readdir37(cacheRoot, { withFileTypes: true }).catch(() => []);
125573
125827
  for (const marketplace of marketplaces) {
125574
125828
  if (!marketplace.isDirectory())
125575
125829
  continue;
125576
- const pluginDir = join146(cacheRoot, marketplace.name, PLUGIN_NAME);
125830
+ const pluginDir = join147(cacheRoot, marketplace.name, PLUGIN_NAME);
125577
125831
  if (!existsSync39(pluginDir))
125578
125832
  continue;
125579
- const versions = await readdir36(pluginDir, { withFileTypes: true }).catch(() => []);
125833
+ const versions = await readdir37(pluginDir, { withFileTypes: true }).catch(() => []);
125580
125834
  for (const version3 of versions) {
125581
125835
  if (!version3.isDirectory())
125582
125836
  continue;
125583
- const versionDir = join146(pluginDir, version3.name);
125584
- if (!existsSync39(join146(versionDir, ORPHAN_MARKER2)))
125837
+ const versionDir = join147(pluginDir, version3.name);
125838
+ if (!existsSync39(join147(versionDir, ORPHAN_MARKER2)))
125585
125839
  continue;
125586
125840
  removed.push(`${marketplace.name}/${PLUGIN_NAME}/${version3.name}`);
125587
125841
  if (!dryRun) {
125588
- await rm35(versionDir, { recursive: true, force: true });
125842
+ await rm36(versionDir, { recursive: true, force: true });
125589
125843
  }
125590
125844
  }
125591
125845
  if (!dryRun && await isEmptyDir2(pluginDir)) {
125592
- await rm35(pluginDir, { recursive: true, force: true });
125846
+ await rm36(pluginDir, { recursive: true, force: true });
125593
125847
  }
125594
- const marketplaceDir = join146(cacheRoot, marketplace.name);
125848
+ const marketplaceDir = join147(cacheRoot, marketplace.name);
125595
125849
  if (!dryRun && await isEmptyDir2(marketplaceDir)) {
125596
- await rm35(marketplaceDir, { recursive: true, force: true });
125850
+ await rm36(marketplaceDir, { recursive: true, force: true });
125597
125851
  }
125598
125852
  }
125599
125853
  if (removed.length > 0) {
@@ -125612,12 +125866,12 @@ async function pruneClaudeLegacyPluginCache(dryRun, steps) {
125612
125866
  return;
125613
125867
  const removed = [];
125614
125868
  for (const pluginName of LEGACY_PLUGIN_NAMES) {
125615
- const pluginDir = join146(cacheRoot, MARKETPLACE_NAME, pluginName);
125869
+ const pluginDir = join147(cacheRoot, MARKETPLACE_NAME, pluginName);
125616
125870
  if (!existsSync39(pluginDir))
125617
125871
  continue;
125618
125872
  removed.push(`${MARKETPLACE_NAME}/${pluginName}`);
125619
125873
  if (!dryRun) {
125620
- await rm35(pluginDir, { recursive: true, force: true });
125874
+ await rm36(pluginDir, { recursive: true, force: true });
125621
125875
  }
125622
125876
  }
125623
125877
  if (removed.length > 0) {
@@ -125629,12 +125883,12 @@ async function pruneClaudeLegacyPluginCache(dryRun, steps) {
125629
125883
  }
125630
125884
  }
125631
125885
  async function pruneClaudeSupersededContextCache(root2, dryRun, steps) {
125632
- const manifest = await readFile120(join146(root2, "claude", ".claude-plugin", "plugin.json"), "utf8").then((content3) => JSON.parse(content3)).catch(() => null);
125886
+ const manifest = await readFile120(join147(root2, "claude", ".claude-plugin", "plugin.json"), "utf8").then((content3) => JSON.parse(content3)).catch(() => null);
125633
125887
  const currentVersion = typeof manifest?.version === "string" ? manifest.version : null;
125634
125888
  if (!currentVersion)
125635
125889
  return;
125636
- const pluginDir = join146(claudePluginCacheRoot(), MARKETPLACE_NAME, PLUGIN_NAME);
125637
- const staleVersions = (await readdir36(pluginDir, { withFileTypes: true }).catch(() => [])).filter((entry) => entry.isDirectory() && entry.name !== currentVersion).map((entry) => entry.name);
125890
+ const pluginDir = join147(claudePluginCacheRoot(), MARKETPLACE_NAME, PLUGIN_NAME);
125891
+ const staleVersions = (await readdir37(pluginDir, { withFileTypes: true }).catch(() => [])).filter((entry) => entry.isDirectory() && entry.name !== currentVersion).map((entry) => entry.name);
125638
125892
  if (staleVersions.length === 0)
125639
125893
  return;
125640
125894
  steps.push({
@@ -125643,7 +125897,7 @@ async function pruneClaudeSupersededContextCache(root2, dryRun, steps) {
125643
125897
  status: dryRun ? "planned" : "ran"
125644
125898
  });
125645
125899
  if (!dryRun) {
125646
- await Promise.all(staleVersions.map((version3) => rm35(join146(pluginDir, version3), { recursive: true, force: true })));
125900
+ await Promise.all(staleVersions.map((version3) => rm36(join147(pluginDir, version3), { recursive: true, force: true })));
125647
125901
  }
125648
125902
  }
125649
125903
  function enableCodexPluginConfig(content3) {
@@ -125707,7 +125961,7 @@ source = ${JSON.stringify(root2)}
125707
125961
  `;
125708
125962
  }
125709
125963
  async function ensureCodexPluginEnabled() {
125710
- const configPath = join146(codexHome(), "config.toml");
125964
+ const configPath = join147(codexHome(), "config.toml");
125711
125965
  await mkdir46(dirname55(configPath), { recursive: true });
125712
125966
  const current3 = await readFile120(configPath, "utf8").catch(() => "");
125713
125967
  const next2 = enableCodexPluginConfig(current3);
@@ -125716,7 +125970,7 @@ async function ensureCodexPluginEnabled() {
125716
125970
  }
125717
125971
  }
125718
125972
  async function ensureCodexLocalMarketplace(root2) {
125719
- const configPath = join146(codexHome(), "config.toml");
125973
+ const configPath = join147(codexHome(), "config.toml");
125720
125974
  await mkdir46(dirname55(configPath), { recursive: true });
125721
125975
  const current3 = await readFile120(configPath, "utf8").catch(() => "");
125722
125976
  const next2 = upsertCodexLocalMarketplaceConfig(current3, root2);
@@ -125725,7 +125979,7 @@ async function ensureCodexLocalMarketplace(root2) {
125725
125979
  }
125726
125980
  }
125727
125981
  async function codexPluginVersion(root2) {
125728
- const manifestPath = join146(root2, "codex", ".codex-plugin", "plugin.json");
125982
+ const manifestPath = join147(root2, "codex", ".codex-plugin", "plugin.json");
125729
125983
  const manifest = JSON.parse(await readFile120(manifestPath, "utf8"));
125730
125984
  if (typeof manifest.version !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(manifest.version)) {
125731
125985
  throw new Error(`Codex plugin manifest has an invalid version: ${manifestPath}`);
@@ -125733,13 +125987,13 @@ async function codexPluginVersion(root2) {
125733
125987
  return manifest.version;
125734
125988
  }
125735
125989
  function codexPluginCacheDir(version3) {
125736
- return join146(codexHome(), "plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME, version3);
125990
+ return join147(codexHome(), "plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME, version3);
125737
125991
  }
125738
125992
  async function replaceDirectoryFromSource(source2, target) {
125739
125993
  await mkdir46(dirname55(target), { recursive: true });
125740
125994
  const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
125741
125995
  const previous3 = `${target}.previous-${process.pid}-${Date.now()}`;
125742
- await rm35(temporary, { recursive: true, force: true });
125996
+ await rm36(temporary, { recursive: true, force: true });
125743
125997
  await cp4(source2, temporary, { recursive: true, force: true });
125744
125998
  const hadPrevious = existsSync39(target);
125745
125999
  try {
@@ -125747,16 +126001,16 @@ async function replaceDirectoryFromSource(source2, target) {
125747
126001
  await rename13(target, previous3);
125748
126002
  await rename13(temporary, target);
125749
126003
  if (hadPrevious)
125750
- await rm35(previous3, { recursive: true, force: true });
126004
+ await rm36(previous3, { recursive: true, force: true });
125751
126005
  } catch (error) {
125752
- await rm35(temporary, { recursive: true, force: true });
126006
+ await rm36(temporary, { recursive: true, force: true });
125753
126007
  if (hadPrevious && !existsSync39(target) && existsSync39(previous3))
125754
126008
  await rename13(previous3, target);
125755
126009
  throw error;
125756
126010
  }
125757
126011
  }
125758
126012
  async function materializeCodexPluginCache(root2, version3, dryRun, steps) {
125759
- const source2 = join146(root2, "codex");
126013
+ const source2 = join147(root2, "codex");
125760
126014
  const target = codexPluginCacheDir(version3);
125761
126015
  steps.push({
125762
126016
  agent: "codex",
@@ -125768,13 +126022,13 @@ async function materializeCodexPluginCache(root2, version3, dryRun, steps) {
125768
126022
  await replaceDirectoryFromSource(source2, target);
125769
126023
  }
125770
126024
  async function bundledProviderSkillNames(root2) {
125771
- const skillsRoot = join146(root2, "skills");
125772
- const entries2 = await readdir36(skillsRoot, { withFileTypes: true });
126025
+ const skillsRoot = join147(root2, "skills");
126026
+ const entries2 = await readdir37(skillsRoot, { withFileTypes: true });
125773
126027
  const names = [];
125774
126028
  for (const entry of entries2) {
125775
126029
  if (!entry.isDirectory() || entry.name === "context")
125776
126030
  continue;
125777
- const skillPath = join146(skillsRoot, entry.name, "SKILL.md");
126031
+ const skillPath = join147(skillsRoot, entry.name, "SKILL.md");
125778
126032
  if (!existsSync39(skillPath))
125779
126033
  continue;
125780
126034
  const skill = await readFile120(skillPath, "utf8");
@@ -125789,10 +126043,10 @@ async function bundledProviderSkillNames(root2) {
125789
126043
  return names;
125790
126044
  }
125791
126045
  async function materializeProviderSkills(root2, targetRoot, agent, dryRun, steps) {
125792
- const sourceRoot = join146(root2, "skills");
126046
+ const sourceRoot = join147(root2, "skills");
125793
126047
  for (const name3 of await bundledProviderSkillNames(root2)) {
125794
- const source2 = join146(sourceRoot, name3);
125795
- const target = join146(targetRoot, name3);
126048
+ const source2 = join147(sourceRoot, name3);
126049
+ const target = join147(targetRoot, name3);
125796
126050
  steps.push({
125797
126051
  agent,
125798
126052
  command: `materialize lifecycle Provider skill: ${shellQuote8(source2)} -> ${shellQuote8(target)}`,
@@ -125803,7 +126057,7 @@ async function materializeProviderSkills(root2, targetRoot, agent, dryRun, steps
125803
126057
  }
125804
126058
  }
125805
126059
  async function installCursor(root2, dryRun, steps) {
125806
- const source2 = join146(root2, "cursor");
126060
+ const source2 = join147(root2, "cursor");
125807
126061
  const target = cursorPluginRoot();
125808
126062
  steps.push({
125809
126063
  agent: "cursor",
@@ -125858,12 +126112,12 @@ async function installCodex(root2, dryRun, steps) {
125858
126112
  steps.push({ agent: "codex", command: commandLine("codex", addArgs), status: dryRun ? "planned" : "ran" });
125859
126113
  steps.push({
125860
126114
  agent: "codex",
125861
- command: `ensure ${shellQuote8(join146(codexHome(), "config.toml"))} registers local marketplace ${shellQuote8(MARKETPLACE_NAME)}`,
126115
+ command: `ensure ${shellQuote8(join147(codexHome(), "config.toml"))} registers local marketplace ${shellQuote8(MARKETPLACE_NAME)}`,
125862
126116
  status: dryRun ? "planned" : "ran"
125863
126117
  });
125864
126118
  steps.push({
125865
126119
  agent: "codex",
125866
- command: `ensure ${shellQuote8(join146(codexHome(), "config.toml"))} enables ${shellQuote8(PLUGIN_ID)}`,
126120
+ command: `ensure ${shellQuote8(join147(codexHome(), "config.toml"))} enables ${shellQuote8(PLUGIN_ID)}`,
125867
126121
  status: dryRun ? "planned" : "ran"
125868
126122
  });
125869
126123
  if (dryRun) {
@@ -125918,13 +126172,13 @@ function pluginRootCandidates() {
125918
126172
  return [resolve54(envRoot)];
125919
126173
  const candidates = [];
125920
126174
  for (const dir of packageCandidateDirs()) {
125921
- candidates.push(join147(dir, "plugins"));
125922
- candidates.push(join147(dir, "dist", "plugins"));
126175
+ candidates.push(join148(dir, "plugins"));
126176
+ candidates.push(join148(dir, "dist", "plugins"));
125923
126177
  }
125924
126178
  return [...new Set(candidates)];
125925
126179
  }
125926
126180
  function isInstallablePluginRoot(root2) {
125927
- return existsSync40(join147(root2, ".claude-plugin", "marketplace.json")) && existsSync40(join147(root2, ".agents", "plugins", "marketplace.json")) && existsSync40(join147(root2, "claude", ".claude-plugin", "plugin.json")) && existsSync40(join147(root2, "codex", ".codex-plugin", "plugin.json")) && existsSync40(join147(root2, "cursor", ".cursor-plugin", "plugin.json")) && existsSync40(join147(root2, "skills"));
126181
+ return existsSync40(join148(root2, ".claude-plugin", "marketplace.json")) && existsSync40(join148(root2, ".agents", "plugins", "marketplace.json")) && existsSync40(join148(root2, "claude", ".claude-plugin", "plugin.json")) && existsSync40(join148(root2, "codex", ".codex-plugin", "plugin.json")) && existsSync40(join148(root2, "cursor", ".cursor-plugin", "plugin.json")) && existsSync40(join148(root2, "skills"));
125928
126182
  }
125929
126183
  function resolveBundledPluginsRoot() {
125930
126184
  const candidates = pluginRootCandidates();
@@ -126190,10 +126444,10 @@ function readQuickstartPath() {
126190
126444
  try {
126191
126445
  let dir = dirname57(fileURLToPath12(import.meta.url));
126192
126446
  for (let i2 = 0;i2 < 8; i2++) {
126193
- const candidate = join148(dir, "docs", "quickstart.md");
126447
+ const candidate = join149(dir, "docs", "quickstart.md");
126194
126448
  if (existsSync41(candidate))
126195
126449
  return candidate;
126196
- const pkg = join148(dir, "package.json");
126450
+ const pkg = join149(dir, "package.json");
126197
126451
  if (existsSync41(pkg))
126198
126452
  return candidate;
126199
126453
  const parent2 = dirname57(dir);
@@ -126202,7 +126456,7 @@ function readQuickstartPath() {
126202
126456
  dir = parent2;
126203
126457
  }
126204
126458
  } catch {}
126205
- return join148(dirname57(fileURLToPath12(import.meta.url)), "docs", "quickstart.md");
126459
+ return join149(dirname57(fileURLToPath12(import.meta.url)), "docs", "quickstart.md");
126206
126460
  }
126207
126461
  var GREEN = "\x1B[32m";
126208
126462
  var RESET = "\x1B[0m";