@adhdev/daemon-standalone 0.9.82-rc.411 → 0.9.82-rc.412

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
@@ -29747,14 +29747,6 @@ var require_dist3 = __commonJS({
29747
29747
  const trimmed = value.trim();
29748
29748
  return MESH_SCHEDULING_STRATEGIES.includes(trimmed) ? trimmed : DEFAULT_MESH_SCHEDULING_STRATEGY;
29749
29749
  }
29750
- function normalizeMeshDistribution(value) {
29751
- if (typeof value !== "string") return DEFAULT_MESH_DISTRIBUTION;
29752
- const trimmed = value.trim();
29753
- return MESH_DISTRIBUTIONS.includes(trimmed) ? trimmed : DEFAULT_MESH_DISTRIBUTION;
29754
- }
29755
- function distributionToStrategy(distribution) {
29756
- return distribution === "spread" ? "least_loaded" : "first_eligible";
29757
- }
29758
29750
  function resolveNodeSchedulingPriority(nodePolicy) {
29759
29751
  const raw = Number(nodePolicy?.schedulingPriority);
29760
29752
  return Number.isFinite(raw) ? raw : 0;
@@ -29843,8 +29835,6 @@ var require_dist3 = __commonJS({
29843
29835
  }
29844
29836
  var MESH_SCHEDULING_STRATEGIES;
29845
29837
  var DEFAULT_MESH_SCHEDULING_STRATEGY;
29846
- var MESH_DISTRIBUTIONS;
29847
- var DEFAULT_MESH_DISTRIBUTION;
29848
29838
  var MESH_CONVERGE_REFINE_TAG;
29849
29839
  var MESH_CONVERGE_FAST_FORWARD_TAG;
29850
29840
  var DEFAULT_MESH_POLICY;
@@ -29864,8 +29854,6 @@ var require_dist3 = __commonJS({
29864
29854
  "priority_only"
29865
29855
  ];
29866
29856
  DEFAULT_MESH_SCHEDULING_STRATEGY = "first_eligible";
29867
- MESH_DISTRIBUTIONS = ["spread", "in_order"];
29868
- DEFAULT_MESH_DISTRIBUTION = "spread";
29869
29857
  MESH_CONVERGE_REFINE_TAG = "converge=refine";
29870
29858
  MESH_CONVERGE_FAST_FORWARD_TAG = "converge=fast_forward";
29871
29859
  DEFAULT_MESH_POLICY = {
@@ -30127,10 +30115,10 @@ var require_dist3 = __commonJS({
30127
30115
  }
30128
30116
  function getDaemonBuildInfo() {
30129
30117
  if (cached2) return cached2;
30130
- const commit = readInjected(true ? "69cd9c459ec9efafe19a05f66899bb791d6e0561" : void 0) ?? "unknown";
30131
- const commitShort = readInjected(true ? "69cd9c45" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
30132
- const version2 = readInjected(true ? "0.9.82-rc.411" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
30133
- const builtAt = readInjected(true ? "2026-06-28T09:11:57.766Z" : void 0);
30118
+ const commit = readInjected(true ? "f8bbe838081c3b3e14df690b3ed24568979f635e" : void 0) ?? "unknown";
30119
+ const commitShort = readInjected(true ? "f8bbe838" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
30120
+ const version2 = readInjected(true ? "0.9.82-rc.412" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
30121
+ const builtAt = readInjected(true ? "2026-06-28T10:27:49.415Z" : void 0);
30134
30122
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
30135
30123
  return cached2;
30136
30124
  }
@@ -36882,6 +36870,9 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36882
36870
  summarizeMissionTasks: () => summarizeMissionTasks,
36883
36871
  upsertMeshMission: () => upsertMeshMission
36884
36872
  });
36873
+ function summarizeGoalForLedger(goal) {
36874
+ return goal.length > LEDGER_GOAL_SUMMARY_MAX ? goal.slice(0, LEDGER_GOAL_SUMMARY_MAX) : goal;
36875
+ }
36885
36876
  function normalizeMissionStatus(value) {
36886
36877
  return MESH_MISSION_STATUSES.includes(value) ? value : "active";
36887
36878
  }
@@ -36894,6 +36885,8 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36894
36885
  const id = typeof input.id === "string" && input.id.trim() ? input.id.trim() : (0, import_crypto7.randomUUID)();
36895
36886
  const store = MeshRuntimeStore.getInstance();
36896
36887
  const existing = store.getMission(meshId, id);
36888
+ const prevStatus = existing ? normalizeMissionStatus(existing.status) : null;
36889
+ const prevGoal = existing?.goal ?? "";
36897
36890
  const record2 = {
36898
36891
  id,
36899
36892
  meshId,
@@ -36903,7 +36896,61 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36903
36896
  };
36904
36897
  store.upsertMission(record2);
36905
36898
  const saved = store.getMission(meshId, id);
36906
- return { ...saved, status: normalizeMissionStatus(saved.status) };
36899
+ const result = { ...saved, status: normalizeMissionStatus(saved.status) };
36900
+ appendMissionLedgerEntries(meshId, {
36901
+ isCreate: !existing,
36902
+ record: result,
36903
+ prevStatus,
36904
+ prevGoal
36905
+ });
36906
+ return result;
36907
+ }
36908
+ function appendMissionLedgerEntries(meshId, args) {
36909
+ const { isCreate, record: record2, prevStatus, prevGoal } = args;
36910
+ try {
36911
+ if (isCreate) {
36912
+ const goal = record2.goal ?? "";
36913
+ appendLedgerEntry(meshId, {
36914
+ kind: "mission_created",
36915
+ payload: {
36916
+ missionId: record2.id,
36917
+ title: record2.title,
36918
+ goalSummary: summarizeGoalForLedger(goal),
36919
+ goalLength: goal.length,
36920
+ goalTruncated: goal.length > LEDGER_GOAL_SUMMARY_MAX,
36921
+ status: record2.status
36922
+ }
36923
+ });
36924
+ return;
36925
+ }
36926
+ if (prevStatus !== null && prevStatus !== record2.status) {
36927
+ appendLedgerEntry(meshId, {
36928
+ kind: "mission_status_changed",
36929
+ payload: {
36930
+ missionId: record2.id,
36931
+ title: record2.title,
36932
+ fromStatus: prevStatus,
36933
+ toStatus: record2.status
36934
+ }
36935
+ });
36936
+ }
36937
+ const nextGoal = record2.goal ?? "";
36938
+ if (nextGoal !== prevGoal) {
36939
+ appendLedgerEntry(meshId, {
36940
+ kind: "mission_goal_updated",
36941
+ payload: {
36942
+ missionId: record2.id,
36943
+ title: record2.title,
36944
+ prevGoalSummary: summarizeGoalForLedger(prevGoal),
36945
+ nextGoalSummary: summarizeGoalForLedger(nextGoal),
36946
+ prevGoalLength: prevGoal.length,
36947
+ nextGoalLength: nextGoal.length,
36948
+ goalTruncated: prevGoal.length > LEDGER_GOAL_SUMMARY_MAX || nextGoal.length > LEDGER_GOAL_SUMMARY_MAX
36949
+ }
36950
+ });
36951
+ }
36952
+ } catch {
36953
+ }
36907
36954
  }
36908
36955
  function getMeshMissions(meshId, statuses) {
36909
36956
  return MeshRuntimeStore.getInstance().getMissions(meshId, statuses).map((m) => ({ ...m, status: normalizeMissionStatus(m.status) }));
@@ -37008,6 +37055,7 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
37008
37055
  return lines.join("\n");
37009
37056
  }
37010
37057
  var import_crypto7;
37058
+ var LEDGER_GOAL_SUMMARY_MAX;
37011
37059
  var MESH_MISSION_STATUSES;
37012
37060
  var GOAL_PREVIEW_MAX;
37013
37061
  var COMPACT_STATUS_GOAL_PREVIEW_MAX;
@@ -37018,6 +37066,8 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
37018
37066
  init_mesh_runtime_store();
37019
37067
  init_mesh_work_queue();
37020
37068
  init_mesh_task_stats();
37069
+ init_mesh_ledger();
37070
+ LEDGER_GOAL_SUMMARY_MAX = 200;
37021
37071
  MESH_MISSION_STATUSES = ["active", "paused", "completed", "abandoned"];
37022
37072
  GOAL_PREVIEW_MAX = 120;
37023
37073
  COMPACT_STATUS_GOAL_PREVIEW_MAX = 80;
@@ -38491,6 +38541,218 @@ ${rendered}`, "utf-8");
38491
38541
  OUTPUT_SUMMARY_CHARS = 2e3;
38492
38542
  }
38493
38543
  });
38544
+ var mesh_json_config_exports = {};
38545
+ __export2(mesh_json_config_exports, {
38546
+ MESH_JSON_CONFIG_LOCATIONS: () => MESH_JSON_CONFIG_LOCATIONS,
38547
+ MESH_JSON_CONFIG_SCHEMA: () => MESH_JSON_CONFIG_SCHEMA,
38548
+ applyRepoMeshConfig: () => applyRepoMeshConfig,
38549
+ buildMeshJsonConfigScaffold: () => buildMeshJsonConfigScaffold,
38550
+ loadRepoMeshJsonConfig: () => loadRepoMeshJsonConfig,
38551
+ mergeEffectiveCoordinatorConfig: () => mergeEffectiveCoordinatorConfig,
38552
+ mergeEffectiveOperatingNotes: () => mergeEffectiveOperatingNotes,
38553
+ normalizeRepoMeshDeclarativeConfig: () => normalizeRepoMeshDeclarativeConfig,
38554
+ serializeMeshJsonConfigScaffold: () => serializeMeshJsonConfigScaffold
38555
+ });
38556
+ function isRecord3(value) {
38557
+ return !!value && typeof value === "object" && !Array.isArray(value);
38558
+ }
38559
+ function parseConfigText4(path43, text) {
38560
+ if (/\.json$/i.test(path43)) return JSON.parse(text);
38561
+ return yaml4.load(text);
38562
+ }
38563
+ function normalizeOperatingNote(value) {
38564
+ if (!isRecord3(value)) return null;
38565
+ const text = typeof value.text === "string" ? value.text.trim() : "";
38566
+ if (!text) return null;
38567
+ const category = value.category === "provider_quirk" || value.category === "pattern_to_avoid" || value.category === "recovery_lesson" ? value.category : void 0;
38568
+ return {
38569
+ text,
38570
+ ...category ? { category } : {},
38571
+ ...typeof value.createdAt === "string" ? { createdAt: value.createdAt } : {},
38572
+ ...typeof value.sourceCoordinator === "string" ? { sourceCoordinator: value.sourceCoordinator } : {}
38573
+ };
38574
+ }
38575
+ function normalizeRepoMeshDeclarativeConfig(parsed) {
38576
+ const errors = [];
38577
+ if (!isRecord3(parsed)) return { valid: false, errors: ["config must be an object"] };
38578
+ if (parsed.version !== 1) {
38579
+ return { valid: false, errors: [`version must be 1 (got ${JSON.stringify(parsed.version)})`] };
38580
+ }
38581
+ const config2 = { version: 1 };
38582
+ if (parsed.coordinator !== void 0) {
38583
+ if (isRecord3(parsed.coordinator)) {
38584
+ const coord = {};
38585
+ const c = parsed.coordinator;
38586
+ if (typeof c.systemPromptOverride === "string") coord.systemPromptOverride = c.systemPromptOverride;
38587
+ if (typeof c.systemPromptAppend === "string") coord.systemPromptAppend = c.systemPromptAppend;
38588
+ if (Number.isFinite(Number(c.maxPromptChars))) coord.maxPromptChars = Number(c.maxPromptChars);
38589
+ config2.coordinator = coord;
38590
+ } else {
38591
+ errors.push("coordinator must be an object when provided");
38592
+ }
38593
+ }
38594
+ if (parsed.operatingNotes !== void 0) {
38595
+ if (Array.isArray(parsed.operatingNotes)) {
38596
+ const notes = parsed.operatingNotes.map(normalizeOperatingNote).filter((n) => n !== null);
38597
+ if (notes.length) config2.operatingNotes = notes;
38598
+ } else {
38599
+ errors.push("operatingNotes must be an array when provided");
38600
+ }
38601
+ }
38602
+ if (parsed.limits !== void 0) {
38603
+ if (isRecord3(parsed.limits)) {
38604
+ const limits = {};
38605
+ if (Number.isFinite(Number(parsed.limits.maxNoteChars))) limits.maxNoteChars = Number(parsed.limits.maxNoteChars);
38606
+ if (Number.isFinite(Number(parsed.limits.maxNotes))) limits.maxNotes = Number(parsed.limits.maxNotes);
38607
+ if (Object.keys(limits).length) config2.limits = limits;
38608
+ } else {
38609
+ errors.push("limits must be an object when provided");
38610
+ }
38611
+ }
38612
+ return { valid: true, config: config2, errors };
38613
+ }
38614
+ function loadRepoMeshJsonConfig(workspace) {
38615
+ const bases = [];
38616
+ const ws = typeof workspace === "string" ? workspace.trim() : "";
38617
+ if (ws) bases.push(ws);
38618
+ let cwd = "";
38619
+ try {
38620
+ cwd = process.cwd();
38621
+ } catch {
38622
+ }
38623
+ if (cwd && cwd !== ws) bases.push(cwd);
38624
+ for (const base of bases) {
38625
+ for (const relative5 of MESH_JSON_CONFIG_LOCATIONS) {
38626
+ const configPath = (0, import_path9.join)(base, relative5);
38627
+ if (!(0, import_fs10.existsSync)(configPath)) continue;
38628
+ try {
38629
+ const parsed = parseConfigText4(configPath, (0, import_fs10.readFileSync)(configPath, "utf-8"));
38630
+ const result = normalizeRepoMeshDeclarativeConfig(parsed);
38631
+ if (!result.valid || !result.config) {
38632
+ return { source: relative5, sourceType: "invalid", path: configPath, error: result.errors.join("; ") };
38633
+ }
38634
+ return { config: result.config, source: relative5, sourceType: "repo_file", path: configPath };
38635
+ } catch (error48) {
38636
+ return { source: relative5, sourceType: "invalid", path: configPath, error: error48?.message || String(error48) };
38637
+ }
38638
+ }
38639
+ }
38640
+ return {
38641
+ source: "unavailable",
38642
+ sourceType: "unavailable",
38643
+ error: `No repo mesh config found. Checked: ${MESH_JSON_CONFIG_LOCATIONS.join(", ")}`
38644
+ };
38645
+ }
38646
+ function mergeEffectiveCoordinatorConfig(repoCoord, localCoord) {
38647
+ const out = { ...localCoord || {} };
38648
+ const localOverride = localCoord?.systemPromptOverride?.trim();
38649
+ const repoOverride = repoCoord?.systemPromptOverride?.trim();
38650
+ if (localOverride) {
38651
+ out.systemPromptOverride = localCoord.systemPromptOverride;
38652
+ } else if (repoOverride) {
38653
+ out.systemPromptOverride = repoCoord.systemPromptOverride;
38654
+ } else {
38655
+ delete out.systemPromptOverride;
38656
+ }
38657
+ const repoAppend = repoCoord?.systemPromptAppend?.trim() ? repoCoord.systemPromptAppend.trim() : "";
38658
+ const localAppendRaw = localCoord?.systemPromptAppend ?? localCoord?.systemPromptSuffix;
38659
+ const localAppend = localAppendRaw?.trim() ? localAppendRaw.trim() : "";
38660
+ const stacked = [repoAppend, localAppend].filter(Boolean).join("\n\n");
38661
+ if (stacked) {
38662
+ out.systemPromptAppend = stacked;
38663
+ delete out.systemPromptSuffix;
38664
+ }
38665
+ return out;
38666
+ }
38667
+ function mergeEffectiveOperatingNotes(repoNotes, ledgerNotes) {
38668
+ const usable = (notes) => Array.isArray(notes) ? notes.filter((n) => n && typeof n.text === "string" && n.text.trim()) : [];
38669
+ const repo = usable(repoNotes);
38670
+ const ledger = usable(ledgerNotes);
38671
+ const ledgerTexts = new Set(ledger.map((n) => n.text.trim()));
38672
+ const repoKept = repo.filter((n) => !ledgerTexts.has(n.text.trim()));
38673
+ const merged = [...repoKept, ...ledger];
38674
+ return merged.length ? merged : void 0;
38675
+ }
38676
+ function applyRepoMeshConfig(mesh, repoConfig) {
38677
+ if (!repoConfig) return mesh;
38678
+ return {
38679
+ ...mesh,
38680
+ coordinator: mergeEffectiveCoordinatorConfig(repoConfig.coordinator, mesh.coordinator)
38681
+ };
38682
+ }
38683
+ function buildMeshJsonConfigScaffold(mesh) {
38684
+ const scaffold = { version: 1 };
38685
+ const coord = {};
38686
+ const override = mesh.coordinator?.systemPromptOverride;
38687
+ if (typeof override === "string" && override.trim()) coord.systemPromptOverride = override;
38688
+ const append = mesh.coordinator?.systemPromptAppend ?? mesh.coordinator?.systemPromptSuffix;
38689
+ if (typeof append === "string" && append.trim()) coord.systemPromptAppend = append;
38690
+ if (Object.keys(coord).length) scaffold.coordinator = coord;
38691
+ return scaffold;
38692
+ }
38693
+ function serializeMeshJsonConfigScaffold(config2) {
38694
+ return JSON.stringify(config2, null, 2);
38695
+ }
38696
+ var import_fs10;
38697
+ var import_path9;
38698
+ var yaml4;
38699
+ var MESH_JSON_CONFIG_LOCATIONS;
38700
+ var MESH_JSON_CONFIG_SCHEMA;
38701
+ var init_mesh_json_config = __esm2({
38702
+ "src/config/mesh-json-config.ts"() {
38703
+ "use strict";
38704
+ import_fs10 = require("fs");
38705
+ import_path9 = require("path");
38706
+ yaml4 = __toESM2(require_js_yaml());
38707
+ MESH_JSON_CONFIG_LOCATIONS = [
38708
+ ".adhdev/mesh.json",
38709
+ ".adhdev/mesh.yaml",
38710
+ ".adhdev/mesh.yml"
38711
+ ];
38712
+ MESH_JSON_CONFIG_SCHEMA = {
38713
+ $schema: "https://json-schema.org/draft/2020-12/schema",
38714
+ title: "ADHDev Repo Mesh Declarative Config",
38715
+ type: "object",
38716
+ additionalProperties: false,
38717
+ required: ["version"],
38718
+ properties: {
38719
+ version: { const: 1 },
38720
+ coordinator: {
38721
+ type: "object",
38722
+ additionalProperties: false,
38723
+ properties: {
38724
+ systemPromptOverride: { type: "string" },
38725
+ systemPromptAppend: { type: "string" },
38726
+ maxPromptChars: { type: "number", minimum: 1 }
38727
+ }
38728
+ },
38729
+ operatingNotes: {
38730
+ type: "array",
38731
+ maxItems: 200,
38732
+ items: {
38733
+ type: "object",
38734
+ additionalProperties: false,
38735
+ required: ["text"],
38736
+ properties: {
38737
+ text: { type: "string", minLength: 1 },
38738
+ category: { enum: ["provider_quirk", "pattern_to_avoid", "recovery_lesson"] },
38739
+ createdAt: { type: "string" },
38740
+ sourceCoordinator: { type: "string" }
38741
+ }
38742
+ }
38743
+ },
38744
+ limits: {
38745
+ type: "object",
38746
+ additionalProperties: false,
38747
+ properties: {
38748
+ maxNoteChars: { type: "number", minimum: 1 },
38749
+ maxNotes: { type: "number", minimum: 1 }
38750
+ }
38751
+ }
38752
+ }
38753
+ };
38754
+ }
38755
+ });
38494
38756
  async function fastForwardMeshNode(args) {
38495
38757
  const workspace = typeof args.workspace === "string" ? args.workspace.trim() : "";
38496
38758
  const nodeId = normalizeOptionalString(args.nodeId);
@@ -39953,9 +40215,9 @@ Next step: ${nextStep}`;
39953
40215
  const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
39954
40216
  if (coordinatorDaemonId) {
39955
40217
  const safeDaemon = coordinatorDaemonId.replace(/[^a-zA-Z0-9_-]/g, "_");
39956
- return (0, import_path9.join)(getLedgerDir(), `${safe}-${safeDaemon}.pending-events.jsonl`);
40218
+ return (0, import_path10.join)(getLedgerDir(), `${safe}-${safeDaemon}.pending-events.jsonl`);
39957
40219
  }
39958
- return (0, import_path9.join)(getLedgerDir(), `${safe}.pending-events.jsonl`);
40220
+ return (0, import_path10.join)(getLedgerDir(), `${safe}.pending-events.jsonl`);
39959
40221
  }
39960
40222
  function readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId) {
39961
40223
  if (!meshId) return [];
@@ -39964,9 +40226,9 @@ Next step: ${nextStep}`;
39964
40226
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
39965
40227
  const events = [];
39966
40228
  for (const path43 of paths) {
39967
- if (!(0, import_fs10.existsSync)(path43)) continue;
40229
+ if (!(0, import_fs11.existsSync)(path43)) continue;
39968
40230
  try {
39969
- const raw = (0, import_fs10.readFileSync)(path43, "utf-8");
40231
+ const raw = (0, import_fs11.readFileSync)(path43, "utf-8");
39970
40232
  const parsed = raw.split("\n").filter(Boolean).flatMap((line) => {
39971
40233
  try {
39972
40234
  return [JSON.parse(line)];
@@ -40041,9 +40303,9 @@ Next step: ${nextStep}`;
40041
40303
  }
40042
40304
  function trimPendingEventsIfNeeded(path43) {
40043
40305
  try {
40044
- if (!(0, import_fs10.existsSync)(path43)) return;
40045
- if ((0, import_fs10.statSync)(path43).size <= MAX_PENDING_EVENTS_BYTES) return;
40046
- const lines = (0, import_fs10.readFileSync)(path43, "utf-8").split("\n").filter(Boolean);
40306
+ if (!(0, import_fs11.existsSync)(path43)) return;
40307
+ if ((0, import_fs11.statSync)(path43).size <= MAX_PENDING_EVENTS_BYTES) return;
40308
+ const lines = (0, import_fs11.readFileSync)(path43, "utf-8").split("\n").filter(Boolean);
40047
40309
  if (lines.length <= MAX_PENDING_EVENTS_KEEP) return;
40048
40310
  const dropped = lines.slice(0, lines.length - MAX_PENDING_EVENTS_KEEP);
40049
40311
  for (const line of dropped) {
@@ -40076,7 +40338,7 @@ Next step: ${nextStep}`;
40076
40338
  LOG2.warn("MeshEvents", `Failed to ledger-record trim-dropped ${event.event} for mesh ${event.meshId}: ${e?.message || e}`);
40077
40339
  }
40078
40340
  }
40079
- (0, import_fs10.writeFileSync)(path43, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
40341
+ (0, import_fs11.writeFileSync)(path43, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
40080
40342
  } catch {
40081
40343
  }
40082
40344
  }
@@ -40108,7 +40370,7 @@ Next step: ${nextStep}`;
40108
40370
  try {
40109
40371
  const path43 = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
40110
40372
  trimPendingEventsIfNeeded(path43);
40111
- (0, import_fs10.appendFileSync)(path43, JSON.stringify(event) + "\n", "utf-8");
40373
+ (0, import_fs11.appendFileSync)(path43, JSON.stringify(event) + "\n", "utf-8");
40112
40374
  } catch (e) {
40113
40375
  if (!sqliteOk) throw e;
40114
40376
  LOG2.warn("MeshEvents", `JSONL append failed for mesh ${event.meshId}; SQLite holds the event: ${e?.message || e}`);
@@ -40122,20 +40384,20 @@ Next step: ${nextStep}`;
40122
40384
  function atomicDrainFile(path43) {
40123
40385
  const tmpPath = `${path43}.draining`;
40124
40386
  try {
40125
- (0, import_fs10.renameSync)(path43, tmpPath);
40387
+ (0, import_fs11.renameSync)(path43, tmpPath);
40126
40388
  } catch {
40127
40389
  return null;
40128
40390
  }
40129
40391
  try {
40130
- const content = (0, import_fs10.readFileSync)(tmpPath, "utf-8");
40392
+ const content = (0, import_fs11.readFileSync)(tmpPath, "utf-8");
40131
40393
  try {
40132
- (0, import_fs10.unlinkSync)(tmpPath);
40394
+ (0, import_fs11.unlinkSync)(tmpPath);
40133
40395
  } catch {
40134
40396
  }
40135
40397
  return content;
40136
40398
  } catch {
40137
40399
  try {
40138
- (0, import_fs10.unlinkSync)(tmpPath);
40400
+ (0, import_fs11.unlinkSync)(tmpPath);
40139
40401
  } catch {
40140
40402
  }
40141
40403
  return null;
@@ -40144,16 +40406,16 @@ Next step: ${nextStep}`;
40144
40406
  function selectiveDrainFile(path43, predicate) {
40145
40407
  const tmpPath = `${path43}.draining`;
40146
40408
  try {
40147
- (0, import_fs10.renameSync)(path43, tmpPath);
40409
+ (0, import_fs11.renameSync)(path43, tmpPath);
40148
40410
  } catch {
40149
40411
  return [];
40150
40412
  }
40151
40413
  let content;
40152
40414
  try {
40153
- content = (0, import_fs10.readFileSync)(tmpPath, "utf-8");
40415
+ content = (0, import_fs11.readFileSync)(tmpPath, "utf-8");
40154
40416
  } catch {
40155
40417
  try {
40156
- (0, import_fs10.unlinkSync)(tmpPath);
40418
+ (0, import_fs11.unlinkSync)(tmpPath);
40157
40419
  } catch {
40158
40420
  }
40159
40421
  return [];
@@ -40176,12 +40438,12 @@ Next step: ${nextStep}`;
40176
40438
  }
40177
40439
  try {
40178
40440
  if (keptLines.length > 0) {
40179
- (0, import_fs10.writeFileSync)(path43, keptLines.join("\n") + "\n", "utf-8");
40441
+ (0, import_fs11.writeFileSync)(path43, keptLines.join("\n") + "\n", "utf-8");
40180
40442
  }
40181
- (0, import_fs10.unlinkSync)(tmpPath);
40443
+ (0, import_fs11.unlinkSync)(tmpPath);
40182
40444
  } catch {
40183
40445
  try {
40184
- if ((0, import_fs10.existsSync)(tmpPath) && !(0, import_fs10.existsSync)(path43)) (0, import_fs10.renameSync)(tmpPath, path43);
40446
+ if ((0, import_fs11.existsSync)(tmpPath) && !(0, import_fs11.existsSync)(path43)) (0, import_fs11.renameSync)(tmpPath, path43);
40185
40447
  } catch {
40186
40448
  }
40187
40449
  return [];
@@ -40276,14 +40538,14 @@ Next step: ${nextStep}`;
40276
40538
  }
40277
40539
  const paths = coordinatorDaemonId ? [getPendingEventsPath(meshId, coordinatorDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
40278
40540
  for (const path43 of paths) {
40279
- if ((0, import_fs10.existsSync)(path43)) try {
40280
- (0, import_fs10.unlinkSync)(path43);
40541
+ if ((0, import_fs11.existsSync)(path43)) try {
40542
+ (0, import_fs11.unlinkSync)(path43);
40281
40543
  } catch {
40282
40544
  }
40283
40545
  }
40284
40546
  }
40285
- var import_fs10;
40286
- var import_path9;
40547
+ var import_fs11;
40548
+ var import_path10;
40287
40549
  var import_crypto8;
40288
40550
  var REFINE_TERMINAL_EVENTS;
40289
40551
  var TERMINAL_COMPLETION_EVENTS;
@@ -40292,8 +40554,8 @@ Next step: ${nextStep}`;
40292
40554
  var init_mesh_events_pending = __esm2({
40293
40555
  "src/mesh/mesh-events-pending.ts"() {
40294
40556
  "use strict";
40295
- import_fs10 = require("fs");
40296
- import_path9 = require("path");
40557
+ import_fs11 = require("fs");
40558
+ import_path10 = require("path");
40297
40559
  import_crypto8 = require("crypto");
40298
40560
  init_logger();
40299
40561
  init_mesh_ledger();
@@ -41070,7 +41332,7 @@ Next step: ${nextStep}`;
41070
41332
  if (isExplicitCommandPath(trimmed)) {
41071
41333
  const expanded = expandHome(trimmed);
41072
41334
  const candidate = path12.isAbsolute(expanded) ? expanded : path12.resolve(expanded);
41073
- return (0, import_fs11.existsSync)(candidate) ? candidate : null;
41335
+ return (0, import_fs12.existsSync)(candidate) ? candidate : null;
41074
41336
  }
41075
41337
  return null;
41076
41338
  }
@@ -41080,7 +41342,7 @@ Next step: ${nextStep}`;
41080
41342
  const whichResult = await execAsync(`${whichCmd} ${shellQuote(command)}`);
41081
41343
  if (whichResult) return whichResult.split("\n")[0];
41082
41344
  const resolved = findBinary(command);
41083
- if (path12.isAbsolute(resolved) && (0, import_fs11.existsSync)(resolved)) return resolved;
41345
+ if (path12.isAbsolute(resolved) && (0, import_fs12.existsSync)(resolved)) return resolved;
41084
41346
  return null;
41085
41347
  }
41086
41348
  function execAsync(cmd, timeoutMs = 5e3) {
@@ -41178,14 +41440,14 @@ Next step: ${nextStep}`;
41178
41440
  var import_child_process2;
41179
41441
  var os62;
41180
41442
  var path12;
41181
- var import_fs11;
41443
+ var import_fs12;
41182
41444
  var init_cli_detector = __esm2({
41183
41445
  "src/detection/cli-detector.ts"() {
41184
41446
  "use strict";
41185
41447
  import_child_process2 = require("child_process");
41186
41448
  os62 = __toESM2(require("os"));
41187
41449
  path12 = __toESM2(require("path"));
41188
- import_fs11 = require("fs");
41450
+ import_fs12 = require("fs");
41189
41451
  init_provider_cli_shared();
41190
41452
  }
41191
41453
  });
@@ -41301,348 +41563,6 @@ Next step: ${nextStep}`;
41301
41563
  "use strict";
41302
41564
  }
41303
41565
  });
41304
- var mesh_json_config_exports = {};
41305
- __export2(mesh_json_config_exports, {
41306
- MESH_JSON_CONFIG_LOCATIONS: () => MESH_JSON_CONFIG_LOCATIONS,
41307
- MESH_JSON_CONFIG_SCHEMA: () => MESH_JSON_CONFIG_SCHEMA,
41308
- __resetMeshJsonConfigCacheForTests: () => __resetMeshJsonConfigCacheForTests,
41309
- applyRepoMeshConfig: () => applyRepoMeshConfig,
41310
- buildMeshJsonConfigScaffold: () => buildMeshJsonConfigScaffold,
41311
- diffPolicyFromDefault: () => diffPolicyFromDefault,
41312
- loadMeshJsonConfig: () => loadMeshJsonConfig,
41313
- loadRepoMeshJsonConfig: () => loadRepoMeshJsonConfig,
41314
- mergeEffectiveCoordinatorConfig: () => mergeEffectiveCoordinatorConfig,
41315
- mergeEffectiveMeshPolicy: () => mergeEffectiveMeshPolicy,
41316
- mergeEffectiveOperatingNotes: () => mergeEffectiveOperatingNotes,
41317
- normalizeRepoMeshDeclarativeConfig: () => normalizeRepoMeshDeclarativeConfig,
41318
- serializeMeshJsonConfigScaffold: () => serializeMeshJsonConfigScaffold,
41319
- validateMeshJsonConfig: () => validateMeshJsonConfig
41320
- });
41321
- function isRecord3(value) {
41322
- return !!value && typeof value === "object" && !Array.isArray(value);
41323
- }
41324
- function parseConfigText4(path43, text) {
41325
- if (/\.json$/i.test(path43)) return JSON.parse(text);
41326
- return yaml4.load(text);
41327
- }
41328
- function normalizeOperatingNote(value) {
41329
- if (!isRecord3(value)) return null;
41330
- const text = typeof value.text === "string" ? value.text.trim() : "";
41331
- if (!text) return null;
41332
- const category = value.category === "provider_quirk" || value.category === "pattern_to_avoid" || value.category === "recovery_lesson" ? value.category : void 0;
41333
- return {
41334
- text,
41335
- ...category ? { category } : {},
41336
- ...typeof value.createdAt === "string" ? { createdAt: value.createdAt } : {},
41337
- ...typeof value.sourceCoordinator === "string" ? { sourceCoordinator: value.sourceCoordinator } : {}
41338
- };
41339
- }
41340
- function normalizeRepoMeshDeclarativeConfig(parsed) {
41341
- const errors = [];
41342
- if (!isRecord3(parsed)) return { valid: false, errors: ["config must be an object"] };
41343
- if (parsed.version !== 1) {
41344
- return { valid: false, errors: [`version must be 1 (got ${JSON.stringify(parsed.version)})`] };
41345
- }
41346
- const config2 = { version: 1 };
41347
- if (parsed.policy !== void 0) {
41348
- if (isRecord3(parsed.policy)) {
41349
- config2.policy = parsed.policy;
41350
- } else {
41351
- errors.push("policy must be an object when provided");
41352
- }
41353
- }
41354
- if (parsed.coordinator !== void 0) {
41355
- if (isRecord3(parsed.coordinator)) {
41356
- const coord = {};
41357
- const c = parsed.coordinator;
41358
- if (typeof c.systemPromptOverride === "string") coord.systemPromptOverride = c.systemPromptOverride;
41359
- if (typeof c.systemPromptAppend === "string") coord.systemPromptAppend = c.systemPromptAppend;
41360
- if (Number.isFinite(Number(c.maxPromptChars))) coord.maxPromptChars = Number(c.maxPromptChars);
41361
- config2.coordinator = coord;
41362
- } else {
41363
- errors.push("coordinator must be an object when provided");
41364
- }
41365
- }
41366
- if (parsed.operatingNotes !== void 0) {
41367
- if (Array.isArray(parsed.operatingNotes)) {
41368
- const notes = parsed.operatingNotes.map(normalizeOperatingNote).filter((n) => n !== null);
41369
- if (notes.length) config2.operatingNotes = notes;
41370
- } else {
41371
- errors.push("operatingNotes must be an array when provided");
41372
- }
41373
- }
41374
- if (parsed.limits !== void 0) {
41375
- if (isRecord3(parsed.limits)) {
41376
- const limits = {};
41377
- if (Number.isFinite(Number(parsed.limits.maxNoteChars))) limits.maxNoteChars = Number(parsed.limits.maxNoteChars);
41378
- if (Number.isFinite(Number(parsed.limits.maxNotes))) limits.maxNotes = Number(parsed.limits.maxNotes);
41379
- if (Object.keys(limits).length) config2.limits = limits;
41380
- } else {
41381
- errors.push("limits must be an object when provided");
41382
- }
41383
- }
41384
- return { valid: true, config: config2, errors };
41385
- }
41386
- function loadRepoMeshJsonConfig(workspace) {
41387
- const bases = [];
41388
- const ws = typeof workspace === "string" ? workspace.trim() : "";
41389
- if (ws) bases.push(ws);
41390
- let cwd = "";
41391
- try {
41392
- cwd = process.cwd();
41393
- } catch {
41394
- }
41395
- if (cwd && cwd !== ws) bases.push(cwd);
41396
- for (const base of bases) {
41397
- for (const relative5 of MESH_JSON_CONFIG_LOCATIONS) {
41398
- const configPath = (0, import_path10.join)(base, relative5);
41399
- if (!(0, import_fs12.existsSync)(configPath)) continue;
41400
- try {
41401
- const parsed = parseConfigText4(configPath, (0, import_fs12.readFileSync)(configPath, "utf-8"));
41402
- const result = normalizeRepoMeshDeclarativeConfig(parsed);
41403
- if (!result.valid || !result.config) {
41404
- return { source: relative5, sourceType: "invalid", path: configPath, error: result.errors.join("; ") };
41405
- }
41406
- return { config: result.config, source: relative5, sourceType: "repo_file", path: configPath };
41407
- } catch (error48) {
41408
- return { source: relative5, sourceType: "invalid", path: configPath, error: error48?.message || String(error48) };
41409
- }
41410
- }
41411
- }
41412
- return {
41413
- source: "unavailable",
41414
- sourceType: "unavailable",
41415
- error: `No repo mesh config found. Checked: ${MESH_JSON_CONFIG_LOCATIONS.join(", ")}`
41416
- };
41417
- }
41418
- function deepEqual(a, b) {
41419
- if (a === b) return true;
41420
- try {
41421
- return JSON.stringify(a) === JSON.stringify(b);
41422
- } catch {
41423
- return false;
41424
- }
41425
- }
41426
- function diffPolicyFromDefault(local) {
41427
- if (!local || typeof local !== "object") return {};
41428
- const out = {};
41429
- const def = mergeAndNormalizePolicy(void 0, void 0);
41430
- for (const [key, value] of Object.entries(local)) {
41431
- if (value === void 0) continue;
41432
- if (!deepEqual(value, def[key])) out[key] = value;
41433
- }
41434
- return out;
41435
- }
41436
- function mergeEffectiveMeshPolicy(repoPolicy, localPolicy) {
41437
- const repoMerged = mergeAndNormalizePolicy(void 0, repoPolicy);
41438
- const localOverrides = diffPolicyFromDefault(localPolicy);
41439
- return mergeAndNormalizePolicy(repoMerged, localOverrides);
41440
- }
41441
- function mergeEffectiveCoordinatorConfig(repoCoord, localCoord) {
41442
- const out = { ...localCoord || {} };
41443
- const localOverride = localCoord?.systemPromptOverride?.trim();
41444
- const repoOverride = repoCoord?.systemPromptOverride?.trim();
41445
- if (localOverride) {
41446
- out.systemPromptOverride = localCoord.systemPromptOverride;
41447
- } else if (repoOverride) {
41448
- out.systemPromptOverride = repoCoord.systemPromptOverride;
41449
- } else {
41450
- delete out.systemPromptOverride;
41451
- }
41452
- const repoAppend = repoCoord?.systemPromptAppend?.trim() ? repoCoord.systemPromptAppend.trim() : "";
41453
- const localAppendRaw = localCoord?.systemPromptAppend ?? localCoord?.systemPromptSuffix;
41454
- const localAppend = localAppendRaw?.trim() ? localAppendRaw.trim() : "";
41455
- const stacked = [repoAppend, localAppend].filter(Boolean).join("\n\n");
41456
- if (stacked) {
41457
- out.systemPromptAppend = stacked;
41458
- delete out.systemPromptSuffix;
41459
- }
41460
- return out;
41461
- }
41462
- function mergeEffectiveOperatingNotes(repoNotes, ledgerNotes) {
41463
- const usable = (notes) => Array.isArray(notes) ? notes.filter((n) => n && typeof n.text === "string" && n.text.trim()) : [];
41464
- const repo = usable(repoNotes);
41465
- const ledger = usable(ledgerNotes);
41466
- const ledgerTexts = new Set(ledger.map((n) => n.text.trim()));
41467
- const repoKept = repo.filter((n) => !ledgerTexts.has(n.text.trim()));
41468
- const merged = [...repoKept, ...ledger];
41469
- return merged.length ? merged : void 0;
41470
- }
41471
- function applyRepoMeshConfig(mesh, repoConfig) {
41472
- if (!repoConfig) return mesh;
41473
- return {
41474
- ...mesh,
41475
- policy: mergeEffectiveMeshPolicy(repoConfig.policy, mesh.policy),
41476
- coordinator: mergeEffectiveCoordinatorConfig(repoConfig.coordinator, mesh.coordinator)
41477
- };
41478
- }
41479
- function buildMeshJsonConfigScaffold(mesh) {
41480
- const scaffold = {
41481
- version: 1,
41482
- policy: mergeAndNormalizePolicy(void 0, mesh.policy)
41483
- };
41484
- const coord = {};
41485
- const override = mesh.coordinator?.systemPromptOverride;
41486
- if (typeof override === "string" && override.trim()) coord.systemPromptOverride = override;
41487
- const append = mesh.coordinator?.systemPromptAppend ?? mesh.coordinator?.systemPromptSuffix;
41488
- if (typeof append === "string" && append.trim()) coord.systemPromptAppend = append;
41489
- if (Object.keys(coord).length) scaffold.coordinator = coord;
41490
- return scaffold;
41491
- }
41492
- function serializeMeshJsonConfigScaffold(config2) {
41493
- return JSON.stringify(config2, null, 2);
41494
- }
41495
- function validateMeshJsonConfig(raw, source = "inline") {
41496
- const errors = [];
41497
- if (!isRecord3(raw)) {
41498
- return { valid: false, errors: [`${source}: config must be an object`] };
41499
- }
41500
- const config2 = {};
41501
- const policy = raw.policy;
41502
- const schedulingRaw = isRecord3(policy) ? policy.scheduling : void 0;
41503
- if (schedulingRaw !== void 0) {
41504
- if (!isRecord3(schedulingRaw)) {
41505
- errors.push("policy.scheduling must be an object");
41506
- } else {
41507
- const scheduling = {};
41508
- if (schedulingRaw.distribution !== void 0) {
41509
- if (typeof schedulingRaw.distribution !== "string" || !["spread", "in_order"].includes(schedulingRaw.distribution.trim())) {
41510
- errors.push("policy.scheduling.distribution must be 'spread' or 'in_order'");
41511
- } else {
41512
- scheduling.distribution = normalizeMeshDistribution(schedulingRaw.distribution);
41513
- }
41514
- }
41515
- if (schedulingRaw.maxParallel !== void 0) {
41516
- const n = Number(schedulingRaw.maxParallel);
41517
- if (!Number.isFinite(n) || n < MESH_MAX_PARALLEL_TASKS_MIN || n > MESH_MAX_PARALLEL_TASKS_MAX) {
41518
- errors.push(`policy.scheduling.maxParallel must be a number in [${MESH_MAX_PARALLEL_TASKS_MIN}, ${MESH_MAX_PARALLEL_TASKS_MAX}]`);
41519
- } else {
41520
- scheduling.maxParallel = Math.floor(n);
41521
- }
41522
- }
41523
- if (schedulingRaw.readonlyMultiplier !== void 0) {
41524
- const n = Number(schedulingRaw.readonlyMultiplier);
41525
- if (!Number.isFinite(n) || n < 1) {
41526
- errors.push("policy.scheduling.readonlyMultiplier must be a number >= 1");
41527
- } else {
41528
- scheduling.readonlyMultiplier = Math.floor(n);
41529
- }
41530
- }
41531
- for (const key of Object.keys(schedulingRaw)) {
41532
- if (!["distribution", "maxParallel", "readonlyMultiplier"].includes(key)) {
41533
- errors.push(`policy.scheduling.${key} is not a recognized field`);
41534
- }
41535
- }
41536
- if (Object.keys(scheduling).length) config2.scheduling = scheduling;
41537
- }
41538
- }
41539
- return { valid: errors.length === 0, errors, config: errors.length === 0 ? config2 : void 0 };
41540
- }
41541
- function loadMeshJsonConfig(repoRoot) {
41542
- if (!repoRoot) {
41543
- return { source: "unavailable", sourceType: "unavailable", error: "no repo root", sourceKey: "unavailable" };
41544
- }
41545
- for (const relative5 of MESH_JSON_CONFIG_LOCATIONS) {
41546
- const configPath = (0, import_path10.join)(repoRoot, relative5);
41547
- if (!(0, import_fs12.existsSync)(configPath)) continue;
41548
- let mtimeMs = 0;
41549
- try {
41550
- mtimeMs = (0, import_fs12.statSync)(configPath).mtimeMs;
41551
- } catch {
41552
- mtimeMs = 0;
41553
- }
41554
- const cacheKey = configPath;
41555
- const sourceKey = `file:${configPath}:${mtimeMs}`;
41556
- const cached3 = cache.get(cacheKey);
41557
- if (cached3 && cached3.sourceKey === sourceKey) return cached3.result;
41558
- let result;
41559
- try {
41560
- const text = (0, import_fs12.readFileSync)(configPath, "utf-8");
41561
- const parsed = parseConfigText4(configPath, text);
41562
- const validation = validateMeshJsonConfig(parsed, relative5);
41563
- result = validation.valid ? { config: validation.config, source: relative5, sourceType: "repo_file", path: configPath, sourceKey } : { source: relative5, sourceType: "invalid", path: configPath, error: validation.errors.join("; "), sourceKey: `invalid:${configPath}:${mtimeMs}` };
41564
- } catch (error48) {
41565
- result = { source: relative5, sourceType: "invalid", path: configPath, error: error48?.message || String(error48), sourceKey: `error:${configPath}` };
41566
- }
41567
- cache.set(cacheKey, { sourceKey: result.sourceKey, result });
41568
- return result;
41569
- }
41570
- return {
41571
- source: "unavailable",
41572
- sourceType: "unavailable",
41573
- error: `No .adhdev/mesh config found. Checked: ${MESH_JSON_CONFIG_LOCATIONS.join(", ")}`,
41574
- sourceKey: "unavailable"
41575
- };
41576
- }
41577
- function __resetMeshJsonConfigCacheForTests() {
41578
- cache.clear();
41579
- }
41580
- var import_fs12;
41581
- var import_path10;
41582
- var yaml4;
41583
- var MESH_JSON_CONFIG_LOCATIONS;
41584
- var MESH_JSON_CONFIG_SCHEMA;
41585
- var cache;
41586
- var init_mesh_json_config = __esm2({
41587
- "src/config/mesh-json-config.ts"() {
41588
- "use strict";
41589
- import_fs12 = require("fs");
41590
- import_path10 = require("path");
41591
- yaml4 = __toESM2(require_js_yaml());
41592
- init_repo_mesh_types();
41593
- MESH_JSON_CONFIG_LOCATIONS = [
41594
- ".adhdev/mesh.json",
41595
- ".adhdev/mesh.yaml",
41596
- ".adhdev/mesh.yml"
41597
- ];
41598
- MESH_JSON_CONFIG_SCHEMA = {
41599
- $schema: "https://json-schema.org/draft/2020-12/schema",
41600
- title: "ADHDev Repo Mesh Declarative Config",
41601
- type: "object",
41602
- additionalProperties: false,
41603
- required: ["version"],
41604
- properties: {
41605
- version: { const: 1 },
41606
- // policy is validated/normalized through mergeAndNormalizePolicy at merge
41607
- // time; the schema here only asserts it is an object.
41608
- policy: { type: "object" },
41609
- coordinator: {
41610
- type: "object",
41611
- additionalProperties: false,
41612
- properties: {
41613
- systemPromptOverride: { type: "string" },
41614
- systemPromptAppend: { type: "string" },
41615
- maxPromptChars: { type: "number", minimum: 1 }
41616
- }
41617
- },
41618
- operatingNotes: {
41619
- type: "array",
41620
- maxItems: 200,
41621
- items: {
41622
- type: "object",
41623
- additionalProperties: false,
41624
- required: ["text"],
41625
- properties: {
41626
- text: { type: "string", minLength: 1 },
41627
- category: { enum: ["provider_quirk", "pattern_to_avoid", "recovery_lesson"] },
41628
- createdAt: { type: "string" },
41629
- sourceCoordinator: { type: "string" }
41630
- }
41631
- }
41632
- },
41633
- limits: {
41634
- type: "object",
41635
- additionalProperties: false,
41636
- properties: {
41637
- maxNoteChars: { type: "number", minimum: 1 },
41638
- maxNotes: { type: "number", minimum: 1 }
41639
- }
41640
- }
41641
- }
41642
- };
41643
- cache = /* @__PURE__ */ new Map();
41644
- }
41645
- });
41646
41566
  function __resetIdleAutoFastForwardForTests() {
41647
41567
  idleAutoFastForwardLastAttempt.clear();
41648
41568
  }
@@ -42057,26 +41977,7 @@ Next step: ${nextStep}`;
42057
41977
  function nodeActiveLoad(meshId, nodeId) {
42058
41978
  return MeshRuntimeStore.getInstance().nodeActiveAssignmentCount(meshId, nodeId);
42059
41979
  }
42060
- function resolveMeshRepoRootForScheduling(mesh) {
42061
- const nodes = Array.isArray(mesh?.nodes) ? mesh.nodes : [];
42062
- const pickRoot = (n) => readNonEmptyString2(n?.repoRoot) || readNonEmptyString2(n?.workspace);
42063
- const base = nodes.find((n) => n?.isLocalWorktree !== true && pickRoot(n));
42064
- if (base) return pickRoot(base);
42065
- const anyNode = nodes.find((n) => pickRoot(n));
42066
- return anyNode ? pickRoot(anyNode) : "";
42067
- }
42068
- function resolveMeshSchedulingOverride(mesh) {
42069
- const repoRoot = resolveMeshRepoRootForScheduling(mesh);
42070
- if (!repoRoot) return void 0;
42071
- try {
42072
- return loadMeshJsonConfig(repoRoot).config?.scheduling;
42073
- } catch {
42074
- return void 0;
42075
- }
42076
- }
42077
41980
  function resolveSchedulingStrategy(mesh) {
42078
- const override = resolveMeshSchedulingOverride(mesh);
42079
- if (override?.distribution) return distributionToStrategy(override.distribution);
42080
41981
  return normalizeMeshSchedulingStrategy(mesh?.policy?.schedulingStrategy);
42081
41982
  }
42082
41983
  function orderEligibleNodes(meshId, strategy, nodes, opts) {
@@ -42219,11 +42120,8 @@ Next step: ${nextStep}`;
42219
42120
  const queue = getQueue(meshId);
42220
42121
  const pending = queue.filter((task) => task.status === "pending");
42221
42122
  if (!pending.length) return false;
42222
- const schedulingOverride = resolveMeshSchedulingOverride(mesh);
42223
- const maxParallelTasks = resolveMaxParallelTasks(
42224
- schedulingOverride?.maxParallel ?? mesh?.policy?.maxParallelTasks
42225
- );
42226
- const maxReadonlyParallelTasks = resolveMaxReadonlyParallelTasks(maxParallelTasks, schedulingOverride?.readonlyMultiplier);
42123
+ const maxParallelTasks = resolveMaxParallelTasks(mesh?.policy?.maxParallelTasks);
42124
+ const maxReadonlyParallelTasks = resolveMaxReadonlyParallelTasks(maxParallelTasks);
42227
42125
  for (const task of pending) {
42228
42126
  const isReadonly = isTaskReadonly(task);
42229
42127
  if (isReadonly) {
@@ -42652,7 +42550,6 @@ Next step: ${nextStep}`;
42652
42550
  init_mesh_event_trace();
42653
42551
  init_mesh_warmup_deadline();
42654
42552
  init_repo_mesh_types();
42655
- init_mesh_json_config();
42656
42553
  init_dist();
42657
42554
  init_mesh_events_stale();
42658
42555
  init_mesh_events_utils();
@@ -44874,11 +44771,11 @@ ${cleanBody}`;
44874
44771
  String(snapshot.messageUpdatedAt)
44875
44772
  ].join("|");
44876
44773
  }
44877
- function shouldEmitRecentReadDebugLog(cache2, snapshot) {
44774
+ function shouldEmitRecentReadDebugLog(cache, snapshot) {
44878
44775
  const nextSignature = buildRecentReadDebugSignature(snapshot);
44879
- const previousSignature = cache2.get(snapshot.sessionId);
44776
+ const previousSignature = cache.get(snapshot.sessionId);
44880
44777
  if (previousSignature === nextSignature) return false;
44881
- cache2.set(snapshot.sessionId, nextSignature);
44778
+ cache.set(snapshot.sessionId, nextSignature);
44882
44779
  return true;
44883
44780
  }
44884
44781
  function buildDetectedIdeInfos(detectedIdes, cdpManagers) {
@@ -53103,6 +53000,7 @@ ${lastSnapshot}`;
53103
53000
  loadMeshCoordinatorRegistry: () => loadMeshCoordinatorRegistry,
53104
53001
  loadMeshRefineConfig: () => loadMeshRefineConfig,
53105
53002
  loadMeshWorktreeBootstrapConfig: () => loadMeshWorktreeBootstrapConfig,
53003
+ loadRepoSettings: () => loadRepoSettings,
53106
53004
  loadState: () => loadState,
53107
53005
  logCommand: () => logCommand,
53108
53006
  machineCoreFromDaemonId: () => machineCoreFromDaemonId,
@@ -54455,6 +54353,25 @@ ${lastSnapshot}`;
54455
54353
  init_coordinator_registry();
54456
54354
  init_refine_config();
54457
54355
  init_worktree_bootstrap_config();
54356
+ init_mesh_json_config();
54357
+ init_refine_config();
54358
+ init_worktree_bootstrap_config();
54359
+ init_change_impact_config();
54360
+ function loadRepoSettings(opts) {
54361
+ const workspace = typeof opts.workspace === "string" ? opts.workspace : "";
54362
+ const mesh = opts.mesh;
54363
+ const repoRoot = typeof opts.repoRoot === "string" && opts.repoRoot ? opts.repoRoot : workspace;
54364
+ const meshJson = loadRepoMeshJsonConfig(workspace);
54365
+ return {
54366
+ coordinator: meshJson.config?.coordinator,
54367
+ operatingNotes: meshJson.config?.operatingNotes,
54368
+ limits: meshJson.config?.limits,
54369
+ meshJson,
54370
+ refine: loadMeshRefineConfig(mesh, workspace),
54371
+ worktreeBootstrap: loadMeshWorktreeBootstrapConfig(mesh, workspace),
54372
+ changeImpact: loadChangeImpactConfig(repoRoot)
54373
+ };
54374
+ }
54458
54375
  init_mesh_ledger();
54459
54376
  init_mesh_fast_forward();
54460
54377
  function lastTimestamp(slice) {
@@ -78269,6 +78186,21 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
78269
78186
  init_worktree_bootstrap_config();
78270
78187
  init_mesh_events();
78271
78188
  init_config();
78189
+ async function decideOssCloneSync(ossCtx, worktreeOssSha, sourceSha, rg) {
78190
+ if (!worktreeOssSha || !sourceSha || worktreeOssSha === sourceSha) return "noop";
78191
+ const isAncestor = async (ancestor, descendant) => {
78192
+ try {
78193
+ await rg(ossCtx, ["merge-base", "--is-ancestor", ancestor, descendant], { timeoutMs: 1e4 });
78194
+ return true;
78195
+ } catch (err) {
78196
+ if (err?.exitCode === 1 || err?.code === 1) return false;
78197
+ throw err;
78198
+ }
78199
+ };
78200
+ if (await isAncestor(sourceSha, worktreeOssSha)) return "skip_rewind";
78201
+ if (await isAncestor(worktreeOssSha, sourceSha)) return "advance";
78202
+ return "skip_diverged";
78203
+ }
78272
78204
  var meshCrudHandlers = {
78273
78205
  list_meshes: async (_ctx, _args) => {
78274
78206
  try {
@@ -78359,7 +78291,8 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
78359
78291
  // entry. This is an export scaffold for the operator to review and commit to
78360
78292
  // the repo, NOT an automatic data migration: nothing is written to disk and
78361
78293
  // meshes.json is untouched. The returned `scaffold` (object) + `scaffoldJson`
78362
- // (2-space text) capture the local policy + coordinator prompt override/append.
78294
+ // (2-space text) capture the coordinator prompt override/append (policy is
78295
+ // machine-local and is intentionally NOT exported into mesh.json).
78363
78296
  export_mesh_json_config: async (_ctx, args) => {
78364
78297
  const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
78365
78298
  if (!meshId) return { success: false, error: "meshId required" };
@@ -78730,7 +78663,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
78730
78663
  }
78731
78664
  };
78732
78665
  const initSubmodules = sourceNode.policy?.initSubmodulesOnClone !== false;
78733
- const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, result.worktreePath);
78666
+ const loadedBootstrap = loadRepoSettings({ workspace: result.worktreePath, mesh }).worktreeBootstrap;
78734
78667
  const runningBootstrapState = {
78735
78668
  status: "running",
78736
78669
  required: loadedBootstrap.config?.required !== false,
@@ -78764,12 +78697,25 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
78764
78697
  const ossCtx = { workspace: `${result.worktreePath}/oss`, repoRoot: `${result.worktreePath}/oss`, isGitRepo: true };
78765
78698
  const worktreeOssHeadOut = await rg(ossCtx, ["rev-parse", "HEAD"], { timeoutMs: 1e4 });
78766
78699
  const worktreeOssSha = (typeof worktreeOssHeadOut === "string" ? worktreeOssHeadOut : worktreeOssHeadOut?.stdout ?? "").trim();
78767
- if (worktreeOssSha !== sourceSha) {
78700
+ if (worktreeOssSha && worktreeOssSha !== sourceSha) {
78768
78701
  await rg(ossCtx, ["fetch", `${sourceWorkspace}/oss`, "HEAD"], { timeoutMs: 6e4 });
78769
- await rg(ossCtx, ["checkout", sourceSha], { timeoutMs: 1e4 });
78770
- await rg(worktreeCtx, ["add", "oss"], { timeoutMs: 1e4 });
78771
- await rg(worktreeCtx, ["commit", "-m", "chore: sync oss to source node HEAD on clone"], { timeoutMs: 1e4 });
78772
- console.log(`[mesh] Synced oss submodule to source HEAD ${sourceSha.slice(0, 8)} in worktree`);
78702
+ let ossAction;
78703
+ try {
78704
+ ossAction = await decideOssCloneSync(ossCtx, worktreeOssSha, sourceSha, rg);
78705
+ } catch (decideErr) {
78706
+ ossAction = "skip_diverged";
78707
+ console.warn(`[mesh] oss submodule sync guard could not resolve ancestry (kept fresh worktree HEAD): ${decideErr?.message ?? decideErr}`);
78708
+ }
78709
+ if (ossAction === "advance") {
78710
+ await rg(ossCtx, ["checkout", sourceSha], { timeoutMs: 1e4 });
78711
+ await rg(worktreeCtx, ["add", "oss"], { timeoutMs: 1e4 });
78712
+ await rg(worktreeCtx, ["commit", "-m", "chore: sync oss to source node HEAD on clone"], { timeoutMs: 1e4 });
78713
+ console.log(`[mesh] Advanced oss submodule to newer source HEAD ${sourceSha.slice(0, 8)} in worktree`);
78714
+ } else if (ossAction === "skip_rewind") {
78715
+ console.warn(`[mesh] Skipped oss submodule rewind on clone: source node oss ${sourceSha.slice(0, 8)} is an ancestor of the fresh worktree oss ${worktreeOssSha.slice(0, 8)} \u2014 kept fresher worktree HEAD`);
78716
+ } else if (ossAction === "skip_diverged") {
78717
+ console.warn(`[mesh] Skipped oss submodule sync on clone: source node oss ${sourceSha.slice(0, 8)} diverged from the fresh worktree oss ${worktreeOssSha.slice(0, 8)} \u2014 kept worktree HEAD (coordinator reconciles)`);
78718
+ }
78773
78719
  }
78774
78720
  }
78775
78721
  } catch (ossErr) {