@lousy-agents/cli 5.23.9 → 5.23.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3053,7 +3053,7 @@ exports.basename = (path, { windows } = {}) => {
3053
3053
 
3054
3054
 
3055
3055
  },
3056
- 6416(__unused_rspack_module, __unused_rspack___webpack_exports__, __webpack_require__) {
3056
+ 5219(__unused_rspack_module, __unused_rspack___webpack_exports__, __webpack_require__) {
3057
3057
  // NAMESPACE OBJECT: ../../node_modules/micromark/lib/constructs.js
3058
3058
  var constructs_namespaceObject = {};
3059
3059
  __webpack_require__.r(constructs_namespaceObject);
@@ -3195,7 +3195,7 @@ const external_node_async_hooks_namespaceObject = __rspack_createRequire_require
3195
3195
 
3196
3196
  const file_observation_active = new external_node_async_hooks_namespaceObject.AsyncLocalStorage();
3197
3197
  function recordFileObservationFailure(error, kind) {
3198
- const failures = file_observation_active.getStore();
3198
+ const failures = file_observation_active.getStore()?.failures;
3199
3199
  if (!failures)
3200
3200
  return;
3201
3201
  let kinds = failures.get(error);
@@ -3204,13 +3204,17 @@ function recordFileObservationFailure(error, kind) {
3204
3204
  kinds.add(kind);
3205
3205
  }
3206
3206
  function isFileObservationFailure(error, kind) {
3207
- return file_observation_active.getStore()?.get(error)?.has(kind) === true;
3207
+ return file_observation_active.getStore()?.failures.get(error)?.has(kind) === true;
3208
+ }
3209
+ async function observedFilePublicationPending(filePath, identity) {
3210
+ return await file_observation_active.getStore()?.publicationPending?.(filePath, identity) ?? false;
3208
3211
  }
3209
3212
  // Each Root observation owns its receipts, including nested and concurrent reads.
3210
- function fileObservation() {
3213
+ function fileObservation(options = {}) {
3211
3214
  const failures = new Map();
3215
+ const context = { failures, ...options };
3212
3216
  return {
3213
- run(operation) { return file_observation_active.run(failures, operation); },
3217
+ run(operation) { return file_observation_active.run(context, operation); },
3214
3218
  has(error, kind) { return failures.get(error)?.has(kind) === true; },
3215
3219
  };
3216
3220
  }
@@ -5489,17 +5493,19 @@ function cleanupSidecarStages(target, assertCurrent, native, onlyStage) {
5489
5493
  }
5490
5494
  // Readers reject the linked record and retry. Authorized cleanup may handle
5491
5495
  // the one matching stage; recognition streams past the opportunistic budget.
5492
- function sidecar_lock_staging_sidecarPublicationPending(target, onStage) {
5496
+ function sidecar_lock_staging_sidecarPublicationPending(target, onStage, options = {}) {
5493
5497
  let entries;
5494
5498
  let callbackFailure;
5495
5499
  try {
5496
5500
  const current = external_node_fs_.lstatSync(target, { bigint: true, throwIfNoEntry: false });
5497
5501
  if (!current)
5498
- return true;
5502
+ return !options.requireStage;
5503
+ if (options.identity && !sameFileIdentityForCleanup(current, options.identity))
5504
+ return false;
5499
5505
  if (!current.isFile() || current.isSymbolicLink())
5500
5506
  return false;
5501
5507
  if (current.nlink === 1n)
5502
- return true;
5508
+ return !options.requireStage;
5503
5509
  if (current.nlink !== 2n)
5504
5510
  return false;
5505
5511
  const prefix = stagingPrefix(target);
@@ -5523,7 +5529,7 @@ function sidecar_lock_staging_sidecarPublicationPending(target, onStage) {
5523
5529
  }
5524
5530
  }
5525
5531
  const after = external_node_fs_.lstatSync(target, { bigint: true, throwIfNoEntry: false });
5526
- return !after || !sameFileIdentityForCleanup(after, current) || after.nlink === 1n;
5532
+ return !options.requireStage && (!after || !sameFileIdentityForCleanup(after, current) || after.nlink === 1n);
5527
5533
  }
5528
5534
  catch {
5529
5535
  if (callbackFailure)
@@ -6052,6 +6058,236 @@ function pinNodeDirectoryForModeSync(dirPath, options = {}) {
6052
6058
  }
6053
6059
  }
6054
6060
 
6061
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/test-hooks.js
6062
+
6063
+ let test_hooks_fsSafeTestHooks;
6064
+ function allowFsSafeTestHooks() {
6065
+ return false || process.env.VITEST === "true";
6066
+ }
6067
+ function getFsSafeTestHooks() {
6068
+ return test_hooks_fsSafeTestHooks;
6069
+ }
6070
+ function __setFsSafeTestHooksForTest(hooks) {
6071
+ if (hooks && !allowFsSafeTestHooks()) {
6072
+ throw new Error("__setFsSafeTestHooksForTest is only available in tests");
6073
+ }
6074
+ test_hooks_fsSafeTestHooks = hooks;
6075
+ }
6076
+
6077
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/timing.js
6078
+ const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
6079
+ function scheduleTimeout(callback, ms) {
6080
+ let timer;
6081
+ if (Number.isFinite(ms) && ms > MAX_TIMER_DELAY_MS) {
6082
+ const startedAt = performance.now();
6083
+ const tick = () => {
6084
+ const remaining = ms - (performance.now() - startedAt);
6085
+ if (remaining <= 0)
6086
+ callback();
6087
+ else
6088
+ timer = setTimeout(tick, Math.min(remaining, MAX_TIMER_DELAY_MS));
6089
+ };
6090
+ // Node clamps overflowing delays to 1 ms. Rearm bounded timers against a
6091
+ // monotonic clock so clock changes and event-loop stalls cannot shorten them.
6092
+ timer = setTimeout(tick, MAX_TIMER_DELAY_MS);
6093
+ }
6094
+ else {
6095
+ timer = setTimeout(callback, ms);
6096
+ }
6097
+ return () => clearTimeout(timer);
6098
+ }
6099
+ function sleep(ms) {
6100
+ return new Promise((resolve) => { scheduleTimeout(resolve, ms); });
6101
+ }
6102
+ function sleepSync(ms) {
6103
+ if (ms <= 0) {
6104
+ return;
6105
+ }
6106
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
6107
+ }
6108
+ async function withTimeout(promise, timeoutMs, labelOrOptions = {
6109
+ message: "timeout",
6110
+ }) {
6111
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
6112
+ return await promise;
6113
+ }
6114
+ const options = typeof labelOrOptions === "string" ? { label: labelOrOptions } : labelOrOptions;
6115
+ const createError = options.createError ??
6116
+ (() => new Error(options.message ?? `${options.label ?? "operation"} timed out after ${timeoutMs}ms`));
6117
+ let cancelTimeout;
6118
+ try {
6119
+ return await Promise.race([
6120
+ promise,
6121
+ new Promise((_, reject) => {
6122
+ cancelTimeout = scheduleTimeout(() => {
6123
+ try {
6124
+ reject(createError());
6125
+ }
6126
+ catch (error) {
6127
+ reject(error);
6128
+ }
6129
+ }, timeoutMs);
6130
+ }),
6131
+ ]);
6132
+ }
6133
+ finally {
6134
+ cancelTimeout?.();
6135
+ }
6136
+ }
6137
+
6138
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/publication-recovery.js
6139
+
6140
+
6141
+
6142
+
6143
+
6144
+
6145
+
6146
+
6147
+ const non9pDevices = new Set();
6148
+ /** Other platforms keep their existing path even when the option is enabled. */
6149
+ function shouldPrepareDrvfsRecovery(enabled, dev) {
6150
+ if (enabled !== true)
6151
+ return false;
6152
+ // Synthetic mount evidence must not inherit observations from the real host.
6153
+ if (getFsSafeTestHooks()?.drvfsMountObservation)
6154
+ return true;
6155
+ if (process.platform !== "linux")
6156
+ return false;
6157
+ if (dev === undefined)
6158
+ return true;
6159
+ // Linux 9p allocates anonymous devices (major zero), never block devices.
6160
+ if (((dev >> 8n) & 0xfffn) !== 0n || ((dev >> 32n) & 0xfffff000n) !== 0n)
6161
+ return false;
6162
+ return !non9pDevices.has(dev);
6163
+ }
6164
+ /** Negative evidence only: a stale/reused device number can only disable recovery. */
6165
+ function mayPrepareDrvfsRecoveryAtFd(parentFd, dev) {
6166
+ if (!shouldPrepareDrvfsRecovery(true, dev))
6167
+ return false;
6168
+ if (getFsSafeTestHooks()?.drvfsMountObservation)
6169
+ return true;
6170
+ try {
6171
+ if (native_getNativeBinding()?.is9pFilesystem?.(parentFd) === false) {
6172
+ non9pDevices.add(dev);
6173
+ return false;
6174
+ }
6175
+ }
6176
+ catch { /* Unavailable evidence preserves full recovery-time verification. */ }
6177
+ return true;
6178
+ }
6179
+ /** No sampling or positive cache: the retained directory's exact mount owns admission. */
6180
+ function admitsDrvfsRenameRecoveryAtFd(parentFd) {
6181
+ try {
6182
+ const hook = getFsSafeTestHooks()?.drvfsMountObservation;
6183
+ if (!hook && process.platform !== "linux")
6184
+ return false;
6185
+ if (!Number.isInteger(parentFd) || parentFd < 0)
6186
+ return false;
6187
+ const observation = hook ? hook(parentFd) : (() => {
6188
+ if (external_node_fs_.statfsSync("/proc/self/fd", { bigint: true }).type !== 0x9fa0n)
6189
+ return undefined;
6190
+ // statfs follows this kernel-owned descriptor alias to the retained parent.
6191
+ return {
6192
+ magic: external_node_fs_.statfsSync(`/proc/self/fd/${parentFd}`, { bigint: true }).type,
6193
+ fdinfo: external_node_fs_.readFileSync(`/proc/self/fdinfo/${parentFd}`, "utf8"),
6194
+ mountinfo: external_node_fs_.readFileSync("/proc/self/mountinfo", "utf8"),
6195
+ };
6196
+ })();
6197
+ if (!observation || observation.magic !== 0x01021997n)
6198
+ return false;
6199
+ const ids = [...observation.fdinfo.matchAll(/^mnt_id:\s*(\d+)\s*$/gm)];
6200
+ if (ids.length !== 1)
6201
+ return false;
6202
+ const entries = observation.mountinfo.split("\n").filter(line => line.split(" ")[0] === ids[0][1]);
6203
+ if (entries.length !== 1)
6204
+ return false;
6205
+ const [before, after, extra] = entries[0].split(" - ");
6206
+ if (!before || !after || extra !== undefined || before.split(" ").length < 6)
6207
+ return false;
6208
+ const fields = after.split(" ");
6209
+ return fields.length === 3 && fields[0] === "9p" &&
6210
+ fields[2].split(",").some(option => option === "aname=drvfs" || option.startsWith("aname=drvfs;"));
6211
+ }
6212
+ catch {
6213
+ return false;
6214
+ }
6215
+ }
6216
+ /** Exact metadata is necessary but cannot exclude inode reuse after the final close. */
6217
+ function assertRecoveredPublication(actual, expected) {
6218
+ if (!actual.isFile() || actual.isSymbolicLink() || actual.nlink !== 1n ||
6219
+ actual.dev !== expected.dev || actual.ino !== expected.ino || actual.size !== expected.size ||
6220
+ actual.mode !== expected.mode || actual.uid !== expected.uid || actual.gid !== expected.gid) {
6221
+ throw new errors_FsSafeError("path-mismatch", "published file changed during DrvFS recovery");
6222
+ }
6223
+ }
6224
+ async function recoverAfterHiddenRename(params) {
6225
+ if (!admitsDrvfsRenameRecoveryAtFd(params.parentFd)) {
6226
+ throw new errors_FsSafeError("path-mismatch", "hidden rename recovery requires a verified DrvFS mount");
6227
+ }
6228
+ await params.closeWriter();
6229
+ for (let attempt = 0;; attempt++) {
6230
+ let recovered;
6231
+ try {
6232
+ recovered = await params.reopen();
6233
+ }
6234
+ catch (error) {
6235
+ if (!hasErrorCode(error, "ENOENT") || attempt === 4)
6236
+ throw error;
6237
+ await sleep(20);
6238
+ continue;
6239
+ }
6240
+ try {
6241
+ await params.retain?.(recovered);
6242
+ }
6243
+ catch (error) {
6244
+ await params.dispose?.(recovered).catch(() => undefined);
6245
+ throw error;
6246
+ }
6247
+ return recovered;
6248
+ }
6249
+ }
6250
+ function recoverAfterHiddenRenameSync(params) {
6251
+ if (!admitsDrvfsRenameRecoveryAtFd(params.parentFd)) {
6252
+ throw new errors_FsSafeError("path-mismatch", "hidden rename recovery requires a verified DrvFS mount");
6253
+ }
6254
+ params.closeWriter();
6255
+ for (let attempt = 0;; attempt++) {
6256
+ try {
6257
+ return params.reopen();
6258
+ }
6259
+ catch (error) {
6260
+ if (!hasErrorCode(error, "ENOENT") || attempt === 4)
6261
+ throw error;
6262
+ sleepSync(20);
6263
+ }
6264
+ }
6265
+ }
6266
+ function assertRecoveredFile(fd, expected, content) {
6267
+ assertRecoveredPublication(external_node_fs_.fstatSync(fd, { bigint: true }), expected);
6268
+ if (content && !bounded_read_readFileDescriptorBoundedSync(fd, content.byteLength).equals(content)) {
6269
+ throw new errors_FsSafeError("path-mismatch", "published content changed during DrvFS recovery");
6270
+ }
6271
+ assertRecoveredPublication(external_node_fs_.fstatSync(fd, { bigint: true }), expected);
6272
+ }
6273
+ function reopenRecoveredNativeFile(binding, parentFd, basename, expected, content) {
6274
+ if (!binding.openBeneath || !binding.closeOwnedFd || !binding.stagedFileMatches) {
6275
+ throw new errors_FsSafeError("helper-unavailable", "native DrvFS recovery requires descriptor-relative verification");
6276
+ }
6277
+ const fd = binding.openBeneath(parentFd, basename, nativeOpenFlags(external_node_fs_.constants.O_RDONLY | external_node_fs_.constants.O_NONBLOCK)).fd;
6278
+ try {
6279
+ assertRecoveredFile(fd, expected, content);
6280
+ if (!binding.stagedFileMatches(parentFd, basename, fd)) {
6281
+ throw new errors_FsSafeError("path-mismatch", "published name changed during DrvFS recovery");
6282
+ }
6283
+ return fd;
6284
+ }
6285
+ catch (error) {
6286
+ binding.closeOwnedFd(fd);
6287
+ throw error;
6288
+ }
6289
+ }
6290
+
6055
6291
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-boundary.js
6056
6292
 
6057
6293
 
@@ -6430,67 +6666,6 @@ function recursiveMkdirPath(directory) {
6430
6666
  return needsAbsolutePath ? absolutePathWithRawSegments(directory) : directory;
6431
6667
  }
6432
6668
 
6433
- ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/timing.js
6434
- const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
6435
- function scheduleTimeout(callback, ms) {
6436
- let timer;
6437
- if (Number.isFinite(ms) && ms > MAX_TIMER_DELAY_MS) {
6438
- const startedAt = performance.now();
6439
- const tick = () => {
6440
- const remaining = ms - (performance.now() - startedAt);
6441
- if (remaining <= 0)
6442
- callback();
6443
- else
6444
- timer = setTimeout(tick, Math.min(remaining, MAX_TIMER_DELAY_MS));
6445
- };
6446
- // Node clamps overflowing delays to 1 ms. Rearm bounded timers against a
6447
- // monotonic clock so clock changes and event-loop stalls cannot shorten them.
6448
- timer = setTimeout(tick, MAX_TIMER_DELAY_MS);
6449
- }
6450
- else {
6451
- timer = setTimeout(callback, ms);
6452
- }
6453
- return () => clearTimeout(timer);
6454
- }
6455
- function sleep(ms) {
6456
- return new Promise((resolve) => { scheduleTimeout(resolve, ms); });
6457
- }
6458
- function sleepSync(ms) {
6459
- if (ms <= 0) {
6460
- return;
6461
- }
6462
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
6463
- }
6464
- async function withTimeout(promise, timeoutMs, labelOrOptions = {
6465
- message: "timeout",
6466
- }) {
6467
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
6468
- return await promise;
6469
- }
6470
- const options = typeof labelOrOptions === "string" ? { label: labelOrOptions } : labelOrOptions;
6471
- const createError = options.createError ??
6472
- (() => new Error(options.message ?? `${options.label ?? "operation"} timed out after ${timeoutMs}ms`));
6473
- let cancelTimeout;
6474
- try {
6475
- return await Promise.race([
6476
- promise,
6477
- new Promise((_, reject) => {
6478
- cancelTimeout = scheduleTimeout(() => {
6479
- try {
6480
- reject(createError());
6481
- }
6482
- catch (error) {
6483
- reject(error);
6484
- }
6485
- }, timeoutMs);
6486
- }),
6487
- ]);
6488
- }
6489
- finally {
6490
- cancelTimeout?.();
6491
- }
6492
- }
6493
-
6494
6669
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/exclusive-create.js
6495
6670
 
6496
6671
 
@@ -6782,6 +6957,7 @@ class AtomicFile {
6782
6957
 
6783
6958
 
6784
6959
 
6960
+
6785
6961
  function replace_file_descriptor_parentCloseFailure(primary, closeError) {
6786
6962
  return primary ? new AggregateError([primary.error, closeError], "Atomic parent preparation and close failed") : closeError;
6787
6963
  }
@@ -6844,6 +7020,8 @@ async function pinDirectoryForMode(params) {
6844
7020
  ignoreChmodError: params.ignoreChmodError,
6845
7021
  });
6846
7022
  await owner.verify();
7023
+ if (params.allowDrvfsRenameRecovery)
7024
+ mayPrepareDrvfsRecoveryAtFd(handle.fd, expected.dev);
6847
7025
  return owner;
6848
7026
  }
6849
7027
  catch (error) {
@@ -6890,6 +7068,8 @@ function* applyDirectoryMode(io, params) {
6890
7068
  let primary;
6891
7069
  try {
6892
7070
  inspectAtomicIdentity(io, () => file.statExact(), expected, false, admit);
7071
+ if (params.allowDrvfsRenameRecovery)
7072
+ mayPrepareDrvfsRecoveryAtFd(file.fd, expected.dev);
6893
7073
  if (params.mode !== "preserve") {
6894
7074
  params.mutation?.assert();
6895
7075
  file.chmod(params.mode & 0o7777);
@@ -7115,146 +7295,6 @@ function __cleanupRegisteredTempPathForTest(tempPath) {
7115
7295
  }
7116
7296
  }
7117
7297
 
7118
- ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/test-hooks.js
7119
-
7120
- let test_hooks_fsSafeTestHooks;
7121
- function allowFsSafeTestHooks() {
7122
- return false || process.env.VITEST === "true";
7123
- }
7124
- function getFsSafeTestHooks() {
7125
- return test_hooks_fsSafeTestHooks;
7126
- }
7127
- function __setFsSafeTestHooksForTest(hooks) {
7128
- if (hooks && !allowFsSafeTestHooks()) {
7129
- throw new Error("__setFsSafeTestHooksForTest is only available in tests");
7130
- }
7131
- test_hooks_fsSafeTestHooks = hooks;
7132
- }
7133
-
7134
- ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/publication-recovery.js
7135
-
7136
-
7137
-
7138
-
7139
-
7140
-
7141
-
7142
- /** Other platforms keep their existing path even when the option is enabled. */
7143
- function shouldPrepareDrvfsRecovery(enabled) {
7144
- return enabled === true && (process.platform === "linux" || getFsSafeTestHooks()?.drvfsMountObservation !== undefined);
7145
- }
7146
- /** No sampling or positive cache: the retained directory's exact mount owns admission. */
7147
- function admitsDrvfsRenameRecoveryAtFd(parentFd) {
7148
- try {
7149
- const hook = getFsSafeTestHooks()?.drvfsMountObservation;
7150
- if (!hook && process.platform !== "linux")
7151
- return false;
7152
- if (!Number.isInteger(parentFd) || parentFd < 0)
7153
- return false;
7154
- const observation = hook ? hook(parentFd) : (() => {
7155
- if (external_node_fs_.statfsSync("/proc/self/fd", { bigint: true }).type !== 0x9fa0n)
7156
- return undefined;
7157
- // statfs follows this kernel-owned descriptor alias to the retained parent.
7158
- return {
7159
- magic: external_node_fs_.statfsSync(`/proc/self/fd/${parentFd}`, { bigint: true }).type,
7160
- fdinfo: external_node_fs_.readFileSync(`/proc/self/fdinfo/${parentFd}`, "utf8"),
7161
- mountinfo: external_node_fs_.readFileSync("/proc/self/mountinfo", "utf8"),
7162
- };
7163
- })();
7164
- if (!observation || observation.magic !== 0x01021997n)
7165
- return false;
7166
- const ids = [...observation.fdinfo.matchAll(/^mnt_id:\s*(\d+)\s*$/gm)];
7167
- if (ids.length !== 1)
7168
- return false;
7169
- const entries = observation.mountinfo.split("\n").filter(line => line.split(" ")[0] === ids[0][1]);
7170
- if (entries.length !== 1)
7171
- return false;
7172
- const [before, after, extra] = entries[0].split(" - ");
7173
- if (!before || !after || extra !== undefined || before.split(" ").length < 6)
7174
- return false;
7175
- const fields = after.split(" ");
7176
- return fields.length === 3 && fields[0] === "9p" &&
7177
- fields[2].split(",").some(option => option === "aname=drvfs" || option.startsWith("aname=drvfs;"));
7178
- }
7179
- catch {
7180
- return false;
7181
- }
7182
- }
7183
- /** Exact metadata is necessary but cannot exclude inode reuse after the final close. */
7184
- function assertRecoveredPublication(actual, expected) {
7185
- if (!actual.isFile() || actual.isSymbolicLink() || actual.nlink !== 1n ||
7186
- actual.dev !== expected.dev || actual.ino !== expected.ino || actual.size !== expected.size ||
7187
- actual.mode !== expected.mode || actual.uid !== expected.uid || actual.gid !== expected.gid) {
7188
- throw new errors_FsSafeError("path-mismatch", "published file changed during DrvFS recovery");
7189
- }
7190
- }
7191
- async function recoverAfterHiddenRename(params) {
7192
- if (!admitsDrvfsRenameRecoveryAtFd(params.parentFd)) {
7193
- throw new errors_FsSafeError("path-mismatch", "hidden rename recovery requires a verified DrvFS mount");
7194
- }
7195
- await params.closeWriter();
7196
- for (let attempt = 0;; attempt++) {
7197
- let recovered;
7198
- try {
7199
- recovered = await params.reopen();
7200
- }
7201
- catch (error) {
7202
- if (!hasErrorCode(error, "ENOENT") || attempt === 4)
7203
- throw error;
7204
- await sleep(20);
7205
- continue;
7206
- }
7207
- try {
7208
- await params.retain?.(recovered);
7209
- }
7210
- catch (error) {
7211
- await params.dispose?.(recovered).catch(() => undefined);
7212
- throw error;
7213
- }
7214
- return recovered;
7215
- }
7216
- }
7217
- function recoverAfterHiddenRenameSync(params) {
7218
- if (!admitsDrvfsRenameRecoveryAtFd(params.parentFd)) {
7219
- throw new errors_FsSafeError("path-mismatch", "hidden rename recovery requires a verified DrvFS mount");
7220
- }
7221
- params.closeWriter();
7222
- for (let attempt = 0;; attempt++) {
7223
- try {
7224
- return params.reopen();
7225
- }
7226
- catch (error) {
7227
- if (!hasErrorCode(error, "ENOENT") || attempt === 4)
7228
- throw error;
7229
- sleepSync(20);
7230
- }
7231
- }
7232
- }
7233
- function assertRecoveredFile(fd, expected, content) {
7234
- assertRecoveredPublication(external_node_fs_.fstatSync(fd, { bigint: true }), expected);
7235
- if (content && !bounded_read_readFileDescriptorBoundedSync(fd, content.byteLength).equals(content)) {
7236
- throw new errors_FsSafeError("path-mismatch", "published content changed during DrvFS recovery");
7237
- }
7238
- assertRecoveredPublication(external_node_fs_.fstatSync(fd, { bigint: true }), expected);
7239
- }
7240
- function reopenRecoveredNativeFile(binding, parentFd, basename, expected, content) {
7241
- if (!binding.openBeneath || !binding.closeOwnedFd || !binding.stagedFileMatches) {
7242
- throw new errors_FsSafeError("helper-unavailable", "native DrvFS recovery requires descriptor-relative verification");
7243
- }
7244
- const fd = binding.openBeneath(parentFd, basename, nativeOpenFlags(external_node_fs_.constants.O_RDONLY | external_node_fs_.constants.O_NONBLOCK)).fd;
7245
- try {
7246
- assertRecoveredFile(fd, expected, content);
7247
- if (!binding.stagedFileMatches(parentFd, basename, fd)) {
7248
- throw new errors_FsSafeError("path-mismatch", "published name changed during DrvFS recovery");
7249
- }
7250
- return fd;
7251
- }
7252
- catch (error) {
7253
- binding.closeOwnedFd(fd);
7254
- throw error;
7255
- }
7256
- }
7257
-
7258
7298
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/directory-receipt.js
7259
7299
 
7260
7300
 
@@ -7847,8 +7887,11 @@ function staged_directory_openStagedDirectory(directory) {
7847
7887
 
7848
7888
 
7849
7889
 
7890
+
7850
7891
  /** Retained only for an explicitly enabled operation; no new default-path I/O. */
7851
- function retainDrvfsParent(directory) {
7892
+ function retainDrvfsParent(directory, dev, filesystemChecked = false) {
7893
+ if (!shouldPrepareDrvfsRecovery(true, dev))
7894
+ return undefined;
7852
7895
  let parent;
7853
7896
  try {
7854
7897
  // Resolve through the filesystem first: lexical normalization of link/..
@@ -7862,6 +7905,11 @@ function retainDrvfsParent(directory) {
7862
7905
  assertStagedDirectoryCurrent(retained.receipt);
7863
7906
  };
7864
7907
  assertCurrent();
7908
+ if (!filesystemChecked && !mayPrepareDrvfsRecoveryAtFd(retained.fd, retained.receipt.identity.dev)) {
7909
+ parent = undefined;
7910
+ external_node_fs_.closeSync(retained.fd);
7911
+ return undefined;
7912
+ }
7865
7913
  return { fd: retained.fd, assertCurrent, close() { external_node_fs_.closeSync(retained.fd); } };
7866
7914
  }
7867
7915
  catch {
@@ -7981,10 +8029,10 @@ class AtomicTempOwner {
7981
8029
  throw new Error("Atomic temp owner has no descriptor");
7982
8030
  return this.resource.fd;
7983
8031
  }
7984
- *prepareRecovery(content, directory = external_node_path_.dirname(this.pathname)) {
8032
+ *prepareRecovery(content, directory = external_node_path_.dirname(this.pathname), filesystemChecked = false) {
7985
8033
  if (!shouldPrepareDrvfsRecovery(true))
7986
8034
  return;
7987
- this.recoveryParent = retainDrvfsParent(directory);
8035
+ this.recoveryParent = retainDrvfsParent(directory, this.identity.dev, filesystemChecked);
7988
8036
  if (!this.recoveryParent)
7989
8037
  return;
7990
8038
  const observed = this.resource.statExact();
@@ -10337,11 +10385,11 @@ function fileLockSyncRootReceiptStillCurrent(pathAuthority, receipt) {
10337
10385
 
10338
10386
 
10339
10387
 
10340
- async function rootSidecarPublicationPending(lockRoot, relative, cleanAbandoned = false) {
10388
+ async function rootSidecarPublicationPending(lockRoot, relative, options = {}) {
10341
10389
  const resolved = await lockRoot.resolve(relative);
10342
10390
  const parent = external_node_path_.dirname(resolved);
10343
10391
  const identity = await directory_guard_inspectDirectoryIdentity(parent);
10344
- if (cleanAbandoned) {
10392
+ if (options.cleanAbandoned) {
10345
10393
  const admitted = admitFileLockSyncRootPath(captureFileLockSyncRootAuthority(lockRoot), resolved);
10346
10394
  const receipt = observeDirectory(external_node_path_.dirname(admitted.path));
10347
10395
  cleanupSidecarStages(admitted.path, candidate => {
@@ -10352,7 +10400,7 @@ async function rootSidecarPublicationPending(lockRoot, relative, cleanAbandoned
10352
10400
  assertFileLockSyncRootMutationAllowed(candidate, admitted.authority.denyMutations);
10353
10401
  });
10354
10402
  }
10355
- const pending = sidecar_lock_staging_sidecarPublicationPending(resolved);
10403
+ const pending = sidecar_lock_staging_sidecarPublicationPending(resolved, undefined, options);
10356
10404
  await directory_guard_inspectDirectoryIdentity(parent, identity);
10357
10405
  return pending && await lockRoot.resolve(relative) === resolved;
10358
10406
  }
@@ -10384,7 +10432,10 @@ async function openSidecarRoot(lockRoot, relative, discardObservation, onOpenFai
10384
10432
  break;
10385
10433
  }
10386
10434
  }
10387
- const observation = fileObservation();
10435
+ const observation = fileObservation({
10436
+ publicationPending: async (candidate, identity) => discardObservation === "changed" && candidate === resolved &&
10437
+ await rootSidecarPublicationPending(lockRoot, relative, { requireStage: true, identity }),
10438
+ });
10388
10439
  try {
10389
10440
  const opened = await observation.run(() => lockRoot.open(relative));
10390
10441
  if (opened.realPath !== expectedRealPath) {
@@ -10405,13 +10456,19 @@ async function openSidecarRoot(lockRoot, relative, discardObservation, onOpenFai
10405
10456
  return null;
10406
10457
  const discardable = observation.has(error, `unlinked:${resolved}`) ||
10407
10458
  (discardObservation === "changed" && observation.has(error, `changed:${resolved}`));
10408
- if (!discardObservation || (!missing && (!completeParents || !discardable)))
10459
+ const linkedChange = discardObservation === "changed" && observation.has(error, `linked-change:${resolved}`);
10460
+ if (!discardObservation || (!missing && (!completeParents || (!discardable && !linkedChange))))
10409
10461
  throw error;
10410
10462
  try {
10463
+ // Linked-change receipts already proved a matching stage while the exact
10464
+ // descriptor was open; retained ancestry and the current path still fence it.
10411
10465
  const probe = fileObservation();
10412
10466
  try {
10413
10467
  const current = await probe.run(() => lockRoot.stat(relative));
10414
- if (!current.isFile || current.isSymbolicLink || current.nlink !== 1)
10468
+ // A successor can still hold its matching publication-stage link.
10469
+ // Discard only the old read; retained ancestry is revalidated below.
10470
+ if (!current.isFile || current.isSymbolicLink || (current.nlink !== 1 &&
10471
+ !(current.nlink === 2 && await rootSidecarPublicationPending(lockRoot, relative))))
10415
10472
  throw error;
10416
10473
  }
10417
10474
  catch (probeError) {
@@ -18063,6 +18120,7 @@ class NativeStagedFile {
18063
18120
  #recoveryIdentity;
18064
18121
  #recoveryContent;
18065
18122
  #recovered = false;
18123
+ #prepareRecovery;
18066
18124
  #publicationTask;
18067
18125
  #rejectFinalSymlink = false;
18068
18126
  #unsupportedNoReplace;
@@ -18076,6 +18134,8 @@ class NativeStagedFile {
18076
18134
  this.#assertBeforeMutation = owner.assertBeforeMutation;
18077
18135
  this.#private = owner.permissionPolicy === "private-creation";
18078
18136
  this.#verifyMode = owner.permissionPolicy !== undefined;
18137
+ this.#prepareRecovery = shouldPrepareDrvfsRecovery(owner.allowDrvfsRenameRecovery, owner.directory.identity.dev) &&
18138
+ mayPrepareDrvfsRecoveryAtFd(owner.parentFd, owner.directory.identity.dev);
18079
18139
  }
18080
18140
  // The supplied closer owns parentFd even on construction or preparation failure.
18081
18141
  static async create(owner, input, maxBytes) {
@@ -18092,7 +18152,7 @@ class NativeStagedFile {
18092
18152
  }
18093
18153
  throw error;
18094
18154
  }
18095
- if (shouldPrepareDrvfsRecovery(owner.allowDrvfsRenameRecovery) && input.kind === "buffer") {
18155
+ if (staged.#prepareRecovery && input.kind === "buffer") {
18096
18156
  staged.#recoveryContent = typeof input.data === "string" ? Buffer.from(input.data, input.encoding) : Buffer.from(input.data);
18097
18157
  }
18098
18158
  await staged.#prepare(input, maxBytes);
@@ -18330,7 +18390,7 @@ class NativeStagedFile {
18330
18390
  this.#assertCurrent();
18331
18391
  assertFinalSymlinkRejected(external_node_path_.join(this.#owner.directory.realPath, basename), this.#rejectFinalSymlink);
18332
18392
  }
18333
- if (shouldPrepareDrvfsRecovery(this.#owner.allowDrvfsRenameRecovery)) {
18393
+ if (this.#prepareRecovery) {
18334
18394
  // Apply restrictive modes before exposing the name or releasing its last fd.
18335
18395
  if ((this.#owner.mode & 0o600) !== 0o600)
18336
18396
  external_node_fs_.fchmodSync(this.#file(), this.#owner.mode);
@@ -18930,10 +18990,11 @@ async function handleStaleSidecarAdmission(params) {
18930
18990
  throw error;
18931
18991
  }
18932
18992
  // An incomplete owner can still be writing; age is not liveness evidence.
18933
- if (!snapshot || (!params.parserState.parser && snapshot.payload === null) || isIncompleteSidecarLockRecord(snapshot.raw)) {
18993
+ if (!snapshot) {
18934
18994
  await params.waitForRetry();
18935
18995
  return;
18936
18996
  }
18997
+ const incomplete = (!params.parserState.parser && snapshot.payload === null) || isIncompleteSidecarLockRecord(snapshot.raw);
18937
18998
  const staleOptions = params.staleOptionsState;
18938
18999
  try {
18939
19000
  if (!staleOptions.shouldReclaimObserved) {
@@ -18969,7 +19030,7 @@ async function handleStaleSidecarAdmission(params) {
18969
19030
  assertUnheld();
18970
19031
  try {
18971
19032
  if (!shouldReclaim)
18972
- return defaultSidecarLockShouldReclaim(snapshot, params.staleMs, Date.now());
19033
+ return !incomplete && defaultSidecarLockShouldReclaim(snapshot, params.staleMs, Date.now());
18973
19034
  return await Reflect.apply(shouldReclaim, undefined, [{
18974
19035
  lockPath,
18975
19036
  normalizedTargetPath,
@@ -19015,6 +19076,9 @@ async function handleStaleSidecarAdmission(params) {
19015
19076
  await params.waitForRetry();
19016
19077
  return;
19017
19078
  }
19079
+ // Policy may diagnose an incomplete record, but can never authorize its removal.
19080
+ if (incomplete)
19081
+ throw sidecarLockStale(lockPath, normalizedTargetPath);
19018
19082
  if ((staleOptions.staleRecovery ?? "fail-closed") === "remove-if-unchanged") {
19019
19083
  const acquiredGuard = await admission.run(() => tryAcquireSidecarReclaimGuard(params.reclaimGuards, params.reclaimGuardPath, params.lockRoot));
19020
19084
  if (acquiredGuard)
@@ -19723,7 +19787,7 @@ async function acquireSidecarLock(options, context) {
19723
19787
  catch (error) {
19724
19788
  let cause = error;
19725
19789
  for (let depth = 0; depth < 4 && cause && typeof cause === "object"; depth++) {
19726
- if (observation.has(cause, "hardlink") && await rootSidecarPublicationPending(lockRoot, relativeLockPath, true)) {
19790
+ if (observation.has(cause, "hardlink") && await rootSidecarPublicationPending(lockRoot, relativeLockPath, { cleanAbandoned: true })) {
19727
19791
  exclusiveCreateConflict = true;
19728
19792
  throw Object.assign(new Error("sidecar publication in progress"), { code: "EEXIST" });
19729
19793
  }
@@ -20643,7 +20707,7 @@ async function runPinnedStagedWrite(params, parentPath, parentGuard) {
20643
20707
  ((params.mode & 0o400) !== 0 ||
20644
20708
  (process.platform === "linux" && (process.arch === "x64" || process.arch === "arm64")));
20645
20709
  if (shouldPrepareDrvfsRecovery(params.allowDrvfsRenameRecovery)) {
20646
- recoveryParent = retainDrvfsParent(parentPath);
20710
+ recoveryParent = retainDrvfsParent(parentPath, parentGuard.stat.dev);
20647
20711
  if (recoveryParent)
20648
20712
  recoveryIdentity = external_node_fs_.fstatSync(handle.fd, { bigint: true });
20649
20713
  if (recoveryParent && params.input.kind === "buffer")
@@ -21230,16 +21294,26 @@ function openedPathResolutionError(error = new errors_FsSafeError("path-mismatch
21230
21294
  }
21231
21295
  async function recordPreOpenFileChange(error, handle, filePath, before, opened) {
21232
21296
  if (!isFileObservationFailure(error, "identity") || !before?.isFile() || !opened?.isFile() ||
21233
- ![0n, 1n].includes(before.nlink) || ![0n, 1n].includes(opened.nlink))
21297
+ ![0n, 1n].includes(before.nlink) || ![0n, 1n, 2n].includes(opened.nlink))
21234
21298
  return;
21235
21299
  try {
21236
21300
  await strict_file_identity_inspectFileIdentity(async () => before);
21237
- const current = await strict_file_identity_inspectFileIdentity(() => process.platform === "win32"
21301
+ // A fresh exact descriptor distinguishes a completed handoff from a
21302
+ // still-linked generation that needs separate publication proof.
21303
+ const inspectCurrent = () => strict_file_identity_inspectFileIdentity(() => process.platform === "win32"
21238
21304
  ? external_node_fs_.fstatSync(handle.fd, { bigint: true }) : handle.stat({ bigint: true }), opened);
21239
- if (current.isFile() && [0n, 1n].includes(current.nlink) &&
21240
- (before.dev !== current.dev || before.ino !== current.ino)) {
21305
+ let current = await inspectCurrent();
21306
+ let publication = false;
21307
+ if (current.isFile() && current.nlink === 2n) {
21308
+ publication = await observedFilePublicationPending(filePath, current);
21309
+ current = await inspectCurrent();
21310
+ }
21311
+ if (current.isFile() && (before.dev !== current.dev || before.ino !== current.ino)) {
21241
21312
  // A stale pathname sample is not proof that its former inode was unlinked.
21242
- recordFileObservationFailure(error, `changed:${filePath}`);
21313
+ if ([0n, 1n].includes(current.nlink))
21314
+ recordFileObservationFailure(error, `changed:${filePath}`);
21315
+ else if (current.nlink === 2n && publication)
21316
+ recordFileObservationFailure(error, `linked-change:${filePath}`);
21243
21317
  }
21244
21318
  }
21245
21319
  catch {
@@ -21345,7 +21419,7 @@ async function openLocalFileDescriptor(filePath, options) {
21345
21419
  : await strict_file_identity_inspectFileIdentity(async () => inspect(await handle.stat({ bigint: true })), expected);
21346
21420
  }
21347
21421
  catch (error) {
21348
- if (openedIdentity && [0n, 1n].includes(openedIdentity.nlink)) {
21422
+ if (openedIdentity && [0n, 1n, 2n].includes(openedIdentity.nlink)) {
21349
21423
  await recordPreOpenFileChange(error, handle, filePath, preOpenStat, openedIdentity);
21350
21424
  }
21351
21425
  throw error;
@@ -25477,8 +25551,12 @@ async function commitPinnedWriteInRoot(root, pinned, params, input) {
25477
25551
  });
25478
25552
  }
25479
25553
  catch (error) {
25480
- if (error instanceof SidecarFallbackWriteError)
25481
- throw error.failure;
25554
+ if (error instanceof SidecarFallbackWriteError) {
25555
+ // Windows keeps its historical direct-write error identity.
25556
+ if (process.platform === "win32")
25557
+ throw error.failure;
25558
+ error = error.failure;
25559
+ }
25482
25560
  if (verifyingPublication)
25483
25561
  throw error;
25484
25562
  const errorCode = error?.code;
@@ -47339,41 +47417,6 @@ const RUN_LEVEL_RULE_IDS = new Set([
47339
47417
  return ruleId !== undefined && RUN_LEVEL_RULE_IDS.has(ruleId);
47340
47418
  }
47341
47419
 
47342
- ;// CONCATENATED MODULE: ../core/src/entities/discovery-limit-message.ts
47343
- /**
47344
- * The one wording for a directory walk that stopped at a limit, shared by lint
47345
- * (instruction/discovery-limit-reached) and doctor (discovery-limit-reached)
47346
- * so the two cannot describe the same limits differently. Each caller says
47347
- * what it was looking for and what the user should take from the gap.
47348
- */ /** The limits a walk reached; a limit it did not reach is left out. */ /** One sentence for each limit that was reached: directories, depth, entries. */ function describeDiscoveryLimits(reached, { subject, missing, consequence }) {
47349
- const sentences = [];
47350
- if (reached.maxDirectories !== undefined) {
47351
- sentences.push(`${subject} stopped after listing ${reached.maxDirectories} directories, so ${missing} in the remaining directories ${consequence}.`);
47352
- }
47353
- if (reached.maxDepth !== undefined) {
47354
- sentences.push(`${subject} did not go more than ${reached.maxDepth} directories deep, so ${missing} in deeper directories ${consequence}.`);
47355
- }
47356
- if (reached.maxEntries !== undefined) {
47357
- sentences.push(`${subject} stopped after examining ${reached.maxEntries} directory entries, so ${missing} in the remaining entries ${consequence}.`);
47358
- }
47359
- return sentences;
47360
- }
47361
- /** How many paths a message names before it counts the rest. */ const NAMED_PATHS = 5;
47362
- /**
47363
- * The first few paths joined with commas, and a count of the rest, so a
47364
- * message about a fan-out stays readable: "a, b, c, d, e, and 3 more".
47365
- */ function listPaths(paths) {
47366
- const listed = paths.slice(0, NAMED_PATHS).join(", ");
47367
- const unlisted = paths.length - NAMED_PATHS;
47368
- return unlisted > 0 ? `${listed}, and ${unlisted} more` : listed;
47369
- }
47370
- /**
47371
- * The message for instruction file discovery skipping symbolic links that
47372
- * point outside the repository, so their targets were not analyzed.
47373
- */ function describeSkippedSymlinks(paths) {
47374
- return `Instruction file discovery skipped ${paths.length} symbolic link(s) that point outside the repository, so their targets were not analyzed: ${listPaths(paths)}. Replace a link with a file inside the repository to have it analyzed.`;
47375
- }
47376
-
47377
47420
  ;// CONCATENATED MODULE: ../core/src/entities/agentic-location-catalog.ts
47378
47421
  /**
47379
47422
  * Canonical catalog of agentic construct locations shared by lint and doctor.
@@ -47617,6 +47660,41 @@ function isNestedInstructionFilename(fileName) {
47617
47660
  return NESTED_INSTRUCTION_FILENAMES.has(fileName);
47618
47661
  }
47619
47662
 
47663
+ ;// CONCATENATED MODULE: ../core/src/entities/discovery-limit-message.ts
47664
+ /**
47665
+ * The one wording for a directory walk that stopped at a limit, shared by lint
47666
+ * (instruction/discovery-limit-reached) and doctor (discovery-limit-reached)
47667
+ * so the two cannot describe the same limits differently. Each caller says
47668
+ * what it was looking for and what the user should take from the gap.
47669
+ */ /** The limits a walk reached; a limit it did not reach is left out. */ /** One sentence for each limit that was reached: directories, depth, entries. */ function describeDiscoveryLimits(reached, { subject, missing, consequence }) {
47670
+ const sentences = [];
47671
+ if (reached.maxDirectories !== undefined) {
47672
+ sentences.push(`${subject} stopped after listing ${reached.maxDirectories} directories, so ${missing} in the remaining directories ${consequence}.`);
47673
+ }
47674
+ if (reached.maxDepth !== undefined) {
47675
+ sentences.push(`${subject} did not go more than ${reached.maxDepth} directories deep, so ${missing} in deeper directories ${consequence}.`);
47676
+ }
47677
+ if (reached.maxEntries !== undefined) {
47678
+ sentences.push(`${subject} stopped after examining ${reached.maxEntries} directory entries, so ${missing} in the remaining entries ${consequence}.`);
47679
+ }
47680
+ return sentences;
47681
+ }
47682
+ /** How many paths a message names before it counts the rest. */ const NAMED_PATHS = 5;
47683
+ /**
47684
+ * The first few paths joined with commas, and a count of the rest, so a
47685
+ * message about a fan-out stays readable: "a, b, c, d, e, and 3 more".
47686
+ */ function listPaths(paths) {
47687
+ const listed = paths.slice(0, NAMED_PATHS).join(", ");
47688
+ const unlisted = paths.length - NAMED_PATHS;
47689
+ return unlisted > 0 ? `${listed}, and ${unlisted} more` : listed;
47690
+ }
47691
+ /**
47692
+ * The message for instruction file discovery skipping symbolic links that
47693
+ * point outside the repository, so their targets were not analyzed.
47694
+ */ function describeSkippedSymlinks(paths) {
47695
+ return `Instruction file discovery skipped ${paths.length} symbolic link(s) that point outside the repository, so their targets were not analyzed: ${listPaths(paths)}. Replace a link with a file inside the repository to have it analyzed.`;
47696
+ }
47697
+
47620
47698
  ;// CONCATENATED MODULE: ../core/src/lib/agentic-location-matchers.ts
47621
47699
  /**
47622
47700
  * Pure path→construct matching helpers over the agentic location catalog.
@@ -47742,6 +47820,72 @@ function hookConfigPaths(catalog = agentic_location_catalog_AGENTIC_LOCATION_CAT
47742
47820
  function instructionDiscoveryEntries(catalog = agentic_location_catalog_AGENTIC_LOCATION_CATALOG) {
47743
47821
  return catalog.filter((entry)=>entry.instructionFormat != null);
47744
47822
  }
47823
+ /**
47824
+ * Format for a `CLAUDE.md`, `AGENTS.md`, `AGENTS.MD`, or `agents.md` that the
47825
+ * catalog's exact paths and suffix walks do not already load.
47826
+ *
47827
+ * A directory that loads every markdown file keeps the file (`null` here).
47828
+ * A suffix-restricted directory such as `.github/instructions` does not load
47829
+ * these names, so they stay Claude or shared instructions.
47830
+ */ function formatForAdditionalInstructionFile(path, catalog = agentic_location_catalog_AGENTIC_LOCATION_CATALOG) {
47831
+ const normalized = normalizeRepoRelativePath(path);
47832
+ if (normalized === "") {
47833
+ return null;
47834
+ }
47835
+ const slash = normalized.lastIndexOf("/");
47836
+ const fileName = slash === -1 ? normalized : normalized.slice(slash + 1);
47837
+ if (!isNestedInstructionFilename(fileName)) {
47838
+ return null;
47839
+ }
47840
+ const best = bestMatchingEntry(normalized, catalog);
47841
+ if (best?.matchKind === "exact") {
47842
+ return null;
47843
+ }
47844
+ if (best?.matchKind === "directory-prefix" && best.fileSuffix === undefined) {
47845
+ return null;
47846
+ }
47847
+ return fileName === "CLAUDE.md" ? "claude-md" : "agents-md";
47848
+ }
47849
+
47850
+ ;// CONCATENATED MODULE: ../core/src/lib/agentic-discovery-skips.ts
47851
+ /**
47852
+ * Directories lint and doctor both leave out of discovery.
47853
+ * Pure path rules. No filesystem I/O.
47854
+ */ const BUILD_OUTPUT_DIRECTORY_NAMES = [
47855
+ "dist"
47856
+ ];
47857
+ const NAMED_SKIP_DIRECTORIES = new Set([
47858
+ "node_modules",
47859
+ ".git",
47860
+ ...BUILD_OUTPUT_DIRECTORY_NAMES
47861
+ ]);
47862
+ /**
47863
+ * True when `relativePath` is a fixture directory met below the scan root.
47864
+ * The root itself is not passed here. When the relative path has no parent
47865
+ * segment, `rootDirectoryName` is that parent, so a scan started in a
47866
+ * directory named `tests` still skips its `fixtures` child.
47867
+ *
47868
+ * `tests/fixtures` is the parent and child, not every directory named
47869
+ * `fixtures`, so `src/fixtures` stays in the scan. `__fixtures__` and
47870
+ * `testdata` are names at any depth.
47871
+ */ function isFixtureDirectory(relativePath, rootDirectoryName) {
47872
+ const segments = relativePath.split("/");
47873
+ const name = segments[segments.length - 1] ?? "";
47874
+ if (name === "__fixtures__" || name === "testdata") {
47875
+ return true;
47876
+ }
47877
+ const parent = segments.length >= 2 ? segments[segments.length - 2] : rootDirectoryName;
47878
+ return parent === "tests" && name === "fixtures";
47879
+ }
47880
+ /**
47881
+ * True when a discovered directory should not be entered. Callers that use
47882
+ * `walkRepository` pass `isFixtureDirectory` as `skipDirectory` and add
47883
+ * `BUILD_OUTPUT_DIRECTORY_NAMES` to `skipDirectoryNames` instead.
47884
+ */ function isSkippedDiscoveryDirectory(relativePath, rootDirectoryName) {
47885
+ const segments = relativePath.split("/");
47886
+ const name = segments[segments.length - 1] ?? "";
47887
+ return NAMED_SKIP_DIRECTORIES.has(name) || isFixtureDirectory(relativePath, rootDirectoryName);
47888
+ }
47745
47889
 
47746
47890
  ;// CONCATENATED MODULE: ../core/src/gateways/real-path-within-root.ts
47747
47891
  /**
@@ -47909,6 +48053,7 @@ function resolveSettings(options) {
47909
48053
  includeFile: options.includeFile,
47910
48054
  includeSubdirectories: options.includeSubdirectories ?? true,
47911
48055
  revisit: options.revisit ?? "once-per-real-directory",
48056
+ symbolicLinks: options.symbolicLinks ?? "follow-within-root",
47912
48057
  maxDepth: options.maxDepth ?? DEFAULT_MAX_WALK_DEPTH,
47913
48058
  maxDirectories: options.maxDirectories ?? DEFAULT_MAX_WALK_DIRECTORIES,
47914
48059
  maxEntries: options.maxEntries ?? DEFAULT_MAX_WALK_ENTRIES,
@@ -47927,6 +48072,13 @@ function resolveSettings(options) {
47927
48072
  /** Joins a repository-relative directory and an entry without a leading "/". */ function joinRelative(directory, name) {
47928
48073
  return directory === "" ? name : `${directory}/${name}`;
47929
48074
  }
48075
+ async function repository_walk_isSymbolicLink(absolutePath) {
48076
+ try {
48077
+ return (await (0,promises_.lstat)(absolutePath)).isSymbolicLink();
48078
+ } catch {
48079
+ return false;
48080
+ }
48081
+ }
47930
48082
  function segmentsOf(relativePath) {
47931
48083
  return relativePath.split("/").filter((segment)=>segment !== "");
47932
48084
  }
@@ -47942,6 +48094,7 @@ function segmentsOf(relativePath) {
47942
48094
  listedDirectories = 0;
47943
48095
  limitReached = false;
47944
48096
  depthLimitReached = false;
48097
+ depthLimitedDirectories = [];
47945
48098
  entriesExamined = 0;
47946
48099
  entryLimitReached = false;
47947
48100
  skippedOutsideRoot = [];
@@ -47956,6 +48109,7 @@ function segmentsOf(relativePath) {
47956
48109
  files: this.files,
47957
48110
  directoryLimitReached: this.limitReached,
47958
48111
  depthLimitReached: this.depthLimitReached,
48112
+ depthLimitedDirectories: this.depthLimitedDirectories,
47959
48113
  entryLimitReached: this.entryLimitReached,
47960
48114
  skippedOutsideRoot: this.skippedOutsideRoot,
47961
48115
  limits: {
@@ -48004,6 +48158,9 @@ function segmentsOf(relativePath) {
48004
48158
  }
48005
48159
  }
48006
48160
  async walkEntry(directoryReal, entryRelativePath, name, depth, ancestors) {
48161
+ if (this.settings.symbolicLinks === "skip" && await repository_walk_isSymbolicLink((0,external_node_path_.join)(directoryReal, name))) {
48162
+ return;
48163
+ }
48007
48164
  const entry = await inspectPathWithinRoot(this.rootReal, (0,external_node_path_.join)(directoryReal, name));
48008
48165
  if (entry.status === "outside-root") {
48009
48166
  if (this.wouldHaveCollected(entry.kind, entryRelativePath, name, depth)) {
@@ -48022,6 +48179,7 @@ function segmentsOf(relativePath) {
48022
48179
  await this.walkDirectory(entryRelativePath, depth + 1, ancestors);
48023
48180
  } else if (this.isTooDeep(entryRelativePath, name, depth) && !this.isRevisit(entry.real, ancestors)) {
48024
48181
  this.depthLimitReached = true;
48182
+ this.depthLimitedDirectories.push(entryRelativePath);
48025
48183
  }
48026
48184
  }
48027
48185
  wouldHaveCollected(kind, relativePath, name, depth) {
@@ -48066,6 +48224,7 @@ function segmentsOf(relativePath) {
48066
48224
  files: [],
48067
48225
  directoryLimitReached: false,
48068
48226
  depthLimitReached: false,
48227
+ depthLimitedDirectories: [],
48069
48228
  entryLimitReached: false,
48070
48229
  skippedOutsideRoot: [],
48071
48230
  limits: {
@@ -48078,6 +48237,307 @@ function segmentsOf(relativePath) {
48078
48237
  return new RepositoryWalk(targetDir, rootReal, settings).run();
48079
48238
  }
48080
48239
 
48240
+ ;// CONCATENATED MODULE: ../core/src/gateways/agentic-artifact-discovery.ts
48241
+ /**
48242
+ * Instruction discovery shared by lint and doctor.
48243
+ *
48244
+ * Each directory-prefix instruction location is walked from that location, so
48245
+ * depth 10 is counted from the catalog root. The walk keeps every logical
48246
+ * path (`refuse-ancestors`). Lint collapses those paths to one per real file.
48247
+ */
48248
+
48249
+
48250
+
48251
+
48252
+
48253
+
48254
+
48255
+
48256
+
48257
+ /** Directories below an agent or subagent catalog root that are still listed. */ const AGENT_CATALOG_DEPTH = 32;
48258
+ /** One skill directory below a skill root. `root/<name>/SKILL.md` is depth 1. */ const SKILL_CATALOG_DEPTH = 1;
48259
+ async function discoverInstructionLocations(targetDir, options) {
48260
+ const walks = [];
48261
+ for (const entry of instructionDiscoveryEntries()){
48262
+ if (entry.instructionFormat == null || entry.matchKind !== "directory-prefix") {
48263
+ continue;
48264
+ }
48265
+ walks.push({
48266
+ role: "catalog",
48267
+ format: entry.instructionFormat,
48268
+ walked: await walkRepository(targetDir, instructionWalkOptions(entry, options))
48269
+ });
48270
+ }
48271
+ if (options.includeNestedWalk !== false) {
48272
+ walks.push({
48273
+ role: "nested",
48274
+ format: null,
48275
+ walked: await walkRepository(targetDir, {
48276
+ ...instructionWalkOptions({
48277
+ path: "",
48278
+ matchKind: "directory-prefix",
48279
+ includeSubdirectories: true,
48280
+ fileSuffix: undefined
48281
+ }, options),
48282
+ startRelativePath: "",
48283
+ includeFile: (name)=>isNestedInstructionFilename(name),
48284
+ includeSubdirectories: true
48285
+ })
48286
+ });
48287
+ }
48288
+ return walks;
48289
+ }
48290
+ /**
48291
+ * One logical path per real file. Paths are the same file when their
48292
+ * symlink-free real paths match, so symbolic-link aliases collapse while two
48293
+ * hard links to one inode stay separate files. The path kept is the full
48294
+ * relative path that sorts first by UTF-16 code unit. That is not the directory a
48295
+ * name-ordered walk meets first: `b-extra/file` sorts before `b/file`
48296
+ * because `-` comes before `/`.
48297
+ *
48298
+ * When `preferred` is given, a path it accepts wins over one it rejects, and
48299
+ * code-unit order only breaks a tie between equals. The result is in
48300
+ * code-unit order of the kept paths either way.
48301
+ */ function collapseToFirstRealFile(files, preferred = ()=>false) {
48302
+ const sorted = [
48303
+ ...files
48304
+ ].sort((left, right)=>Number(preferred(right)) - Number(preferred(left)) || compareCodeUnits(left.relativePath, right.relativePath));
48305
+ const seen = new Set();
48306
+ const kept = [];
48307
+ for (const file of sorted){
48308
+ if (seen.has(file.real)) {
48309
+ continue;
48310
+ }
48311
+ seen.add(file.real);
48312
+ kept.push(file);
48313
+ }
48314
+ return kept.sort((left, right)=>compareCodeUnits(left.relativePath, right.relativePath));
48315
+ }
48316
+ /**
48317
+ * Markdown files under the agent catalog roots, to {@link AGENT_CATALOG_DEPTH}
48318
+ * from each root. Symlinks are followed when they stay inside the repository;
48319
+ * lint drops those paths afterwards.
48320
+ */ async function discoverAgentFiles(targetDir, options) {
48321
+ return discoverMarkdownUnderRoots(targetDir, agentDirectoryRoots(), AGENT_CATALOG_DEPTH, options);
48322
+ }
48323
+ /** Markdown files under the subagent catalog roots, to the agent depth. */ async function discoverSubagentFiles(targetDir, options) {
48324
+ return discoverMarkdownUnderRoots(targetDir, subagentDirectoryRoots(), AGENT_CATALOG_DEPTH, options);
48325
+ }
48326
+ /**
48327
+ * `SKILL.md` files one directory below a skill root. A `SKILL.md` in the root
48328
+ * itself, or nested further, is not a skill file. The walk stops at that
48329
+ * depth by definition, so meeting a skill's own subdirectory, such as
48330
+ * `references/` or `scripts/`, is not a depth limit: nothing below it could
48331
+ * be a skill file.
48332
+ */ async function discoverSkillFiles(targetDir, options) {
48333
+ const walked = await discoverMarkdownUnderRoots(targetDir, skillDirectoryRoots(), SKILL_CATALOG_DEPTH, options, (name)=>name === "SKILL.md");
48334
+ return {
48335
+ ...walked,
48336
+ depthLimitReached: false,
48337
+ files: walked.files.filter((file)=>skillDirectoryRoots().some((root)=>isSkillFileUnderRoot(root, file.relativePath)))
48338
+ };
48339
+ }
48340
+ /**
48341
+ * Reports a directory, entry, or depth cap from a construct walk. The depth
48342
+ * number is that walk's own cap, not the repository root's depth of 10.
48343
+ */ function reportConstructLimits(walk, onDiagnostic, wording) {
48344
+ if (onDiagnostic === undefined) {
48345
+ return;
48346
+ }
48347
+ const sentences = describeDiscoveryLimits({
48348
+ ...walk.directoryLimitReached ? {
48349
+ maxDirectories: walk.limits.maxDirectories
48350
+ } : {},
48351
+ ...walk.depthLimitReached ? {
48352
+ maxDepth: walk.limits.maxDepth
48353
+ } : {},
48354
+ ...walk.entryLimitReached ? {
48355
+ maxEntries: walk.limits.maxEntries
48356
+ } : {}
48357
+ }, wording);
48358
+ if (sentences.length > 0) {
48359
+ onDiagnostic({
48360
+ ruleId: DISCOVERY_LIMIT_REACHED_RULE_ID,
48361
+ message: sentences.join(" ")
48362
+ });
48363
+ }
48364
+ }
48365
+ function isSkillFileUnderRoot(root, relativePath) {
48366
+ const rootSegments = root.split("/").filter((segment)=>segment !== "");
48367
+ const segments = relativePath.split("/").filter((segment)=>segment !== "");
48368
+ return segments.length === rootSegments.length + 2 && segments.at(-1) === "SKILL.md" && rootSegments.every((segment, index)=>segments[index] === segment);
48369
+ }
48370
+ /**
48371
+ * Drops a path that is a symbolic link or sits under one. Skills, agents,
48372
+ * subagents, and hooks keep this filter; the shared walk itself follows
48373
+ * in-repo links so doctor can inventory them.
48374
+ */ async function omitSymlinkedPaths(targetDir, files) {
48375
+ const kept = [];
48376
+ for (const file of files){
48377
+ if (!await containsSymbolicLink(targetDir, file.relativePath)) {
48378
+ kept.push(file);
48379
+ }
48380
+ }
48381
+ return kept;
48382
+ }
48383
+ /**
48384
+ * Catalog paths that exist as regular files and are not symbolic links.
48385
+ * Hooks and MCP configs use this, then apply their own content checks.
48386
+ */ async function discoverExactRegularFiles(targetDir, relativePaths) {
48387
+ const rootReal = await (0,promises_.realpath)((0,external_node_path_.resolve)(targetDir)).catch(()=>null);
48388
+ if (rootReal === null) {
48389
+ return [];
48390
+ }
48391
+ const found = [];
48392
+ for (const relativePath of relativePaths){
48393
+ if (relativePath.split("/").some((segment)=>segment === "..")) {
48394
+ continue;
48395
+ }
48396
+ if (await isRegularFileInsideRoot(targetDir, rootReal, relativePath)) {
48397
+ found.push(relativePath);
48398
+ }
48399
+ }
48400
+ return found;
48401
+ }
48402
+ async function isRegularFileInsideRoot(targetDir, rootReal, relativePath) {
48403
+ if (await containsSymbolicLink(targetDir, relativePath)) {
48404
+ return false;
48405
+ }
48406
+ try {
48407
+ const real = await (0,promises_.realpath)((0,external_node_path_.join)(targetDir, ...relativePath.split("/")));
48408
+ const fromRoot = (0,external_node_path_.relative)(rootReal, real);
48409
+ if (fromRoot.startsWith("..") || fromRoot.startsWith("/") || fromRoot === "") {
48410
+ return false;
48411
+ }
48412
+ const stat = await (0,promises_.lstat)(real);
48413
+ return stat.isFile();
48414
+ } catch {
48415
+ return false;
48416
+ }
48417
+ }
48418
+ function isMissingDirectoryError(error) {
48419
+ return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
48420
+ }
48421
+ /** Lists a directory, treating only one that is gone as empty. */ function emptyWhenMissing(list) {
48422
+ return async (rootReal, path)=>{
48423
+ try {
48424
+ return await list(rootReal, path);
48425
+ } catch (error) {
48426
+ if (isMissingDirectoryError(error)) {
48427
+ return [];
48428
+ }
48429
+ throw error;
48430
+ }
48431
+ };
48432
+ }
48433
+ function hasDoubleDot(name) {
48434
+ return name.includes("..");
48435
+ }
48436
+ function lintWalkOptions(includeFile, skipDirectory, list) {
48437
+ return {
48438
+ includeFile: (name)=>!hasDoubleDot(name) && includeFile(name),
48439
+ skipDirectory: (relativePath)=>hasDoubleDot(relativePath.split("/").at(-1) ?? "") || skipDirectory(relativePath),
48440
+ symbolicLinks: "skip",
48441
+ listDirectory: emptyWhenMissing(list)
48442
+ };
48443
+ }
48444
+ async function discoverMarkdownUnderRoots(targetDir, roots, maxDepth, options, includeFile = (name)=>name.endsWith(".md")) {
48445
+ const files = [];
48446
+ const skippedOutsideRoot = [];
48447
+ let directoryLimitReached = false;
48448
+ let entryLimitReached = false;
48449
+ let depthLimitReached = false;
48450
+ let limits = {
48451
+ maxDirectories: options.maxDirectories ?? (/* inlined export .DEFAULT_MAX_WALK_DIRECTORIES */10000),
48452
+ maxDepth,
48453
+ maxEntries: options.maxEntries ?? (/* inlined export .DEFAULT_MAX_WALK_ENTRIES */200000)
48454
+ };
48455
+ for (const root of roots){
48456
+ if (await isLintSkippedRoot(targetDir, root, options)) {
48457
+ continue;
48458
+ }
48459
+ const walked = await walkRepository(targetDir, constructWalkOptions(root, maxDepth, options, includeFile));
48460
+ files.push(...walked.files);
48461
+ directoryLimitReached = directoryLimitReached || walked.directoryLimitReached;
48462
+ entryLimitReached = entryLimitReached || walked.entryLimitReached;
48463
+ depthLimitReached = depthLimitReached || walked.depthLimitReached;
48464
+ limits = walked.limits;
48465
+ for (const path of walked.skippedOutsideRoot){
48466
+ if (!skippedOutsideRoot.includes(path)) {
48467
+ skippedOutsideRoot.push(path);
48468
+ }
48469
+ }
48470
+ }
48471
+ return {
48472
+ files,
48473
+ directoryLimitReached,
48474
+ entryLimitReached,
48475
+ depthLimitReached,
48476
+ skippedOutsideRoot,
48477
+ limits
48478
+ };
48479
+ }
48480
+ /** A lint walk lists nothing below a catalog root that is itself a link. */ async function isLintSkippedRoot(targetDir, root, options) {
48481
+ return options.purpose === "lint" && await containsSymbolicLink(targetDir, root);
48482
+ }
48483
+ function constructWalkOptions(root, maxDepth, options, includeFile) {
48484
+ const base = instructionWalkOptions({
48485
+ path: root,
48486
+ matchKind: "directory-prefix",
48487
+ includeSubdirectories: true,
48488
+ fileSuffix: undefined
48489
+ }, {
48490
+ ...options,
48491
+ maxDepth
48492
+ });
48493
+ const purposeOptions = options.purpose === "lint" ? lintWalkOptions(includeFile, base.skipDirectory ?? (()=>false), options.listDirectory ?? file_system_utils_listDirectoryWithinRoot) : {
48494
+ includeFile,
48495
+ ...options.listDirectory === undefined ? {} : {
48496
+ listDirectory: options.listDirectory
48497
+ }
48498
+ };
48499
+ return {
48500
+ ...base,
48501
+ includeSubdirectories: true,
48502
+ maxDepth,
48503
+ ...purposeOptions
48504
+ };
48505
+ }
48506
+ async function containsSymbolicLink(targetDir, relativePath) {
48507
+ const segments = relativePath.split("/").filter((segment)=>segment !== "");
48508
+ const walked = [];
48509
+ for (const segment of segments){
48510
+ walked.push(segment);
48511
+ try {
48512
+ const stat = await (0,promises_.lstat)((0,external_node_path_.join)(targetDir, ...walked));
48513
+ if (stat.isSymbolicLink()) {
48514
+ return true;
48515
+ }
48516
+ } catch {
48517
+ return false;
48518
+ }
48519
+ }
48520
+ return false;
48521
+ }
48522
+ function instructionWalkOptions(entry, options) {
48523
+ return {
48524
+ startRelativePath: entry.path,
48525
+ includeFile: (name)=>name.endsWith(entry.fileSuffix ?? ".md"),
48526
+ includeSubdirectories: entry.includeSubdirectories === true,
48527
+ revisit: "refuse-ancestors",
48528
+ maxDepth: options.maxDepth ?? (/* inlined export .DEFAULT_MAX_WALK_DEPTH */10),
48529
+ maxDirectories: options.maxDirectories ?? (/* inlined export .DEFAULT_MAX_WALK_DIRECTORIES */10000),
48530
+ skipDirectoryNames: [
48531
+ ...DEFAULT_SKIPPED_DIRECTORY_NAMES,
48532
+ ...BUILD_OUTPUT_DIRECTORY_NAMES
48533
+ ],
48534
+ skipDirectory: (relativePath)=>isFixtureDirectory(relativePath, options.rootDirectoryName),
48535
+ ...options.maxEntries === undefined ? {} : {
48536
+ maxEntries: options.maxEntries
48537
+ }
48538
+ };
48539
+ }
48540
+
48081
48541
  ;// CONCATENATED MODULE: ../core/src/gateways/instruction-file-discovery-gateway.ts
48082
48542
  /**
48083
48543
  * Gateway for discovering instruction files across multiple formats.
@@ -48089,6 +48549,8 @@ function segmentsOf(relativePath) {
48089
48549
 
48090
48550
 
48091
48551
 
48552
+
48553
+
48092
48554
  /**
48093
48555
  * File system implementation of the instruction file discovery gateway.
48094
48556
  *
@@ -48118,34 +48580,77 @@ function segmentsOf(relativePath) {
48118
48580
  rootReal
48119
48581
  };
48120
48582
  const findings = new DiscoveryFindings();
48583
+ const rootDirectoryName = (0,external_node_path_.basename)((0,external_node_path_.resolve)(targetDir));
48584
+ const locations = await discoverInstructionLocations(targetDir, {
48585
+ rootDirectoryName,
48586
+ maxDirectories: this.maxDirectories,
48587
+ ...this.maxEntries === undefined ? {} : {
48588
+ maxEntries: this.maxEntries
48589
+ }
48590
+ });
48591
+ const catalogWalks = locations.filter((location)=>location.role === "catalog");
48592
+ let catalogIndex = 0;
48593
+ const seen = new Set();
48594
+ const exactFiles = [];
48121
48595
  for (const entry of instructionDiscoveryEntries()){
48122
48596
  const format = entry.instructionFormat;
48123
48597
  if (format == null) {
48124
48598
  continue;
48125
48599
  }
48126
48600
  if (entry.matchKind === "exact") {
48127
- findings.addExact(await discoverExactFile(root, entry.path, format));
48601
+ const exact = await discoverExactFile(root, entry.path, format);
48602
+ findings.addExact(exact);
48603
+ if (exact.real !== undefined) {
48604
+ seen.add(entry.path);
48605
+ exactFiles.push(await instruction_file_discovery_gateway_exactFileIdentity(entry.path, exact.real));
48606
+ }
48607
+ continue;
48608
+ }
48609
+ const walked = catalogWalks[catalogIndex]?.walked;
48610
+ catalogIndex += 1;
48611
+ if (walked === undefined) {
48128
48612
  continue;
48129
48613
  }
48130
- findings.addWalk(await walkRepository(targetDir, this.walkOptions(entry)), (file)=>toDiscoveredFile(root, file.relativePath, {
48614
+ const files = collapseToFirstRealFile(walked.files);
48615
+ findings.addWalk({
48616
+ ...walked,
48617
+ files
48618
+ }, (file)=>toDiscoveredFile(root, file.relativePath, {
48131
48619
  kind: "file",
48132
48620
  real: file.real
48133
48621
  }, format));
48622
+ for (const file of files){
48623
+ seen.add(file.relativePath);
48624
+ }
48625
+ }
48626
+ const nested = locations.find((location)=>location.role === "nested");
48627
+ if (nested !== undefined) {
48628
+ this.recordNestedInstructionFiles(root, seen, exactFiles, findings, nested.walked);
48134
48629
  }
48135
48630
  findings.report(onDiagnostic);
48136
48631
  return findings.files;
48137
48632
  }
48138
- walkOptions(entry) {
48139
- return {
48140
- startRelativePath: entry.path,
48141
- includeFile: (name)=>name.endsWith(entry.fileSuffix ?? ".md"),
48142
- includeSubdirectories: entry.includeSubdirectories === true,
48143
- revisit: "once-per-real-directory",
48144
- maxDirectories: this.maxDirectories,
48145
- ...this.maxEntries === undefined ? {} : {
48146
- maxEntries: this.maxEntries
48633
+ recordNestedInstructionFiles(root, seen, exactFiles, findings, additional) {
48634
+ const walkedPaths = new Set(additional.files.map((file)=>file.relativePath));
48635
+ const candidates = additional.files.filter((file)=>{
48636
+ if (seen.has(file.relativePath) || isExactFileAlias(file, exactFiles, walkedPaths)) {
48637
+ return false;
48147
48638
  }
48148
- };
48639
+ return formatForAdditionalInstructionFile(file.relativePath) !== null;
48640
+ });
48641
+ const files = collapseToFirstRealFile(candidates, (file)=>isAtItsRealPath(root, file));
48642
+ findings.addWalk({
48643
+ ...additional,
48644
+ files,
48645
+ skippedOutsideRoot: additional.skippedOutsideRoot.filter(isAnalyzableNestedInstructionLinkPath),
48646
+ depthLimitReached: false
48647
+ }, (file)=>toDiscoveredFile(root, file.relativePath, {
48648
+ kind: "file",
48649
+ real: file.real
48650
+ }, formatForAdditionalInstructionFile(file.relativePath) ?? "agents-md"));
48651
+ if (additional.depthLimitedDirectories.some(isNestedFilenameAnalyzedBelow)) {
48652
+ findings.noteNestedFilenameDepth(additional.limits.maxDepth);
48653
+ }
48149
48654
  }
48150
48655
  }
48151
48656
  /**
@@ -48156,6 +48661,7 @@ function segmentsOf(relativePath) {
48156
48661
  skippedOutsideRoot = [];
48157
48662
  directoryLimitReached = false;
48158
48663
  depthLimitReached = false;
48664
+ nestedFilenameDepth;
48159
48665
  entryLimitReached = false;
48160
48666
  limits;
48161
48667
  addExact(exact) {
@@ -48163,13 +48669,17 @@ function segmentsOf(relativePath) {
48163
48669
  this.skippedOutsideRoot.push(...exact.skippedOutsideRoot);
48164
48670
  }
48165
48671
  addWalk(walked, toDiscovered) {
48166
- this.limits = walked.limits;
48167
- this.directoryLimitReached ||= walked.directoryLimitReached;
48168
- this.depthLimitReached ||= walked.depthLimitReached;
48169
- this.entryLimitReached ||= walked.entryLimitReached;
48170
- this.skippedOutsideRoot.push(...walked.skippedOutsideRoot);
48672
+ this.recordLimits(walked);
48673
+ for (const path of walked.skippedOutsideRoot){
48674
+ if (!this.skippedOutsideRoot.includes(path)) {
48675
+ this.skippedOutsideRoot.push(path);
48676
+ }
48677
+ }
48171
48678
  this.files.push(...walked.files.map(toDiscovered));
48172
48679
  }
48680
+ noteNestedFilenameDepth(maxDepth) {
48681
+ this.nestedFilenameDepth = maxDepth;
48682
+ }
48173
48683
  report(onDiagnostic) {
48174
48684
  const reasons = this.describeLimits();
48175
48685
  if (reasons.length > 0) {
@@ -48185,11 +48695,39 @@ function segmentsOf(relativePath) {
48185
48695
  });
48186
48696
  }
48187
48697
  }
48698
+ recordLimits(walked) {
48699
+ if (this.limits === undefined) {
48700
+ this.limits = {
48701
+ ...walked.limits
48702
+ };
48703
+ }
48704
+ if (walked.directoryLimitReached) {
48705
+ this.directoryLimitReached = true;
48706
+ this.limits = {
48707
+ ...this.limits,
48708
+ maxDirectories: walked.limits.maxDirectories
48709
+ };
48710
+ }
48711
+ if (walked.depthLimitReached) {
48712
+ this.depthLimitReached = true;
48713
+ this.limits = {
48714
+ ...this.limits,
48715
+ maxDepth: walked.limits.maxDepth
48716
+ };
48717
+ }
48718
+ if (walked.entryLimitReached) {
48719
+ this.entryLimitReached = true;
48720
+ this.limits = {
48721
+ ...this.limits,
48722
+ maxEntries: walked.limits.maxEntries
48723
+ };
48724
+ }
48725
+ }
48188
48726
  describeLimits() {
48189
48727
  if (this.limits === undefined) {
48190
48728
  return [];
48191
48729
  }
48192
- return describeDiscoveryLimits({
48730
+ const sentences = describeDiscoveryLimits({
48193
48731
  ...this.directoryLimitReached ? {
48194
48732
  maxDirectories: this.limits.maxDirectories
48195
48733
  } : {},
@@ -48200,6 +48738,12 @@ function segmentsOf(relativePath) {
48200
48738
  maxEntries: this.limits.maxEntries
48201
48739
  } : {}
48202
48740
  }, DISCOVERY_WORDING);
48741
+ if (this.nestedFilenameDepth !== undefined) {
48742
+ sentences.push(...describeDiscoveryLimits({
48743
+ maxDepth: this.nestedFilenameDepth
48744
+ }, NESTED_FILENAME_DEPTH_WORDING));
48745
+ }
48746
+ return sentences;
48203
48747
  }
48204
48748
  }
48205
48749
  const DISCOVERY_WORDING = {
@@ -48207,6 +48751,62 @@ const DISCOVERY_WORDING = {
48207
48751
  missing: "instruction files",
48208
48752
  consequence: "were not analyzed"
48209
48753
  };
48754
+ const NESTED_FILENAME_DEPTH_WORDING = {
48755
+ subject: "Instruction file discovery",
48756
+ missing: "CLAUDE.md, AGENTS.md, AGENTS.MD, and agents.md files",
48757
+ consequence: "may not have been analyzed"
48758
+ };
48759
+ /**
48760
+ * True when the walked path is the file's own location rather than a path
48761
+ * that reaches it through a symbolic link, so a file also visible through a
48762
+ * catalog-owned link is reported where it lives.
48763
+ */ function isAtItsRealPath(root, file) {
48764
+ return file.real === (0,external_node_path_.join)(root.rootReal, ...file.relativePath.split("/"));
48765
+ }
48766
+ /**
48767
+ * True for a skipped link the nested walk would have analyzed: a nested
48768
+ * instruction filename at the root, or one no other catalog entry owns. A
48769
+ * link such as `.claude/skills/a/AGENTS.md` is owned by its skill directory,
48770
+ * so lint would not analyze it as an instruction even inside the repository.
48771
+ */ function isAnalyzableNestedInstructionLinkPath(relativePath) {
48772
+ const slash = relativePath.lastIndexOf("/");
48773
+ if (slash === -1) {
48774
+ return isNestedInstructionFilename(relativePath);
48775
+ }
48776
+ return formatForAdditionalInstructionFile(relativePath) !== null;
48777
+ }
48778
+ async function instruction_file_discovery_gateway_exactFileIdentity(path, real) {
48779
+ const stats = await (0,promises_.stat)(real).catch(()=>null);
48780
+ return {
48781
+ path,
48782
+ real,
48783
+ identity: stats === null ? null : identityKey(stats)
48784
+ };
48785
+ }
48786
+ function identityKey(identity) {
48787
+ return `${identity.dev}:${identity.ino}`;
48788
+ }
48789
+ /**
48790
+ * True when a nested-walk file is an exact catalog file already discovered
48791
+ * under another name: the same real path (a symbolic link to it or from it),
48792
+ * or the same inode under a name that differs only in case, as a
48793
+ * case-insensitive file system reports `agents.md` for `AGENTS.md`. That
48794
+ * second form is one directory entry only when the walk did not also list the
48795
+ * catalog name: two entries listed by their own names are two files, even
48796
+ * when they are hard links to one inode.
48797
+ */ function isExactFileAlias(file, exactFiles, walkedPaths) {
48798
+ const walkedIdentity = identityKey(file.identity);
48799
+ return exactFiles.some((exact)=>exact.real === file.real || exact.identity === walkedIdentity && exact.path.toLowerCase() === file.relativePath.toLowerCase() && !walkedPaths.has(exact.path));
48800
+ }
48801
+ /**
48802
+ * True when a directory the nested walk did not enter could hold a
48803
+ * CLAUDE.md or AGENTS.md that lint would analyze, so the depth limit may have
48804
+ * hidden one. Under a skill, hook, or agent directory those names belong to
48805
+ * the construct that owns the directory and are never analyzed as
48806
+ * instructions; under `.github/instructions` they are.
48807
+ */ function isNestedFilenameAnalyzedBelow(directory) {
48808
+ return formatForAdditionalInstructionFile(`${directory}/CLAUDE.md`) !== null;
48809
+ }
48210
48810
  /**
48211
48811
  * Discovers one exact-path instruction file, or nothing when it is missing
48212
48812
  * or resolves outside the root, in which case a link out of the repository is
@@ -48218,6 +48818,7 @@ const DISCOVERY_WORDING = {
48218
48818
  files: [
48219
48819
  toDiscoveredFile(root, relativePosixPath, inspected, format)
48220
48820
  ],
48821
+ real: inspected.real,
48221
48822
  skippedOutsideRoot: []
48222
48823
  };
48223
48824
  }
@@ -48667,7 +49268,6 @@ const PackageJsonSchema = schemas_object({
48667
49268
 
48668
49269
 
48669
49270
  /** Maximum skill file size: 1 MB */ const MAX_SKILL_FILE_BYTES = 1_048_576;
48670
- /** Catalog skill roots converted to OS-native relative paths. */ const SKILL_DIRECTORIES = skillDirectoryRoots().map((root)=>(0,external_node_path_.join)(...root.split("/")));
48671
49271
  /** Maximum lock file size: 256 KB */ const MAX_LOCK_FILE_BYTES = 262_144;
48672
49272
  /** Relative path to the skills lock file. */ const SKILLS_LOCK_PATH = "skills-lock.json";
48673
49273
  /** Zod schema for skills-lock.json structure */ const SkillsLockSchema = schemas_object({
@@ -48698,59 +49298,40 @@ const PackageJsonSchema = schemas_object({
48698
49298
  /**
48699
49299
  * File system implementation of the skill lint gateway.
48700
49300
  */ class FileSystemSkillLintGateway {
48701
- async discoverSkills(targetDir) {
48702
- const skills = [];
48703
- for (const relativeDir of SKILL_DIRECTORIES){
48704
- const discovered = await this.discoverSkillsInDir(targetDir, relativeDir);
48705
- skills.push(...discovered);
48706
- }
49301
+ limits;
49302
+ constructor(limits = {}){
49303
+ this.limits = limits;
49304
+ }
49305
+ async discoverSkills(targetDir, onDiagnostic) {
49306
+ const walk = await discoverSkillFiles(targetDir, {
49307
+ rootDirectoryName: (0,external_node_path_.basename)((0,external_node_path_.resolve)(targetDir)),
49308
+ purpose: "lint",
49309
+ ...this.limits
49310
+ });
49311
+ reportConstructLimits(walk, onDiagnostic, {
49312
+ subject: "Skill discovery",
49313
+ missing: "skill files",
49314
+ consequence: "were not analyzed"
49315
+ });
49316
+ const found = await omitSymlinkedPaths(targetDir, walk.files);
49317
+ const skills = found.flatMap((file)=>{
49318
+ const skillName = file.relativePath.split("/").at(-2) ?? "";
49319
+ if (skillName.includes("..") || skillName.includes("/") || skillName.includes("\\")) {
49320
+ return [];
49321
+ }
49322
+ return [
49323
+ {
49324
+ filePath: (0,external_node_path_.join)(targetDir, ...file.relativePath.split("/")),
49325
+ skillName
49326
+ }
49327
+ ];
49328
+ });
48707
49329
  const lockedNames = await readLockedSkillNames(targetDir);
48708
49330
  if (lockedNames.size === 0) {
48709
49331
  return skills;
48710
49332
  }
48711
49333
  return skills.filter((skill)=>!lockedNames.has(skill.skillName));
48712
49334
  }
48713
- async discoverSkillsInDir(targetDir, skillsDir) {
48714
- try {
48715
- if (!await file_system_utils_pathExistsWithinRoot(targetDir, skillsDir)) {
48716
- return [];
48717
- }
48718
- } catch {
48719
- return [];
48720
- }
48721
- let entries;
48722
- try {
48723
- entries = await file_system_utils_listDirectoryWithinRoot(targetDir, skillsDir);
48724
- } catch (error) {
48725
- if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
48726
- return [];
48727
- }
48728
- throw error;
48729
- }
48730
- const skills = [];
48731
- for (const entry of entries){
48732
- if (!entry.isDirectory()) {
48733
- continue;
48734
- }
48735
- if (entry.name.includes("..") || entry.name.includes("/") || entry.name.includes("\\")) {
48736
- continue;
48737
- }
48738
- const skillRelativePath = (0,external_node_path_.join)(skillsDir, entry.name, "SKILL.md");
48739
- let hasSkillFile = false;
48740
- try {
48741
- hasSkillFile = await file_system_utils_pathExistsWithinRoot(targetDir, skillRelativePath);
48742
- } catch {
48743
- hasSkillFile = false;
48744
- }
48745
- if (hasSkillFile) {
48746
- skills.push({
48747
- filePath: (0,external_node_path_.join)(targetDir, skillRelativePath),
48748
- skillName: entry.name
48749
- });
48750
- }
48751
- }
48752
- return skills;
48753
- }
48754
49335
  async readSkillFileContent(filePath) {
48755
49336
  return readFileNoFollow(filePath, MAX_SKILL_FILE_BYTES);
48756
49337
  }
@@ -53054,6 +53635,28 @@ function mcpServerRecords(servers) {
53054
53635
  }));
53055
53636
  }
53056
53637
 
53638
+ ;// CONCATENATED MODULE: ../core/src/entities/mcp-config-schema.ts
53639
+ /**
53640
+ * Baseline shape of an MCP server configuration file. Shared by doctor and
53641
+ * lint so the two cannot disagree on what a valid config is.
53642
+ */
53643
+ /**
53644
+ * Zod schema for a single MCP server declaration.
53645
+ * Baseline shape only: an object whose optional `type`/`transport` fields,
53646
+ * when present, must be non-empty strings. Unknown fields are preserved.
53647
+ */ const McpServerEntrySchema = schemas_object({
53648
+ type: schemas_string().min(1, "type must not be empty").optional(),
53649
+ transport: schemas_string().min(1, "transport must not be empty").optional()
53650
+ }).passthrough();
53651
+ /**
53652
+ * Zod schema for the MCP config file shape: `mcpServers` (Claude Code's
53653
+ * `.mcp.json` convention) and `servers` (VS Code's `.vscode/mcp.json`
53654
+ * convention), each a map of server name to a server declaration.
53655
+ */ const McpConfigSchema = schemas_object({
53656
+ mcpServers: schemas_record(schemas_string(), McpServerEntrySchema).optional(),
53657
+ servers: schemas_record(schemas_string(), McpServerEntrySchema).optional()
53658
+ }).passthrough();
53659
+
53057
53660
  ;// CONCATENATED MODULE: ../core/src/entities/mcp-config-source.ts
53058
53661
  /**
53059
53662
  * Canonical list of MCP server configuration file locations.
@@ -53080,10 +53683,6 @@ function mcpServerRecords(servers) {
53080
53683
 
53081
53684
 
53082
53685
  const MAX_MCP_CONFIG_BYTES = 1_048_576;
53083
- const McpServerEntrySchema = schemas_object({
53084
- type: schemas_string().optional(),
53085
- transport: schemas_string().optional()
53086
- }).passthrough();
53087
53686
  /**
53088
53687
  * Property names that must never be used as MCP server names: assigning
53089
53688
  * them via a plain object key (as zod's `record()` does when reconstructing
@@ -53115,55 +53714,107 @@ function hasReservedServerName(parsed) {
53115
53714
  }
53116
53715
  return false;
53117
53716
  }
53118
- // Accepts both Claude Code's `.mcp.json` convention (`mcpServers`) and VS
53119
- // Code's `.vscode/mcp.json` convention (`servers`) regardless of which
53120
- // source file is being read, since either config file could in practice
53121
- // use either key.
53122
- const McpConfigSchema = schemas_object({
53123
- mcpServers: schemas_record(schemas_string(), McpServerEntrySchema).optional(),
53124
- servers: schemas_record(schemas_string(), McpServerEntrySchema).optional()
53125
- }).passthrough();
53717
+ const mcp_config_MISSING_ERROR_CODES = new Set([
53718
+ "not-found",
53719
+ "ENOENT",
53720
+ "ENOTDIR"
53721
+ ]);
53722
+ function codeOf(value) {
53723
+ if (typeof value !== "object" || value === null || !("code" in value)) {
53724
+ return undefined;
53725
+ }
53726
+ return typeof value.code === "string" ? value.code : undefined;
53727
+ }
53728
+ /**
53729
+ * Classifies a read failure. Only a genuinely missing file (or a missing
53730
+ * parent directory) is silent: `undefined`. Anything else means something
53731
+ * is at the path that doctor could not inventory, so it is a defect. The
53732
+ * reason is chosen from the error's codes only, never its message, which
53733
+ * carries absolute paths.
53734
+ */ function unreadableReason(error) {
53735
+ const code = codeOf(error);
53736
+ if (code !== undefined && mcp_config_MISSING_ERROR_CODES.has(code)) {
53737
+ return undefined;
53738
+ }
53739
+ const causeCode = error instanceof Error ? codeOf(error.cause) : undefined;
53740
+ if (causeCode === "symlink") {
53741
+ return "symlink";
53742
+ }
53743
+ if (causeCode === "too-large") {
53744
+ return "too-large";
53745
+ }
53746
+ return "unreadable";
53747
+ }
53748
+ function mcp_config_defect(source, reason) {
53749
+ return {
53750
+ records: [],
53751
+ defects: [
53752
+ {
53753
+ path: source.relPath,
53754
+ reason
53755
+ }
53756
+ ]
53757
+ };
53758
+ }
53126
53759
  async function readMcpServersFromSource(repoRoot, source) {
53127
53760
  let content;
53128
53761
  try {
53129
53762
  content = await file_system_utils_readTextWithinRoot(repoRoot, source.relPath, MAX_MCP_CONFIG_BYTES);
53130
- } catch {
53131
- return [];
53763
+ } catch (error) {
53764
+ const reason = unreadableReason(error);
53765
+ return reason === undefined ? {
53766
+ records: [],
53767
+ defects: []
53768
+ } : mcp_config_defect(source, reason);
53132
53769
  }
53133
53770
  let raw;
53134
53771
  try {
53135
53772
  raw = JSON.parse(content);
53136
53773
  } catch {
53137
- return [];
53774
+ return mcp_config_defect(source, "invalid-json");
53138
53775
  }
53139
53776
  if (hasReservedServerName(raw)) {
53140
- return [];
53777
+ return mcp_config_defect(source, "reserved-name");
53141
53778
  }
53142
53779
  const result = McpConfigSchema.safeParse(raw);
53143
53780
  if (!result.success) {
53144
- return [];
53781
+ return mcp_config_defect(source, "invalid-schema");
53145
53782
  }
53146
53783
  const servers = {
53147
53784
  ...result.data.mcpServers ?? {},
53148
53785
  ...result.data.servers ?? {}
53149
53786
  };
53150
- return Object.entries(servers).map(([serverName, entry])=>({
53151
- serverName,
53152
- harness: source.harnessHint,
53153
- path: source.relPath,
53154
- ...entry.transport !== undefined ? {
53155
- transport: entry.transport
53156
- } : entry.type !== undefined ? {
53157
- transport: entry.type
53158
- } : {}
53159
- }));
53787
+ return {
53788
+ records: Object.entries(servers).map(([serverName, entry])=>({
53789
+ serverName,
53790
+ harness: source.harnessHint,
53791
+ path: source.relPath,
53792
+ ...entry.transport !== undefined ? {
53793
+ transport: entry.transport
53794
+ } : entry.type !== undefined ? {
53795
+ transport: entry.type
53796
+ } : {}
53797
+ })),
53798
+ defects: []
53799
+ };
53160
53800
  }
53161
- async function enumerateMcpServers(repoRoot) {
53801
+ async function inspectMcpConfigs(repoRoot) {
53162
53802
  const records = [];
53803
+ const defects = [];
53163
53804
  for (const source of MCP_CONFIG_SOURCES){
53164
- records.push(...await readMcpServersFromSource(repoRoot, source));
53805
+ const read = await readMcpServersFromSource(repoRoot, source);
53806
+ records.push(...read.records);
53807
+ defects.push(...read.defects);
53165
53808
  }
53166
- return records;
53809
+ return {
53810
+ records,
53811
+ defects
53812
+ };
53813
+ }
53814
+ async function enumerateMcpServers(repoRoot) {
53815
+ return [
53816
+ ...(await inspectMcpConfigs(repoRoot)).records
53817
+ ];
53167
53818
  }
53168
53819
 
53169
53820
  ;// CONCATENATED MODULE: ../core/src/gateways/import-target-classifier.ts
@@ -53334,6 +53985,8 @@ async function enumerateMcpServers(repoRoot) {
53334
53985
 
53335
53986
 
53336
53987
 
53988
+
53989
+
53337
53990
  const SCANNABLE_EXTENSIONS = new Set([
53338
53991
  ".md",
53339
53992
  ".mdc",
@@ -53346,34 +53999,20 @@ const SCANNABLE_EXTENSIONS = new Set([
53346
53999
  const SCANNABLE_EXTENSIONLESS = new Set([
53347
54000
  ".cursorrules"
53348
54001
  ]);
53349
- /** Doctor also skips build output, which the shared walk does not. */ const DOCTOR_SKIPPED_DIRECTORY_NAMES = [
54002
+ /** Doctor also skips build output, which the shared walk's default list does not. */ const DOCTOR_SKIPPED_DIRECTORY_NAMES = [
53350
54003
  ...DEFAULT_SKIPPED_DIRECTORY_NAMES,
53351
- "dist"
54004
+ ...BUILD_OUTPUT_DIRECTORY_NAMES
53352
54005
  ];
53353
- /**
53354
- * True when `relativePath` is a fixture directory the walk met below the
53355
- * scan root. The root itself is not passed here. When the relative path has
53356
- * no parent segment, `rootDirectoryName` is that parent, so a scan started
53357
- * in a directory named `tests` still skips its `fixtures` child.
53358
- *
53359
- * `tests/fixtures` is the parent and child, not every directory named
53360
- * `fixtures`, so `src/fixtures` stays in the scan. `__fixtures__` and
53361
- * `testdata` are names at any depth.
53362
- */ function isFixtureDirectory(relativePath, rootDirectoryName) {
53363
- const segments = relativePath.split("/");
53364
- const name = segments[segments.length - 1];
53365
- if (name === "__fixtures__" || name === "testdata") {
53366
- return true;
53367
- }
53368
- const parent = segments.length >= 2 ? segments[segments.length - 2] : rootDirectoryName;
53369
- return parent === "tests" && name === "fixtures";
53370
- }
53371
54006
  function isScannableFile(name) {
53372
54007
  if (SCANNABLE_EXTENSIONLESS.has(name)) return true;
53373
54008
  const dot = name.lastIndexOf(".");
53374
54009
  if (dot === -1) return false;
53375
54010
  return SCANNABLE_EXTENSIONS.has(name.slice(dot).toLowerCase());
53376
54011
  }
54012
+ function parentSegmentCount(relativePath) {
54013
+ const segments = relativePath.split("/").filter((segment)=>segment !== "");
54014
+ return Math.max(0, segments.length - 1);
54015
+ }
53377
54016
  function toSourceFile(repoRoot, rootReal, file) {
53378
54017
  return {
53379
54018
  absPath: (0,external_node_path_.resolve)(repoRoot, file.relativePath),
@@ -53383,6 +54022,19 @@ function toSourceFile(repoRoot, rootReal, file) {
53383
54022
  identity: file.identity
53384
54023
  };
53385
54024
  }
54025
+ /**
54026
+ * Adds the links a catalog walk skipped, leaving out a path already listed
54027
+ * and a path below one already listed. A catalog walk that starts below a
54028
+ * link out of the repository reports its own start directory, which is not
54029
+ * a link; the link itself is already in the list.
54030
+ */ function appendSkippedLinks(skipped, additions) {
54031
+ for (const path of additions){
54032
+ const covered = skipped.some((listed)=>path === listed || path.startsWith(`${listed}/`));
54033
+ if (!covered) {
54034
+ skipped.push(path);
54035
+ }
54036
+ }
54037
+ }
53386
54038
  /**
53387
54039
  * Scans a repository into an inventory using the shared walk.
53388
54040
  *
@@ -53408,7 +54060,55 @@ function toSourceFile(repoRoot, rootReal, file) {
53408
54060
  maxEntries: options.maxEntries
53409
54061
  }
53410
54062
  });
53411
- const files = walked.files.map((file)=>toSourceFile(absRoot, rootReal, file));
54063
+ const instructionWalks = await discoverInstructionLocations(absRoot, {
54064
+ rootDirectoryName: (0,external_node_path_.basename)(absRoot),
54065
+ maxDirectories,
54066
+ includeNestedWalk: false,
54067
+ ...options.maxEntries === undefined ? {} : {
54068
+ maxEntries: options.maxEntries
54069
+ }
54070
+ });
54071
+ const knownPaths = new Set(walked.files.map((file)=>file.relativePath));
54072
+ const catalogLimits = {
54073
+ rootDirectoryName: (0,external_node_path_.basename)(absRoot),
54074
+ maxDirectories,
54075
+ ...options.maxEntries === undefined ? {} : {
54076
+ maxEntries: options.maxEntries
54077
+ }
54078
+ };
54079
+ const agentWalk = await discoverAgentFiles(absRoot, catalogLimits);
54080
+ const subagentWalk = await discoverSubagentFiles(absRoot, catalogLimits);
54081
+ const deepConstructFiles = [
54082
+ ...agentWalk.files,
54083
+ ...subagentWalk.files
54084
+ ];
54085
+ const beyondRootDepth = [
54086
+ ...instructionWalks.filter((location)=>location.role === "catalog").flatMap((location)=>location.walked.files),
54087
+ ...deepConstructFiles
54088
+ ].filter((file)=>!knownPaths.has(file.relativePath) && parentSegmentCount(file.relativePath) > (/* inlined export .DEFAULT_MAX_WALK_DEPTH */10));
54089
+ // Files the root walk cannot reach are appended after its list, in the
54090
+ // catalog walk's order. They are not interleaved into that walk's order.
54091
+ const files = [
54092
+ ...walked.files,
54093
+ ...beyondRootDepth
54094
+ ].map((file)=>toSourceFile(absRoot, rootReal, file));
54095
+ const catalogWalks = instructionWalks.filter((location)=>location.role === "catalog");
54096
+ const depthLimitReached = walked.depthLimitReached || catalogWalks.some((location)=>location.walked.depthLimitReached);
54097
+ const constructWalks = [
54098
+ agentWalk,
54099
+ subagentWalk
54100
+ ];
54101
+ const directoryLimitReached = walked.directoryLimitReached || catalogWalks.some((location)=>location.walked.directoryLimitReached) || constructWalks.some((walk)=>walk.directoryLimitReached);
54102
+ const entryLimitReached = walked.entryLimitReached || catalogWalks.some((location)=>location.walked.entryLimitReached) || constructWalks.some((walk)=>walk.entryLimitReached);
54103
+ const skippedOutsideRoot = [
54104
+ ...walked.skippedOutsideRoot
54105
+ ];
54106
+ for (const location of catalogWalks){
54107
+ appendSkippedLinks(skippedOutsideRoot, location.walked.skippedOutsideRoot);
54108
+ }
54109
+ for (const walk of constructWalks){
54110
+ appendSkippedLinks(skippedOutsideRoot, walk.skippedOutsideRoot);
54111
+ }
53412
54112
  const edgeContext = {
53413
54113
  repoRoot: absRoot,
53414
54114
  rootReal,
@@ -53418,29 +54118,32 @@ function toSourceFile(repoRoot, rootReal, file) {
53418
54118
  })
53419
54119
  };
53420
54120
  const { records: fileRecords, filesOverImportLimit, unreadFiles } = await buildFileInventory(files, edgeContext, options.readContent);
53421
- const mcpServers = await enumerateMcpServers(absRoot);
54121
+ const mcpConfigs = await inspectMcpConfigs(absRoot);
53422
54122
  return {
53423
54123
  records: [
53424
54124
  ...markReferencedRecords(fileRecords),
53425
- ...mcpServerRecords(mcpServers)
54125
+ ...mcpServerRecords(mcpConfigs.records)
53426
54126
  ],
53427
- ...walked.directoryLimitReached ? {
54127
+ ...mcpConfigs.defects.length > 0 ? {
54128
+ mcpConfigDefects: mcpConfigs.defects
54129
+ } : {},
54130
+ ...directoryLimitReached ? {
53428
54131
  directoryLimit: {
53429
54132
  maxDirectories: walked.limits.maxDirectories
53430
54133
  }
53431
54134
  } : {},
53432
- ...walked.depthLimitReached ? {
54135
+ ...depthLimitReached ? {
53433
54136
  depthLimit: {
53434
54137
  maxDepth: walked.limits.maxDepth
53435
54138
  }
53436
54139
  } : {},
53437
- ...walked.entryLimitReached ? {
54140
+ ...entryLimitReached ? {
53438
54141
  entryLimit: {
53439
54142
  maxEntries: walked.limits.maxEntries
53440
54143
  }
53441
54144
  } : {},
53442
- ...walked.skippedOutsideRoot.length > 0 ? {
53443
- skippedOutsideRoot: walked.skippedOutsideRoot
54145
+ ...skippedOutsideRoot.length > 0 ? {
54146
+ skippedOutsideRoot
53444
54147
  } : {},
53445
54148
  ...filesOverImportLimit.length > 0 ? {
53446
54149
  importLimit: {
@@ -54272,6 +54975,36 @@ function evaluate(criteria, ctx) {
54272
54975
  return findings;
54273
54976
  }
54274
54977
 
54978
+ ;// CONCATENATED MODULE: ../doctor/src/use-cases/mcp-config-finding.ts
54979
+ /**
54980
+ * Constant, content-free text per cause. Never built from the file's content
54981
+ * or an absolute path, so a finding cannot leak either.
54982
+ */ const REASON_TEXT = {
54983
+ "invalid-json": "is not valid JSON",
54984
+ "invalid-schema": "does not match the MCP config schema",
54985
+ "reserved-name": "declares a reserved server name (__proto__, constructor, or prototype)",
54986
+ "too-large": "is larger than the 1 MiB size limit",
54987
+ symlink: "is a symbolic link, which doctor does not follow",
54988
+ unreadable: "exists but could not be read as a regular file"
54989
+ };
54990
+ /**
54991
+ * One high defect per malformed MCP config. The target is the repo-relative
54992
+ * path, so a longer path does not satisfy a shorter one. A missing file is
54993
+ * not a defect, and no server record is invented for a file that did not parse.
54994
+ */ function mcpConfigFindings(defects) {
54995
+ return defects.map((defect)=>({
54996
+ id: `malformed-mcp-config:${defect.path}`,
54997
+ criterionId: "malformed-mcp-config",
54998
+ targetId: defect.path,
54999
+ severity: "high",
55000
+ category: "malformed-reference",
55001
+ classification: "defect",
55002
+ intentGated: false,
55003
+ assumedIntent: false,
55004
+ description: `The MCP config at ${defect.path} is malformed: it ${REASON_TEXT[defect.reason]}.`
55005
+ }));
55006
+ }
55007
+
54275
55008
  ;// CONCATENATED MODULE: ../doctor/src/use-cases/scan-notice-findings.ts
54276
55009
 
54277
55010
 
@@ -54315,6 +55048,7 @@ function evaluate(criteria, ctx) {
54315
55048
 
54316
55049
 
54317
55050
 
55051
+
54318
55052
  async function loadIntent(repoPath, records, classification, ports) {
54319
55053
  const loaded = await ports.readIntent(repoPath);
54320
55054
  if (loaded.report.status !== "absent" || !ports.elicitIntent) {
@@ -54341,7 +55075,7 @@ async function loadIntent(repoPath, records, classification, ports) {
54341
55075
  this.scanWarnings = scanWarnings;
54342
55076
  }
54343
55077
  }
54344
- async function completeRun(input, ports, base) {
55078
+ async function completeRun(input, ports, base, mcpConfigDefects) {
54345
55079
  const { records, classification } = base;
54346
55080
  const snapshotRef = await ports.loadSnapshotRef(input.repoPath);
54347
55081
  const withSnapshot = {
@@ -54350,25 +55084,29 @@ async function completeRun(input, ports, base) {
54350
55084
  snapshotRef
54351
55085
  } : {}
54352
55086
  };
55087
+ const configFindings = mcpConfigFindings(mcpConfigDefects);
54353
55088
  if (input.summaryOnly) {
54354
55089
  return {
54355
55090
  kind: "summary",
54356
55091
  ...withSnapshot
54357
55092
  };
54358
55093
  }
54359
- if (classification.archetype === "none") {
55094
+ if (classification.archetype === "none" && configFindings.length === 0) {
54360
55095
  return {
54361
55096
  kind: "no-constructs",
54362
55097
  ...withSnapshot
54363
55098
  };
54364
55099
  }
54365
55100
  const loaded = await loadIntent(input.repoPath, records, classification, ports);
54366
- const findings = evaluate(CRITERIA, {
54367
- records,
54368
- classification,
54369
- intent: loaded.intent,
54370
- intentLoadStatus: loaded.report.status
54371
- });
55101
+ const findings = [
55102
+ ...evaluate(CRITERIA, {
55103
+ records,
55104
+ classification,
55105
+ intent: loaded.intent,
55106
+ intentLoadStatus: loaded.report.status
55107
+ }),
55108
+ ...configFindings
55109
+ ];
54372
55110
  return {
54373
55111
  kind: "evaluated",
54374
55112
  ...withSnapshot,
@@ -54389,7 +55127,7 @@ async function runDoctor(input, ports) {
54389
55127
  ]
54390
55128
  };
54391
55129
  try {
54392
- return await completeRun(input, ports, base);
55130
+ return await completeRun(input, ports, base, scan.mcpConfigDefects ?? []);
54393
55131
  } catch (error) {
54394
55132
  throw new DoctorRunFailure(error, base.scanWarnings);
54395
55133
  }
@@ -56023,82 +56761,6 @@ function diagnosticLines(output) {
56023
56761
  }
56024
56762
  }
56025
56763
 
56026
- ;// CONCATENATED MODULE: ../core/src/gateways/markdown-file-discovery.ts
56027
- /**
56028
- * Shared recursive markdown-file discovery for lint gateways that scan a
56029
- * catalog root directory for `.md` files (agents, subagents). Guards
56030
- * against path traversal and symlink escapes, and caps recursion depth to
56031
- * avoid stack exhaustion on pathologically deep directory trees.
56032
- */
56033
-
56034
- /** Maximum subdirectory nesting the walk will descend into. */ const MAX_WALK_DEPTH = 32;
56035
- function markdown_file_discovery_isUnsafeEntryName(name) {
56036
- return name.includes("..") || name.includes("/") || name.includes("\\");
56037
- }
56038
- function isWithinResolvedRoot(resolvedRootDir, absoluteEntryPath) {
56039
- const resolvedPath = (0,external_node_path_.resolve)(absoluteEntryPath);
56040
- const rel = (0,external_node_path_.relative)(resolvedRootDir, resolvedPath);
56041
- return !rel.startsWith("..") && !rel.startsWith(external_node_path_.sep);
56042
- }
56043
- async function rootExists(targetDir, rootDir) {
56044
- try {
56045
- return await file_system_utils_pathExistsWithinRoot(targetDir, rootDir);
56046
- } catch {
56047
- return false;
56048
- }
56049
- }
56050
- function isDiscoverableMarkdownFile(entry, name) {
56051
- return entry.isFile() && name.endsWith(".md");
56052
- }
56053
- async function collectEntryFiles(targetDir, resolvedRootDir, dir, depth, entry, deriveName) {
56054
- const name = entry.name;
56055
- if (markdown_file_discovery_isUnsafeEntryName(name)) {
56056
- return [];
56057
- }
56058
- const entryPath = (0,external_node_path_.join)(dir, name);
56059
- const absoluteEntryPath = (0,external_node_path_.join)(targetDir, entryPath);
56060
- if (!isWithinResolvedRoot(resolvedRootDir, absoluteEntryPath)) {
56061
- return [];
56062
- }
56063
- if (entry.isSymbolicLink()) {
56064
- return [];
56065
- }
56066
- if (entry.isDirectory()) {
56067
- return walkMarkdownFiles(targetDir, resolvedRootDir, entryPath, depth + 1, deriveName);
56068
- }
56069
- if (!isDiscoverableMarkdownFile(entry, name)) {
56070
- return [];
56071
- }
56072
- return [
56073
- {
56074
- filePath: absoluteEntryPath,
56075
- name: deriveName(name)
56076
- }
56077
- ];
56078
- }
56079
- async function walkMarkdownFiles(targetDir, resolvedRootDir, dir, depth, deriveName) {
56080
- if (depth > MAX_WALK_DEPTH) {
56081
- return [];
56082
- }
56083
- const entries = await file_system_utils_listDirectoryWithinRoot(targetDir, dir);
56084
- const discovered = [];
56085
- for (const entry of entries){
56086
- const files = await collectEntryFiles(targetDir, resolvedRootDir, dir, depth, entry, deriveName);
56087
- discovered.push(...files);
56088
- }
56089
- return discovered;
56090
- }
56091
- /**
56092
- * Recursively discovers `.md` files under `rootDir` (relative to
56093
- * `targetDir`). `deriveName` maps a filename to the construct name callers
56094
- * use to identify the file (e.g. stripping `.md` or `.agent.md`).
56095
- */ async function discoverMarkdownFiles(targetDir, rootDir, deriveName) {
56096
- if (!await rootExists(targetDir, rootDir)) {
56097
- return [];
56098
- }
56099
- return walkMarkdownFiles(targetDir, (0,external_node_path_.resolve)(targetDir, rootDir), rootDir, 0, deriveName);
56100
- }
56101
-
56102
56764
  ;// CONCATENATED MODULE: ../core/src/gateways/agent-lint-gateway.ts
56103
56765
  /**
56104
56766
  * Gateway for agent lint file system operations.
@@ -56107,26 +56769,33 @@ async function walkMarkdownFiles(targetDir, resolvedRootDir, dir, depth, deriveN
56107
56769
 
56108
56770
 
56109
56771
 
56110
-
56111
56772
  /** Maximum agent file size: 1 MB */ const MAX_AGENT_FILE_BYTES = 1_048_576;
56112
- /** Catalog agent roots converted to OS-native relative paths. */ const AGENT_DIRECTORIES = agentDirectoryRoots().map((root)=>(0,external_node_path_.join)(...root.split("/")));
56113
56773
  /**
56114
56774
  * File system implementation of the agent lint gateway.
56115
56775
  */ class FileSystemAgentLintGateway {
56116
- async discoverAgents(targetDir) {
56117
- const agents = [];
56118
- for (const agentsDir of AGENT_DIRECTORIES){
56119
- const discovered = await this.discoverAgentsInDir(targetDir, agentsDir);
56120
- agents.push(...discovered);
56121
- }
56122
- return agents;
56776
+ limits;
56777
+ constructor(limits = {}){
56778
+ this.limits = limits;
56123
56779
  }
56124
- async discoverAgentsInDir(targetDir, agentsDir) {
56125
- const files = await discoverMarkdownFiles(targetDir, agentsDir, (name)=>name.endsWith(".agent.md") ? (0,external_node_path_.basename)(name, ".agent.md") : (0,external_node_path_.basename)(name, ".md"));
56126
- return files.map((file)=>({
56127
- filePath: file.filePath,
56128
- agentName: file.name
56129
- }));
56780
+ async discoverAgents(targetDir, onDiagnostic) {
56781
+ const walk = await discoverAgentFiles(targetDir, {
56782
+ rootDirectoryName: (0,external_node_path_.basename)((0,external_node_path_.resolve)(targetDir)),
56783
+ purpose: "lint",
56784
+ ...this.limits
56785
+ });
56786
+ reportConstructLimits(walk, onDiagnostic, {
56787
+ subject: "Agent discovery",
56788
+ missing: "agent files",
56789
+ consequence: "were not analyzed"
56790
+ });
56791
+ const found = collapseToFirstRealFile(await omitSymlinkedPaths(targetDir, walk.files));
56792
+ return found.map((file)=>{
56793
+ const name = file.relativePath.split("/").at(-1) ?? "";
56794
+ return {
56795
+ filePath: (0,external_node_path_.join)(targetDir, ...file.relativePath.split("/")),
56796
+ agentName: name.endsWith(".agent.md") ? (0,external_node_path_.basename)(name, ".agent.md") : (0,external_node_path_.basename)(name, ".md")
56797
+ };
56798
+ });
56130
56799
  }
56131
56800
  async readAgentFileContent(filePath) {
56132
56801
  return readFileNoFollow(filePath, MAX_AGENT_FILE_BYTES);
@@ -56294,11 +56963,13 @@ function collectResolvedImports(repoRoot, edges) {
56294
56963
  */
56295
56964
 
56296
56965
 
56966
+
56297
56967
  /** Maximum hook config file size: 1 MB */ const MAX_CONFIG_FILE_BYTES = 1_048_576;
56298
56968
  /** Matches the Copilot hook key `"preToolUse":` to detect hook section presence */ const COPILOT_HOOK_PATTERN = /"preToolUse"\s*:/;
56299
56969
  /** Matches the Claude hook key `"hooks":` to detect hook section presence */ const CLAUDE_HOOK_PATTERN = /"hooks"\s*:/;
56300
56970
  /** Catalog hook config paths converted to OS-native relative paths. */ const HOOK_CONFIG_PATHS = hookConfigPaths().map((entry)=>({
56301
56971
  relativePath: (0,external_node_path_.join)(...entry.relativePath.split("/")),
56972
+ posixPath: entry.relativePath,
56302
56973
  platform: entry.platform
56303
56974
  }));
56304
56975
  /**
@@ -56318,38 +56989,64 @@ function collectResolvedImports(repoRoot, edges) {
56318
56989
  const hooks = parsed.hooks;
56319
56990
  return hooks !== null && typeof hooks === "object" && !Array.isArray(hooks);
56320
56991
  }
56992
+ /** Error messages that mean a hook config path must be left out, not fail the run. */ const UNSAFE_PATH_MESSAGE_PREFIXES = [
56993
+ "Resolved path is outside target directory:",
56994
+ "Path contains symbolic link:"
56995
+ ];
56996
+ function isMissingPathError(error) {
56997
+ return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
56998
+ }
56999
+ function isUnsafePathError(error) {
57000
+ return error instanceof Error && UNSAFE_PATH_MESSAGE_PREFIXES.some((prefix)=>error.message.startsWith(prefix));
57001
+ }
57002
+ function isRejectedFileError(error) {
57003
+ return error instanceof Error && (error.message.startsWith("Symlinks are not allowed") || error.message.includes("exceeds size limit"));
57004
+ }
57005
+ /**
57006
+ * Resolves a catalog hook config path inside the target directory.
57007
+ * Returns undefined when the path is missing, leaves the directory, or
57008
+ * crosses a symbolic link. Any other failure is rethrown.
57009
+ */ async function resolveHookConfigPath(targetDir, relativePath) {
57010
+ try {
57011
+ return await file_system_utils_resolveSafePath(targetDir, relativePath);
57012
+ } catch (error) {
57013
+ if (isMissingPathError(error) || isUnsafePathError(error)) {
57014
+ return undefined;
57015
+ }
57016
+ throw error;
57017
+ }
57018
+ }
57019
+ /**
57020
+ * Reads a hook config file without following symbolic links.
57021
+ * Returns undefined when the file is missing, is a symlink, or is too large.
57022
+ * Any other failure is rethrown.
57023
+ */ async function readHookConfigContent(safePath) {
57024
+ try {
57025
+ return await readFileNoFollow(safePath, MAX_CONFIG_FILE_BYTES);
57026
+ } catch (error) {
57027
+ if (isMissingPathError(error) || isRejectedFileError(error)) {
57028
+ return undefined;
57029
+ }
57030
+ throw error;
57031
+ }
57032
+ }
56321
57033
  /**
56322
57034
  * File system implementation of the hook config lint gateway.
56323
57035
  */ class FileSystemHookConfigGateway {
56324
57036
  async discoverHookFiles(targetDir) {
56325
57037
  const discovered = [];
57038
+ const present = new Set(await discoverExactRegularFiles(targetDir, HOOK_CONFIG_PATHS.map((config)=>config.posixPath)));
56326
57039
  for (const config of HOOK_CONFIG_PATHS){
56327
- let safePath;
56328
- try {
56329
- safePath = await file_system_utils_resolveSafePath(targetDir, config.relativePath);
56330
- } catch (error) {
56331
- if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
56332
- continue;
56333
- }
56334
- if (error instanceof Error && (error.message.startsWith("Resolved path is outside target directory:") || error.message.startsWith("Path contains symbolic link:"))) {
56335
- continue;
56336
- }
56337
- throw error;
57040
+ if (!present.has(config.posixPath)) {
57041
+ continue;
56338
57042
  }
56339
- let content;
56340
- try {
56341
- content = await readFileNoFollow(safePath, MAX_CONFIG_FILE_BYTES);
56342
- } catch (error) {
56343
- if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
56344
- continue;
56345
- }
56346
- if (error instanceof Error && error.message.startsWith("Symlinks are not allowed")) {
56347
- continue;
56348
- }
56349
- if (error instanceof Error && error.message.includes("exceeds size limit")) {
56350
- continue;
56351
- }
56352
- throw error;
57043
+ const safePath = await resolveHookConfigPath(targetDir, config.relativePath);
57044
+ if (safePath === undefined) {
57045
+ continue;
57046
+ }
57047
+ const content = await readHookConfigContent(safePath);
57048
+ if (content === undefined) {
57049
+ continue;
56353
57050
  }
56354
57051
  if (this.mayContainHookSection(content, config.platform)) {
56355
57052
  discovered.push({
@@ -77902,57 +78599,19 @@ const HEADING_PATTERN_DESCRIPTIONS = new Map(Object.entries(HEADING_PATTERN_DESC
77902
78599
  */
77903
78600
 
77904
78601
 
78602
+
77905
78603
  /** Maximum MCP config file size: 1 MB */ const MAX_MCP_CONFIG_FILE_BYTES = 1_048_576;
77906
- /** Catalog MCP config paths converted to OS-native relative paths. */ const MCP_CONFIG_RELATIVE_PATHS = MCP_CONFIG_SOURCES.map((source)=>(0,external_node_path_.join)(...source.relPath.split("/")));
77907
- const SKIPPABLE_PATH_ERROR_PREFIXES = [
77908
- "Resolved path is outside target directory:",
77909
- "Path contains symbolic link:"
77910
- ];
77911
- function isSkippablePathError(error) {
77912
- if (!(error instanceof Error)) {
77913
- return false;
77914
- }
77915
- return SKIPPABLE_PATH_ERROR_PREFIXES.some((prefix)=>error.message.startsWith(prefix));
77916
- }
77917
- async function pathExistsSafely(targetDir, relativePath) {
77918
- try {
77919
- return await file_system_utils_pathExistsWithinRoot(targetDir, relativePath);
77920
- } catch {
77921
- return false;
77922
- }
77923
- }
77924
- async function resolveConfigPathOrNull(targetDir, relativePath) {
77925
- try {
77926
- return await file_system_utils_resolveSafePath(targetDir, relativePath);
77927
- } catch (error) {
77928
- if (isSkippablePathError(error)) {
77929
- return null;
77930
- }
77931
- throw error;
77932
- }
77933
- }
77934
- /**
77935
- * Resolves a config path within the target directory, returning null when the
77936
- * path is missing or escapes the root via traversal/symlink.
77937
- */ async function tryResolveConfigPath(targetDir, relativePath) {
77938
- if (!await pathExistsSafely(targetDir, relativePath)) {
77939
- return null;
77940
- }
77941
- return resolveConfigPathOrNull(targetDir, relativePath);
77942
- }
77943
78604
  /**
77944
78605
  * File system implementation of the MCP server lint gateway.
77945
78606
  */ class FileSystemMcpServersLintGateway {
77946
78607
  async discoverMcpConfigFiles(targetDir) {
77947
78608
  const discovered = [];
77948
- for (const relativePath of MCP_CONFIG_RELATIVE_PATHS){
77949
- const safePath = await tryResolveConfigPath(targetDir, relativePath);
77950
- if (safePath === null) {
77951
- continue;
77952
- }
78609
+ const posixPaths = MCP_CONFIG_SOURCES.map((source)=>source.relPath);
78610
+ const present = await discoverExactRegularFiles(targetDir, posixPaths);
78611
+ for (const relativePath of present){
77953
78612
  discovered.push({
77954
- filePath: safePath,
77955
- relativePath
78613
+ filePath: (0,external_node_path_.join)(targetDir, ...relativePath.split("/")),
78614
+ relativePath: (0,external_node_path_.join)(...relativePath.split("/"))
77956
78615
  });
77957
78616
  }
77958
78617
  return discovered;
@@ -77975,26 +78634,33 @@ async function resolveConfigPathOrNull(targetDir, relativePath) {
77975
78634
 
77976
78635
 
77977
78636
 
77978
-
77979
78637
  /** Maximum subagent file size: 1 MB */ const MAX_SUBAGENT_FILE_BYTES = 1_048_576;
77980
- /** Catalog subagent roots converted to OS-native relative paths. */ const SUBAGENT_DIRECTORIES = subagentDirectoryRoots().map((root)=>(0,external_node_path_.join)(...root.split("/")));
77981
78638
  /**
77982
78639
  * File system implementation of the subagent lint gateway.
77983
78640
  */ class FileSystemSubagentLintGateway {
77984
- async discoverSubagents(targetDir) {
77985
- const subagents = [];
77986
- for (const subagentsDir of SUBAGENT_DIRECTORIES){
77987
- const discovered = await this.discoverSubagentsInDir(targetDir, subagentsDir);
77988
- subagents.push(...discovered);
77989
- }
77990
- return subagents;
78641
+ limits;
78642
+ constructor(limits = {}){
78643
+ this.limits = limits;
77991
78644
  }
77992
- async discoverSubagentsInDir(targetDir, subagentsDir) {
77993
- const files = await discoverMarkdownFiles(targetDir, subagentsDir, (name)=>(0,external_node_path_.basename)(name, ".md"));
77994
- return files.map((file)=>({
77995
- filePath: file.filePath,
77996
- subagentName: file.name
77997
- }));
78645
+ async discoverSubagents(targetDir, onDiagnostic) {
78646
+ const walk = await discoverSubagentFiles(targetDir, {
78647
+ rootDirectoryName: (0,external_node_path_.basename)((0,external_node_path_.resolve)(targetDir)),
78648
+ purpose: "lint",
78649
+ ...this.limits
78650
+ });
78651
+ reportConstructLimits(walk, onDiagnostic, {
78652
+ subject: "Subagent discovery",
78653
+ missing: "subagent files",
78654
+ consequence: "were not analyzed"
78655
+ });
78656
+ const found = collapseToFirstRealFile(await omitSymlinkedPaths(targetDir, walk.files));
78657
+ return found.map((file)=>{
78658
+ const name = file.relativePath.split("/").at(-1) ?? "";
78659
+ return {
78660
+ filePath: (0,external_node_path_.join)(targetDir, ...file.relativePath.split("/")),
78661
+ subagentName: (0,external_node_path_.basename)(name, ".md")
78662
+ };
78663
+ });
77998
78664
  }
77999
78665
  async readSubagentFileContent(filePath) {
78000
78666
  return readFileNoFollow(filePath, MAX_SUBAGENT_FILE_BYTES);
@@ -78184,7 +78850,12 @@ async function resolveConfigPathOrNull(targetDir, relativePath) {
78184
78850
  if (!input.targetDir) {
78185
78851
  throw new Error("Target directory is required");
78186
78852
  }
78187
- const agents = await this.gateway.discoverAgents(input.targetDir);
78853
+ const discoveryDiagnostics = [];
78854
+ const agents = await this.gateway.discoverAgents(input.targetDir, (diagnostic)=>discoveryDiagnostics.push({
78855
+ filePath: input.targetDir,
78856
+ ruleId: diagnostic.ruleId,
78857
+ message: diagnostic.message
78858
+ }));
78188
78859
  const results = [];
78189
78860
  for (const agent of agents){
78190
78861
  const content = await this.gateway.readAgentFileContent(agent.filePath);
@@ -78197,7 +78868,10 @@ async function resolveConfigPathOrNull(targetDir, relativePath) {
78197
78868
  results,
78198
78869
  totalAgents: agents.length,
78199
78870
  totalErrors,
78200
- totalWarnings
78871
+ totalWarnings: totalWarnings + discoveryDiagnostics.length,
78872
+ ...discoveryDiagnostics.length > 0 ? {
78873
+ discoveryDiagnostics
78874
+ } : {}
78201
78875
  };
78202
78876
  }
78203
78877
  lintAgent(agent, content) {
@@ -78680,6 +79354,7 @@ const INVALID_JSON_MESSAGE_PREFIX = "Invalid JSON in hook configuration file";
78680
79354
  * Code's `.vscode/mcp.json` convention) is a map of server name to a
78681
79355
  * server declaration.
78682
79356
  */
79357
+
78683
79358
  const lint_mcp_servers_INVALID_JSON_MESSAGE_PREFIX = "Invalid JSON in MCP server configuration file";
78684
79359
  /**
78685
79360
  * Property names that must never be used as MCP server names: assigning
@@ -78697,20 +79372,6 @@ const lint_mcp_servers_SERVER_MAP_FIELDS = [
78697
79372
  "mcpServers",
78698
79373
  "servers"
78699
79374
  ];
78700
- /**
78701
- * Zod schema for a single MCP server declaration.
78702
- * Baseline shape only: an object whose optional `type`/`transport` fields,
78703
- * when present, must be non-empty strings. Unknown fields are preserved.
78704
- */ const lint_mcp_servers_McpServerEntrySchema = schemas_object({
78705
- type: schemas_string().min(1, "type must not be empty").optional(),
78706
- transport: schemas_string().min(1, "transport must not be empty").optional()
78707
- }).passthrough();
78708
- /**
78709
- * Zod schema for the MCP config file shape.
78710
- */ const lint_mcp_servers_McpConfigSchema = schemas_object({
78711
- mcpServers: schemas_record(schemas_string(), lint_mcp_servers_McpServerEntrySchema).optional(),
78712
- servers: schemas_record(schemas_string(), lint_mcp_servers_McpServerEntrySchema).optional()
78713
- }).passthrough();
78714
79375
  function lint_mcp_servers_isPlainObject(value) {
78715
79376
  return typeof value === "object" && value !== null;
78716
79377
  }
@@ -78821,7 +79482,7 @@ function countBySeverity(results, severity) {
78821
79482
  if (reservedNameDiagnostics.length > 0) {
78822
79483
  return invalidConfigResult(file.filePath, reservedNameDiagnostics);
78823
79484
  }
78824
- const result = lint_mcp_servers_McpConfigSchema.safeParse(parsed);
79485
+ const result = McpConfigSchema.safeParse(parsed);
78825
79486
  if (!result.success) {
78826
79487
  return invalidConfigResult(file.filePath, zodIssuesToDiagnostics(result.error.issues));
78827
79488
  }
@@ -78868,7 +79529,12 @@ class LintSkillFrontmatterUseCase {
78868
79529
  if (!input.targetDir) {
78869
79530
  throw new Error("Target directory is required");
78870
79531
  }
78871
- const skills = await this.gateway.discoverSkills(input.targetDir);
79532
+ const discoveryDiagnostics = [];
79533
+ const skills = await this.gateway.discoverSkills(input.targetDir, (diagnostic)=>discoveryDiagnostics.push({
79534
+ filePath: input.targetDir,
79535
+ ruleId: diagnostic.ruleId,
79536
+ message: diagnostic.message
79537
+ }));
78872
79538
  const results = [];
78873
79539
  for (const skill of skills){
78874
79540
  const content = await this.gateway.readSkillFileContent(skill.filePath);
@@ -78881,7 +79547,10 @@ class LintSkillFrontmatterUseCase {
78881
79547
  results,
78882
79548
  totalSkills: skills.length,
78883
79549
  totalErrors,
78884
- totalWarnings
79550
+ totalWarnings: totalWarnings + discoveryDiagnostics.length,
79551
+ ...discoveryDiagnostics.length > 0 ? {
79552
+ discoveryDiagnostics
79553
+ } : {}
78885
79554
  };
78886
79555
  }
78887
79556
  lintSkill(skill, content) {
@@ -79019,7 +79688,12 @@ function hasFrontmatterDelimiters(content) {
79019
79688
  if (!input.targetDir) {
79020
79689
  throw new Error("Target directory is required");
79021
79690
  }
79022
- const subagents = await this.gateway.discoverSubagents(input.targetDir);
79691
+ const discoveryDiagnostics = [];
79692
+ const subagents = await this.gateway.discoverSubagents(input.targetDir, (diagnostic)=>discoveryDiagnostics.push({
79693
+ filePath: input.targetDir,
79694
+ ruleId: diagnostic.ruleId,
79695
+ message: diagnostic.message
79696
+ }));
79023
79697
  const results = [];
79024
79698
  for (const subagent of subagents){
79025
79699
  const content = await this.gateway.readSubagentFileContent(subagent.filePath);
@@ -79032,7 +79706,10 @@ function hasFrontmatterDelimiters(content) {
79032
79706
  results,
79033
79707
  totalSubagents: subagents.length,
79034
79708
  totalErrors,
79035
- totalWarnings
79709
+ totalWarnings: totalWarnings + discoveryDiagnostics.length,
79710
+ ...discoveryDiagnostics.length > 0 ? {
79711
+ discoveryDiagnostics
79712
+ } : {}
79036
79713
  };
79037
79714
  }
79038
79715
  lintSubagent(subagent, content) {
@@ -79304,6 +79981,16 @@ const LintOptionsSchema = schemas_object({
79304
79981
  });
79305
79982
  }
79306
79983
  }
79984
+ for (const report of output.discoveryDiagnostics ?? []){
79985
+ diagnostics.push({
79986
+ filePath: report.filePath,
79987
+ line: 1,
79988
+ severity: "warning",
79989
+ message: report.message,
79990
+ ruleId: report.ruleId,
79991
+ target
79992
+ });
79993
+ }
79307
79994
  return {
79308
79995
  diagnostics,
79309
79996
  target,
@@ -88870,4 +89557,4 @@ if (installedChunkData !== 0) { // 0 means "already installed".'
88870
89557
  // module factories are used so entry inlining is disabled
88871
89558
  // startup
88872
89559
  // Load entry module and return exports
88873
- var __webpack_exports__ = __webpack_require__(6416);
89560
+ var __webpack_exports__ = __webpack_require__(5219);