@eworkbase/plugin-ai-rules 0.4.1 → 0.4.2

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/plugin.mjs CHANGED
@@ -5814,6 +5814,11 @@ let PluginCommandTransaction = /* @__PURE__ */ function(PluginCommandTransaction
5814
5814
  PluginCommandTransaction["ProjectMutation"] = "projectMutation";
5815
5815
  return PluginCommandTransaction;
5816
5816
  }({});
5817
+ let PluginProcessOutputMode = /* @__PURE__ */ function(PluginProcessOutputMode) {
5818
+ PluginProcessOutputMode["Log"] = "log";
5819
+ PluginProcessOutputMode["Content"] = "content";
5820
+ return PluginProcessOutputMode;
5821
+ }({});
5817
5822
  let PluginSharedChangeKind = /* @__PURE__ */ function(PluginSharedChangeKind) {
5818
5823
  PluginSharedChangeKind["None"] = "none";
5819
5824
  PluginSharedChangeKind["Files"] = "files";
@@ -8284,6 +8289,15 @@ const MAXIMUM_OUTPUT_FILES = 1024;
8284
8289
  const MAXIMUM_JOURNAL_BYTES = 67108864;
8285
8290
  const JOURNAL_FILE = "injection-journal.json";
8286
8291
  const JOURNAL_TEMPORARY_FILE = `${JOURNAL_FILE}.tmp`;
8292
+ const RECOVERY_CLIENT_PATHS = [
8293
+ "AGENTS.md",
8294
+ "CLAUDE.md",
8295
+ ".mcp.json",
8296
+ ".codex/config.toml"
8297
+ ];
8298
+ const RECOVERY_MCP_KEYS = ["mcpServers", "mcp_servers"];
8299
+ const RECOVERY_DIRECTORY_PREFIX = "injection-recovery-";
8300
+ const RECOVERY_CLIENT_SNAPSHOT_FILE = "clients.json";
8287
8301
  const FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set([
8288
8302
  ".",
8289
8303
  "..",
@@ -8300,18 +8314,123 @@ const JOURNAL_SCHEMA = object({
8300
8314
  root: string(),
8301
8315
  files: array(tuple([string(), array(MANAGED_FILE_SCHEMA).min(1).max(2)])).max(MAXIMUM_OUTPUT_FILES)
8302
8316
  }).strict();
8317
+ /** 可通过重新同步恢复的客户端内容冲突,不包括路径或归属记录校验失败。 */
8318
+ var InjectionConflictError = class extends Error {
8319
+ path;
8320
+ constructor(relativePath, cause) {
8321
+ super(cause?.message ?? `规则不会覆盖或撤销已被修改的文件:${relativePath}`, { cause });
8322
+ this.path = relativePath;
8323
+ }
8324
+ };
8303
8325
  var InjectionWriter = class {
8304
8326
  root;
8305
8327
  #stateRoot;
8306
8328
  #managed = /* @__PURE__ */ new Map();
8329
+ #isLoaded = false;
8307
8330
  constructor(root, stateDirectory) {
8308
8331
  this.root = realpathSync(root);
8309
8332
  this.#stateRoot = stateDirectory ? realpathSync(stateDirectory()) : null;
8310
- if (this.#stateRoot) this.#load();
8333
+ this.#isLoaded = this.#load() === null;
8334
+ }
8335
+ /** 在可交互的生命周期内恢复归属,取消与失败均保留文件供原入口重试。 */
8336
+ async prepare(invocation) {
8337
+ const stateRoot = this.#stateRoot;
8338
+ if (this.#isLoaded || !stateRoot) return;
8339
+ const recovery = this.#load();
8340
+ if (!recovery) {
8341
+ this.#isLoaded = true;
8342
+ return;
8343
+ }
8344
+ const paths = recovery.managed ? [...recovery.managed.keys()] : RECOVERY_CLIENT_PATHS;
8345
+ const files = new Map(paths.map((relativePath) => [relativePath, readSafeFile(this.root, relativePath)]));
8346
+ const snapshots = JSON.stringify({
8347
+ root: this.root,
8348
+ files: [...files]
8349
+ });
8350
+ const replacement = recovery.managed ? "恢复会替换旧注入及受管文件中的本地修改。" : "归属记录已不可用,恢复会重建会话规则并重置这些客户端文件的 MCP 连接,包含手动添加的连接。";
8351
+ if (Buffer.byteLength(snapshots) > MAXIMUM_JOURNAL_BYTES) throw new Error("规则客户端备份超过大小上限,恢复已停止,现有文件已保留。");
8352
+ const { confirmed } = await invocation.services.prompt.ask({
8353
+ name: "confirmed",
8354
+ type: "confirm",
8355
+ purpose: "approval",
8356
+ default: false,
8357
+ title: "恢复本机规则上下文",
8358
+ submitLabel: "备份并恢复",
8359
+ message: `${recovery.message}是否备份现有文件并按当前工作区重新生成规则?`,
8360
+ details: `${replacement}其他文件保持原样。原文件和归属记录保存在本机插件私有目录,可供恢复。\n\n涉及文件:\n${paths.join("\n")}`
8361
+ });
8362
+ invocation.signal.throwIfAborted();
8363
+ if (confirmed !== true) throw new Error("已取消规则上下文恢复,现有文件已保留。点击“重试此插件”可重新确认恢复。");
8364
+ const journalPath = safeFilePath(stateRoot, JOURNAL_FILE);
8365
+ if ((lstatSync(journalPath, { throwIfNoEntry: false }) ? readFileSync(journalPath, "utf8") : null) !== recovery.content || [...files].some(([relativePath, content]) => readSafeFile(this.root, relativePath) !== content)) throw new Error("规则文件或归属记录在确认期间已变化,恢复已停止。请重试此插件重新核对。");
8366
+ const backupRoot = mkdtempSync(path.join(stateRoot, RECOVERY_DIRECTORY_PREFIX));
8367
+ writeSafeFile({
8368
+ root: backupRoot,
8369
+ relativePath: JOURNAL_FILE,
8370
+ content: recovery.content ?? "null\n"
8371
+ });
8372
+ writeSafeFile({
8373
+ root: backupRoot,
8374
+ relativePath: RECOVERY_CLIENT_SNAPSHOT_FILE,
8375
+ content: snapshots
8376
+ });
8377
+ const managed = /* @__PURE__ */ new Map();
8378
+ files.forEach((content, relativePath) => {
8379
+ if (content === null) return;
8380
+ const previous = recovery.managed?.get(relativePath)?.at(-1);
8381
+ const before = previous ? previous.before : recoveryBaseline(relativePath, content);
8382
+ managed.set(relativePath, [{
8383
+ before,
8384
+ after: content
8385
+ }]);
8386
+ });
8387
+ this.#save(managed);
8388
+ this.#managed = managed;
8389
+ this.#isLoaded = true;
8390
+ invocation.services.store.setState({ injectionRecoveryBackup: backupRoot });
8391
+ invocation.services.toast.show("本机规则归属已恢复,正在继续生成当前工作区的规则。", "info");
8392
+ invocation.report?.({
8393
+ success: true,
8394
+ summary: "已备份并恢复本机规则归属。",
8395
+ warnings: [`恢复备份:${backupRoot}`]
8396
+ });
8311
8397
  }
8312
8398
  get paths() {
8313
8399
  return [...this.#managed.keys()];
8314
8400
  }
8401
+ get conflicts() {
8402
+ return this.paths.flatMap((relativePath) => {
8403
+ const current = readSafeFile(this.root, relativePath);
8404
+ try {
8405
+ this.#restore(relativePath);
8406
+ return [];
8407
+ } catch (error) {
8408
+ if (!(error instanceof InjectionConflictError)) throw error;
8409
+ return [{
8410
+ path: relativePath,
8411
+ revision: fileRevision(relativePath, current)
8412
+ }];
8413
+ }
8414
+ });
8415
+ }
8416
+ /** 确认的冲突文件只在临时目录回到原基线,生成成功前不改动工作区。 */
8417
+ prepareSynchronization(overwriteFiles) {
8418
+ const before = new Map(this.paths.map((relativePath) => [relativePath, readSafeFile(this.root, relativePath)]));
8419
+ const confirmed = /* @__PURE__ */ new Set();
8420
+ for (const file of overwriteFiles) {
8421
+ if (!before.has(file.path) || confirmed.has(file.path) || fileRevision(file.path, before.get(file.path) ?? null) !== file.revision) throw new Error("客户端文件已变化,请刷新状态后重新确认强制覆盖。");
8422
+ confirmed.add(file.path);
8423
+ }
8424
+ return {
8425
+ before,
8426
+ baselines: new Map(this.paths.map((relativePath) => {
8427
+ if (!confirmed.has(relativePath)) return [relativePath, this.baseline(relativePath)];
8428
+ const managed = this.#managed.get(relativePath)?.at(-1);
8429
+ if (!managed) throw new Error(`客户端文件没有可恢复的归属记录:${relativePath}`);
8430
+ return [relativePath, managed.before];
8431
+ }))
8432
+ };
8433
+ }
8315
8434
  /** 返回去除旧注入后的当前内容,保留注入以外的用户编辑。 */
8316
8435
  baseline(relativePath) {
8317
8436
  return this.#restore(relativePath).content;
@@ -8327,13 +8446,17 @@ var InjectionWriter = class {
8327
8446
  });
8328
8447
  }
8329
8448
  /** 在写入之前验证全部文件;失败时恢复本次实际写入前的内容。 */
8330
- apply(fragments) {
8331
- const desired = /* @__PURE__ */ new Map();
8449
+ apply(fragments, synchronization) {
8450
+ for (const [relativePath, before] of synchronization?.before ?? []) if (readSafeFile(this.root, relativePath) !== before) throw new Error(`客户端文件在同步期间又有修改,已停止覆盖并保留当前内容:${relativePath}`);
8451
+ const desired = new Map(synchronization?.baselines);
8332
8452
  const nextManaged = /* @__PURE__ */ new Map();
8333
8453
  const pendingManaged = /* @__PURE__ */ new Map();
8334
8454
  const paths = /* @__PURE__ */ new Set([...this.#managed.keys(), ...fragments.keys()]);
8335
8455
  for (const relativePath of paths) {
8336
- const { content: before, managed } = this.#restore(relativePath);
8456
+ const { content: before, managed } = synchronization?.baselines.has(relativePath) ? {
8457
+ content: synchronization.baselines.get(relativePath) ?? null,
8458
+ managed: this.#managed.get(relativePath)?.at(-1)
8459
+ } : this.#restore(relativePath);
8337
8460
  const fragment = fragments.get(relativePath);
8338
8461
  const after = fragment === void 0 ? before : mergeContent({
8339
8462
  relativePath,
@@ -8401,32 +8524,54 @@ var InjectionWriter = class {
8401
8524
  managed
8402
8525
  });
8403
8526
  } catch (error) {
8404
- failure = error instanceof Error ? error : conflict(relativePath);
8527
+ failure = error instanceof Error ? new InjectionConflictError(relativePath, error) : conflict(relativePath);
8405
8528
  }
8406
8529
  }
8407
8530
  const first = restored[0];
8408
8531
  if (first && restored.every(({ content }) => content === first.content)) return first;
8409
- if (first) throw new Error(`规则注入恢复未完成:${relativePath} 在中断写入后又有改动,无法安全确认归属。请检查该文件后重试;现有内容已保留。`);
8532
+ if (first) throw new InjectionConflictError(relativePath, /* @__PURE__ */ new Error(`规则注入恢复未完成:${relativePath} 在中断写入后又有改动,无法安全确认归属。请检查该文件后重试;现有内容已保留。`));
8410
8533
  throw failure;
8411
8534
  }
8412
8535
  #load() {
8413
- if (!this.#stateRoot) return;
8536
+ if (!this.#stateRoot) return null;
8414
8537
  const filePath = safeFilePath(this.#stateRoot, JOURNAL_FILE);
8415
8538
  const metadata = lstatSync(filePath, { throwIfNoEntry: false });
8416
- if (!metadata) return;
8539
+ if (!metadata) return [...INSTRUCTION_FILES].some((relativePath) => {
8540
+ const content = readSafeFile(this.root, relativePath);
8541
+ return content?.includes(BLOCK_START) || content?.includes(BLOCK_END);
8542
+ }) ? {
8543
+ content: null,
8544
+ managed: null,
8545
+ message: "客户端保留了旧规则注入,但本机归属记录已缺失。"
8546
+ } : null;
8417
8547
  if (!metadata.isFile() || metadata.size > MAXIMUM_JOURNAL_BYTES) throw new Error("规则注入归属记录不是有效文件;请检查规则插件的私有存储后重试。");
8548
+ const content = readFileSync(filePath, "utf8");
8418
8549
  let stored;
8419
8550
  try {
8420
- stored = JSON.parse(readFileSync(filePath, "utf8"));
8421
- } catch (error) {
8422
- throw new Error("无法读取规则注入归属记录;已保留客户端文件,请检查规则插件的私有存储后重试。", { cause: error });
8551
+ stored = JSON.parse(content);
8552
+ } catch {
8553
+ return {
8554
+ content,
8555
+ managed: null,
8556
+ message: "本机规则归属记录无法解析。"
8557
+ };
8423
8558
  }
8424
8559
  const parsed = JOURNAL_SCHEMA.safeParse(stored);
8425
- if (!parsed.success || parsed.data.root !== this.root) throw new Error("规则注入归属记录无效或不属于当前工作区;已保留客户端文件,请检查私有存储后重试。");
8560
+ if (!parsed.success) return {
8561
+ content,
8562
+ managed: null,
8563
+ message: "本机规则归属记录格式已失效。"
8564
+ };
8426
8565
  const managed = new Map(parsed.data.files);
8427
8566
  if (managed.size !== parsed.data.files.length) throw new Error("规则注入归属记录含重复文件,已保留客户端文件。");
8428
8567
  managed.forEach((_candidates, relativePath) => safeFilePath(this.root, relativePath));
8568
+ if (parsed.data.root !== this.root) return {
8569
+ content,
8570
+ managed,
8571
+ message: "项目目录已变化,旧规则归属记录仍绑定原目录。"
8572
+ };
8429
8573
  this.#managed = managed;
8574
+ return null;
8430
8575
  }
8431
8576
  #save(managed) {
8432
8577
  if (!this.#stateRoot) return;
@@ -8447,6 +8592,29 @@ var InjectionWriter = class {
8447
8592
  }
8448
8593
  }
8449
8594
  };
8595
+ /** 重建时仅移除已确认要替换的会话区块与 MCP 配置,保留其他客户端设置。 */
8596
+ function recoveryBaseline(relativePath, content) {
8597
+ if (INSTRUCTION_FILES.has(path.posix.basename(relativePath))) {
8598
+ const start = content.indexOf(BLOCK_START);
8599
+ const end = content.indexOf(BLOCK_END, start);
8600
+ if (start < 0 && end < 0) return content;
8601
+ if (start < 0 || end < start || content.indexOf(BLOCK_START, start + 30) >= 0 || content.indexOf(BLOCK_END, end + 28) >= 0) return null;
8602
+ const prefix = content.slice(0, start);
8603
+ const suffix = content.slice(end + 28);
8604
+ return (prefix.endsWith("\n\n") ? prefix.slice(0, -2) : prefix) + (suffix.startsWith("\n") ? suffix.slice(1) : suffix);
8605
+ }
8606
+ try {
8607
+ const document = { ...parseDocument$1(relativePath, content) };
8608
+ RECOVERY_MCP_KEYS.forEach((key) => delete document[key]);
8609
+ return formatDocument({
8610
+ relativePath,
8611
+ previous: content,
8612
+ document
8613
+ });
8614
+ } catch {
8615
+ return null;
8616
+ }
8617
+ }
8450
8618
  /** 只接受源树或客户端树内的相对路径,不跟随符号链接。 */
8451
8619
  function safeFilePath(root, relativePath) {
8452
8620
  if (lstatSync(root).isSymbolicLink()) throw new Error("规则输出根目录不能是符号链接。");
@@ -8670,7 +8838,10 @@ function isObject(value) {
8670
8838
  return value !== null && typeof value === "object" && !Array.isArray(value);
8671
8839
  }
8672
8840
  function conflict(relativePath) {
8673
- return /* @__PURE__ */ new Error(`规则不会覆盖或撤销已被修改的文件:${relativePath}`);
8841
+ return new InjectionConflictError(relativePath);
8842
+ }
8843
+ function fileRevision(relativePath, content) {
8844
+ return createHash("sha256").update(JSON.stringify([relativePath, content])).digest("hex");
8674
8845
  }
8675
8846
  //#endregion
8676
8847
  //#region src/injection.ts
@@ -8721,6 +8892,7 @@ var InjectionService = class {
8721
8892
  #options;
8722
8893
  #writer;
8723
8894
  #requests = /* @__PURE__ */ new Map();
8895
+ #pendingRequests = /* @__PURE__ */ new Map();
8724
8896
  #fragments = /* @__PURE__ */ new Map();
8725
8897
  #targets = [];
8726
8898
  #pending = null;
@@ -8742,9 +8914,11 @@ var InjectionService = class {
8742
8914
  }
8743
8915
  }
8744
8916
  status(identity) {
8745
- const requests = [...this.#requests.values()].filter((request) => !identity || key(request) === key(identity));
8917
+ const requests = [...new Map([...this.#requests, ...this.#pendingRequests]).values()].filter((request) => !identity || key(request) === key(identity));
8918
+ const pending = requests.some((request) => this.#pendingRequests.has(key(request)));
8746
8919
  return {
8747
- injected: requests.length > 0 && this.#writer.isApplied(),
8920
+ injected: requests.length > 0 && !pending && this.#writer.isApplied(),
8921
+ pending,
8748
8922
  injections: requests.map(({ pluginId, id, files, mcpServers }) => ({
8749
8923
  pluginId,
8750
8924
  id,
@@ -8764,6 +8938,7 @@ var InjectionService = class {
8764
8938
  summary: "AI 上下文注入未完成。"
8765
8939
  });
8766
8940
  if (isDeepStrictEqual(this.#requests.get(key(request)), request) && isDeepStrictEqual(this.#targets, this.#options.targets()) && this.#writer.isApplied()) {
8941
+ this.#pendingRequests.delete(key(request));
8767
8942
  invocation.report?.({
8768
8943
  ...details,
8769
8944
  success: true,
@@ -8771,10 +8946,15 @@ var InjectionService = class {
8771
8946
  });
8772
8947
  return this.status(request);
8773
8948
  }
8774
- const requests = new Map(this.#requests);
8949
+ const requests = new Map([...this.#requests, ...this.#pendingRequests]);
8775
8950
  requests.set(key(request), request);
8776
8951
  if (requests.size > MAXIMUM_INJECTIONS) throw new Error("当前会话的规则注入数量过多。");
8777
- await this.#update(requests, invocation);
8952
+ try {
8953
+ await this.#update(requests, invocation);
8954
+ } catch (error) {
8955
+ if (error instanceof InjectionConflictError && this.#writer.paths.includes(error.path) && !invocation.signal.aborted) this.#pendingRequests.set(key(request), request);
8956
+ throw error;
8957
+ }
8778
8958
  invocation.report?.({
8779
8959
  ...details,
8780
8960
  success: true,
@@ -8789,9 +8969,10 @@ var InjectionService = class {
8789
8969
  const requests = new Map(this.#requests);
8790
8970
  const request = requests.get(key(identity));
8791
8971
  if (!request) {
8972
+ const wasPending = this.#pendingRequests.delete(key(identity));
8792
8973
  invocation.report?.({
8793
8974
  success: true,
8794
- summary: `注入 ${key(identity)} 不存在,无需撤销。`
8975
+ summary: wasPending ? `已取消待恢复注入:${key(identity)}。` : `注入 ${key(identity)} 不存在,无需撤销。`
8795
8976
  });
8796
8977
  return this.status(identity);
8797
8978
  }
@@ -8803,6 +8984,7 @@ var InjectionService = class {
8803
8984
  });
8804
8985
  requests.delete(key(identity));
8805
8986
  await this.#update(requests, invocation);
8987
+ this.#pendingRequests.delete(key(identity));
8806
8988
  invocation.report?.({
8807
8989
  ...details,
8808
8990
  success: true,
@@ -8816,6 +8998,7 @@ var InjectionService = class {
8816
8998
  return this.run(async () => {
8817
8999
  this.#writer.cleanup();
8818
9000
  this.#requests.clear();
9001
+ this.#pendingRequests.clear();
8819
9002
  this.#fragments.clear();
8820
9003
  this.#targets = [];
8821
9004
  });
@@ -8831,13 +9014,19 @@ var InjectionService = class {
8831
9014
  if (this.#requests.size && targets.some((target) => !SUPPORTED_TARGETS.has(target))) throw new Error("存在动态注入时,仅支持选择 Codex CLI 和 Claude Code。");
8832
9015
  }
8833
9016
  /** 团队规则同步在基线文件上执行,完成后重新覆盖本会话的动态内容。 */
8834
- async synchronize(operation, invocation) {
9017
+ async synchronize(operation, { invocation, overwriteFiles = [] }) {
8835
9018
  return this.run(async () => {
9019
+ await this.#writer.prepare(invocation);
9020
+ if (overwriteFiles.length) return this.#synchronizeOverwrite(operation, {
9021
+ invocation,
9022
+ overwriteFiles
9023
+ });
8836
9024
  this.#writer.apply(/* @__PURE__ */ new Map());
8837
9025
  try {
8838
- return await operation();
9026
+ return await operation(this.#options.workspaceRoot);
8839
9027
  } finally {
8840
- if (this.#requests.size && !invocation.signal.aborted && !isDeepStrictEqual(this.#targets, this.#options.targets())) await this.#update(this.#requests, invocation);
9028
+ const targetsChanged = this.#requests.size > 0 && !isDeepStrictEqual(this.#targets, this.#options.targets());
9029
+ if ((this.#pendingRequests.size > 0 || targetsChanged) && !invocation.signal.aborted) await this.#update(new Map([...this.#requests, ...this.#pendingRequests]), invocation);
8841
9030
  else this.#writer.apply(this.#fragments);
8842
9031
  }
8843
9032
  }, invocation.signal);
@@ -8845,6 +9034,9 @@ var InjectionService = class {
8845
9034
  get paths() {
8846
9035
  return this.#writer.paths;
8847
9036
  }
9037
+ get conflicts() {
9038
+ return this.#writer.conflicts;
9039
+ }
8848
9040
  baseline(relativePath) {
8849
9041
  return this.#writer.baseline(relativePath);
8850
9042
  }
@@ -8853,6 +9045,45 @@ var InjectionService = class {
8853
9045
  new InjectionWriter(outputRoot).apply(this.#fragments);
8854
9046
  }
8855
9047
  async #update(requests, invocation) {
9048
+ const fragments = await this.#generate(requests, invocation);
9049
+ invocation.signal.throwIfAborted();
9050
+ await this.#writer.prepare(invocation);
9051
+ this.#writer.apply(fragments);
9052
+ this.#requests = new Map(requests);
9053
+ requests.forEach((_request, identity) => this.#pendingRequests.delete(identity));
9054
+ this.#fragments = fragments;
9055
+ this.#targets = [...this.#options.targets()];
9056
+ }
9057
+ async #synchronizeOverwrite(operation, { invocation, overwriteFiles = [] }) {
9058
+ const files = this.#writer.prepareSynchronization(overwriteFiles);
9059
+ const temporaryRoot = mkdtempSync(path.join(os.tmpdir(), "workbase-ai-sync-"));
9060
+ try {
9061
+ writeFileBatch(temporaryRoot, files.baselines);
9062
+ const result = await operation(temporaryRoot);
9063
+ if (!result.success) return result;
9064
+ const requests = new Map([...this.#requests, ...this.#pendingRequests]);
9065
+ const targets = this.#options.targets();
9066
+ const fragments = this.#pendingRequests.size > 0 || !isDeepStrictEqual(this.#targets, targets) ? await this.#generate(requests, invocation) : this.#fragments;
9067
+ const baselines = new Map([...files.before.keys()].map((relativePath) => [relativePath, null]));
9068
+ readOutputFiles(temporaryRoot).forEach((content, relativePath) => baselines.set(relativePath, content));
9069
+ invocation.signal.throwIfAborted();
9070
+ this.#writer.apply(fragments, {
9071
+ before: files.before,
9072
+ baselines
9073
+ });
9074
+ this.#requests = requests;
9075
+ this.#pendingRequests.clear();
9076
+ this.#fragments = new Map(fragments);
9077
+ this.#targets = [...targets];
9078
+ return result;
9079
+ } finally {
9080
+ rmSync(temporaryRoot, {
9081
+ recursive: true,
9082
+ force: true
9083
+ });
9084
+ }
9085
+ }
9086
+ async #generate(requests, invocation) {
8856
9087
  const targets = this.#options.targets();
8857
9088
  if (requests.size && targets.some((target) => !SUPPORTED_TARGETS.has(target))) throw new Error("动态注入当前支持 Codex CLI 和 Claude Code,请在规则中选择对应客户端。");
8858
9089
  const temporaryRoot = mkdtempSync(path.join(os.tmpdir(), "workbase-ai-inject-"));
@@ -8872,11 +9103,7 @@ var InjectionService = class {
8872
9103
  }
8873
9104
  const fragments = readOutputFiles(outputRoot);
8874
9105
  if (requests.size && !fragments.size) throw new Error("Rulesync 未生成注入文件,请检查源文件格式及目标客户端。");
8875
- invocation.signal.throwIfAborted();
8876
- this.#writer.apply(fragments);
8877
- this.#requests = new Map(requests);
8878
- this.#fragments = fragments;
8879
- this.#targets = [...targets];
9106
+ return fragments;
8880
9107
  } finally {
8881
9108
  rmSync(temporaryRoot, {
8882
9109
  recursive: true,
@@ -15640,6 +15867,8 @@ const resourceImportSchema = object({ directory: string().min(1).max(4096) }).st
15640
15867
  /** Reads and edits canonical Rulesync sources; client generation remains in the plugin. */
15641
15868
  const WORKFLOW_PLUGIN_ID = "ai-workflows";
15642
15869
  const WORKFLOW_SKILL_REFERENCES_STATUS_ID = "skill.references";
15870
+ const GIT_PROGRAM = "git";
15871
+ const GIT_INSPECTION_TIMEOUT_MILLISECONDS = 15e3;
15643
15872
  function registerResources(context, hooks) {
15644
15873
  const root = context.project.root;
15645
15874
  const catalog = () => ({ resources: resourceDocuments(root).map(({ files, ...summary }) => ({
@@ -15650,7 +15879,70 @@ function registerResources(context, hooks) {
15650
15879
  id: "resources",
15651
15880
  label: "资源",
15652
15881
  description: "只读列出项目规则、技能和 MCP。",
15653
- resolve: catalog
15882
+ resolve: async (_input, invocation) => {
15883
+ const current = catalog();
15884
+ if (!current.resources.length) return current;
15885
+ const sourcePaths = (resource) => resource.kind === "mcp" ? [mcpSource(root).path] : resource.paths;
15886
+ const paths = [...new Set(current.resources.flatMap(sourcePaths))];
15887
+ const inspect = (argumentsList) => resourceGitOutput(invocation, {
15888
+ program: GIT_PROGRAM,
15889
+ currentDirectory: root,
15890
+ arguments: argumentsList
15891
+ });
15892
+ try {
15893
+ const upstream = (await inspect([
15894
+ "rev-parse",
15895
+ "--verify",
15896
+ "@{upstream}"
15897
+ ])).trim();
15898
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(upstream)) throw new Error("团队同步记录不可用。");
15899
+ const [publishedOutput, changedOutput] = await Promise.all([inspect([
15900
+ "ls-tree",
15901
+ "-r",
15902
+ "--name-only",
15903
+ "-z",
15904
+ upstream,
15905
+ "--",
15906
+ ...paths
15907
+ ]), inspect([
15908
+ "diff",
15909
+ "--relative",
15910
+ "--name-only",
15911
+ "-z",
15912
+ "--no-renames",
15913
+ upstream,
15914
+ "--",
15915
+ ...paths
15916
+ ])]);
15917
+ const published = new Set(publishedOutput.split("\0"));
15918
+ const changed = new Set(changedOutput.split("\0"));
15919
+ return { resources: current.resources.map((resource) => {
15920
+ const sources = sourcePaths(resource);
15921
+ if (sources.every((source) => !published.has(source))) return {
15922
+ ...resource,
15923
+ publicationStatus: "local"
15924
+ };
15925
+ if (sources.some((source) => !published.has(source) || changed.has(source))) return {
15926
+ ...resource,
15927
+ publicationStatus: "pending"
15928
+ };
15929
+ return {
15930
+ ...resource,
15931
+ publicationStatus: "synced"
15932
+ };
15933
+ }) };
15934
+ } catch (failure) {
15935
+ invocation.signal.throwIfAborted();
15936
+ context.logger.warn("无法核对资源的团队同步状态。", failure);
15937
+ return {
15938
+ resources: current.resources.map((resource) => ({
15939
+ ...resource,
15940
+ publicationStatus: "unknown"
15941
+ })),
15942
+ publicationWarning: "暂时无法核对团队同步状态,资源仍可查看。请刷新列表重试。"
15943
+ };
15944
+ }
15945
+ }
15654
15946
  });
15655
15947
  hooks.registerStatus({
15656
15948
  id: "resource",
@@ -15773,6 +16065,16 @@ function resourceDocuments(root) {
15773
16065
  });
15774
16066
  return documents.sort((left, right) => `${left.kind}/${left.id}`.localeCompare(`${right.kind}/${right.id}`));
15775
16067
  }
16068
+ async function resourceGitOutput(invocation, options) {
16069
+ const result = await invocation.process.run({
16070
+ ...options,
16071
+ outputMode: PluginProcessOutputMode.Content,
16072
+ timeoutMilliseconds: GIT_INSPECTION_TIMEOUT_MILLISECONDS,
16073
+ environment: { GIT_OPTIONAL_LOCKS: "0" }
16074
+ }, invocation.signal);
16075
+ if (result.failed || result.timedOut || result.wasCancelled || result.standardOutputTruncated !== false) throw new Error("无法完整读取资源的团队同步状态。");
16076
+ return result.standardOutput;
16077
+ }
15776
16078
  function document(identity, contents) {
15777
16079
  const files = [...contents].sort(([left], [right]) => left.localeCompare(right)).map(([path, content]) => ({
15778
16080
  path,
@@ -16002,7 +16304,8 @@ async function generateRules({ config, features: requestedFeatures, invocation,
16002
16304
  });
16003
16305
  }
16004
16306
  async function previewRules({ injections, ...options }) {
16005
- if (!injections.status().injections.length) return generateRules(options);
16307
+ const injectionStatus = injections.status();
16308
+ if (!injectionStatus.injections.length) return generateRules(options);
16006
16309
  const preview = await generateRules({
16007
16310
  ...options,
16008
16311
  mode: "preview"
@@ -16026,7 +16329,7 @@ async function previewRules({ injections, ...options }) {
16026
16329
  if (!generated.success) return generated;
16027
16330
  injections.applyTo(temporaryRoot);
16028
16331
  const outputs = readOutputFiles(temporaryRoot);
16029
- const hasDiff = [...outputs].filter(([relativePath, content]) => readSafeFile(workspaceRoot, relativePath) !== content).length > 0;
16332
+ const hasDiff = [...outputs].filter(([relativePath, content]) => readSafeFile(workspaceRoot, relativePath) !== content).length > 0 || injectionStatus.pending;
16030
16333
  const details = isRecord(preview.details) && isRecord(preview.details.data) ? preview.details.data : {};
16031
16334
  const features = isRecord(details.features) ? details.features : {};
16032
16335
  const success = options.mode !== "check" || !hasDiff;
@@ -16036,6 +16339,7 @@ async function previewRules({ injections, ...options }) {
16036
16339
  success,
16037
16340
  standardOutput: "",
16038
16341
  standardError: success ? "" : "客户端文件与团队规则及当前动态注入不一致。",
16342
+ warnings: injectionStatus.pending ? [...preview.warnings, "仍有会话注入等待恢复,请执行同步以恢复客户端能力。"] : preview.warnings,
16039
16343
  details: {
16040
16344
  success,
16041
16345
  data: {
@@ -16241,6 +16545,10 @@ const CONFIGURATION_INPUT_SCHEMA = object({
16241
16545
  features: array(string().trim().min(1)).min(1),
16242
16546
  targets: array(string().trim().min(1)).min(1)
16243
16547
  }).strict();
16548
+ const SYNC_INPUT_SCHEMA = object({ overwriteFiles: array(object({
16549
+ path: string().min(1).max(240),
16550
+ revision: string().regex(/^[a-f0-9]{64}$/)
16551
+ }).strict()).max(1024).optional() }).strict().default({});
16244
16552
  var plugin_default = definePlugin({
16245
16553
  id: PLUGIN_ID,
16246
16554
  title: "规则",
@@ -16336,10 +16644,13 @@ var plugin_default = definePlugin({
16336
16644
  }));
16337
16645
  }
16338
16646
  });
16339
- const status = () => buildStatus({
16340
- config,
16341
- paths,
16342
- state: context.services.store.getState()
16647
+ const status = () => ({
16648
+ ...buildStatus({
16649
+ config,
16650
+ paths,
16651
+ state: context.services.store.getState()
16652
+ }),
16653
+ conflicts: injections.conflicts
16343
16654
  });
16344
16655
  const record = (result, invocation) => {
16345
16656
  invocation?.report?.({
@@ -16371,14 +16682,20 @@ var plugin_default = definePlugin({
16371
16682
  paths,
16372
16683
  injections
16373
16684
  }), invocation.signal), invocation);
16374
- const runSynchronization = async ({ initializationResult, invocation, operation, sourceArguments }) => record(await injections.synchronize(() => synchronizeRules({
16685
+ const runSynchronization = async ({ initializationResult, invocation, operation, overwriteFiles, sourceArguments }) => record(await injections.synchronize((workspaceRoot) => synchronizeRules({
16375
16686
  config,
16376
16687
  initializationResult,
16377
16688
  invocation,
16378
16689
  operation,
16379
- paths,
16690
+ paths: {
16691
+ ...paths,
16692
+ workspaceRoot
16693
+ },
16380
16694
  sourceArguments
16381
- }), invocation), invocation);
16695
+ }), {
16696
+ invocation,
16697
+ overwriteFiles
16698
+ }), invocation);
16382
16699
  const initialize = async (invocation) => {
16383
16700
  mkdirSync(paths.sourceRoot, { recursive: true });
16384
16701
  mkdirSync(safeFilePath(context.project.root, "rules/.rulesync"), { recursive: true });
@@ -16583,14 +16900,17 @@ var plugin_default = definePlugin({
16583
16900
  hooks.registerCommand({
16584
16901
  effect: PluginCommandEffect.LongRunning,
16585
16902
  id: "sync",
16903
+ input: SYNC_INPUT_SCHEMA,
16586
16904
  title: "同步规则",
16587
16905
  description: "组装 Rules、MCP、Commands、Subagents 和 Skills 并写入当前 Workspace。",
16588
16906
  transaction: PluginCommandTransaction.ProjectMutation,
16589
16907
  plan: () => ({ kind: PluginSharedChangeKind.None }),
16590
- run: async (_input, invocation) => {
16908
+ run: async (input, invocation) => {
16909
+ const { overwriteFiles } = SYNC_INPUT_SCHEMA.parse(input);
16591
16910
  const result = await runSynchronization({
16592
16911
  invocation,
16593
- operation: "sync"
16912
+ operation: "sync",
16913
+ overwriteFiles
16594
16914
  });
16595
16915
  requireSuccessfulOperation(result);
16596
16916
  return {