@adhdev/daemon-core 0.9.82-rc.410 → 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
@@ -36,14 +36,6 @@ function normalizeMeshSchedulingStrategy(value) {
36
36
  const trimmed = value.trim();
37
37
  return MESH_SCHEDULING_STRATEGIES.includes(trimmed) ? trimmed : DEFAULT_MESH_SCHEDULING_STRATEGY;
38
38
  }
39
- function normalizeMeshDistribution(value) {
40
- if (typeof value !== "string") return DEFAULT_MESH_DISTRIBUTION;
41
- const trimmed = value.trim();
42
- return MESH_DISTRIBUTIONS.includes(trimmed) ? trimmed : DEFAULT_MESH_DISTRIBUTION;
43
- }
44
- function distributionToStrategy(distribution) {
45
- return distribution === "spread" ? "least_loaded" : "first_eligible";
46
- }
47
39
  function resolveNodeSchedulingPriority(nodePolicy) {
48
40
  const raw = Number(nodePolicy?.schedulingPriority);
49
41
  return Number.isFinite(raw) ? raw : 0;
@@ -130,7 +122,7 @@ function resolveProviderMaxParallel(nodePolicy, providerType) {
130
122
  }
131
123
  return void 0;
132
124
  }
133
- var MESH_SCHEDULING_STRATEGIES, DEFAULT_MESH_SCHEDULING_STRATEGY, MESH_DISTRIBUTIONS, DEFAULT_MESH_DISTRIBUTION, MESH_CONVERGE_REFINE_TAG, MESH_CONVERGE_FAST_FORWARD_TAG, DEFAULT_MESH_POLICY, SESSION_CLEANUP_MODES, SPAWNED_SESSION_VISIBILITY_MODES, DIRTY_WORKSPACE_BEHAVIORS, MESH_MAX_PARALLEL_TASKS_MIN, MESH_MAX_PARALLEL_TASKS_MAX, DEFAULT_MESH_READONLY_MULTIPLIER;
125
+ var MESH_SCHEDULING_STRATEGIES, DEFAULT_MESH_SCHEDULING_STRATEGY, MESH_CONVERGE_REFINE_TAG, MESH_CONVERGE_FAST_FORWARD_TAG, DEFAULT_MESH_POLICY, SESSION_CLEANUP_MODES, SPAWNED_SESSION_VISIBILITY_MODES, DIRTY_WORKSPACE_BEHAVIORS, MESH_MAX_PARALLEL_TASKS_MIN, MESH_MAX_PARALLEL_TASKS_MAX, DEFAULT_MESH_READONLY_MULTIPLIER;
134
126
  var init_repo_mesh_types = __esm({
135
127
  "src/repo-mesh-types.ts"() {
136
128
  "use strict";
@@ -141,8 +133,6 @@ var init_repo_mesh_types = __esm({
141
133
  "priority_only"
142
134
  ];
143
135
  DEFAULT_MESH_SCHEDULING_STRATEGY = "first_eligible";
144
- MESH_DISTRIBUTIONS = ["spread", "in_order"];
145
- DEFAULT_MESH_DISTRIBUTION = "spread";
146
136
  MESH_CONVERGE_REFINE_TAG = "converge=refine";
147
137
  MESH_CONVERGE_FAST_FORWARD_TAG = "converge=fast_forward";
148
138
  DEFAULT_MESH_POLICY = {
@@ -399,10 +389,10 @@ function readInjected(value) {
399
389
  }
400
390
  function getDaemonBuildInfo() {
401
391
  if (cached) return cached;
402
- const commit = readInjected(true ? "69cd9c459ec9efafe19a05f66899bb791d6e0561" : void 0) ?? "unknown";
403
- const commitShort = readInjected(true ? "69cd9c45" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
404
- const version = readInjected(true ? "0.9.82-rc.410" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
405
- const builtAt = readInjected(true ? "2026-06-28T09:07:41.837Z" : void 0);
392
+ const commit = readInjected(true ? "f8bbe838081c3b3e14df690b3ed24568979f635e" : void 0) ?? "unknown";
393
+ const commitShort = readInjected(true ? "f8bbe838" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
394
+ const version = readInjected(true ? "0.9.82-rc.412" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
395
+ const builtAt = readInjected(true ? "2026-06-28T10:27:03.423Z" : void 0);
406
396
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
407
397
  return cached;
408
398
  }
@@ -7098,6 +7088,9 @@ __export(mesh_missions_exports, {
7098
7088
  summarizeMissionTasks: () => summarizeMissionTasks,
7099
7089
  upsertMeshMission: () => upsertMeshMission
7100
7090
  });
7091
+ function summarizeGoalForLedger(goal) {
7092
+ return goal.length > LEDGER_GOAL_SUMMARY_MAX ? goal.slice(0, LEDGER_GOAL_SUMMARY_MAX) : goal;
7093
+ }
7101
7094
  function normalizeMissionStatus(value) {
7102
7095
  return MESH_MISSION_STATUSES.includes(value) ? value : "active";
7103
7096
  }
@@ -7110,6 +7103,8 @@ function upsertMeshMission(meshId, input) {
7110
7103
  const id = typeof input.id === "string" && input.id.trim() ? input.id.trim() : (0, import_crypto7.randomUUID)();
7111
7104
  const store = MeshRuntimeStore.getInstance();
7112
7105
  const existing = store.getMission(meshId, id);
7106
+ const prevStatus = existing ? normalizeMissionStatus(existing.status) : null;
7107
+ const prevGoal = existing?.goal ?? "";
7113
7108
  const record = {
7114
7109
  id,
7115
7110
  meshId,
@@ -7119,7 +7114,61 @@ function upsertMeshMission(meshId, input) {
7119
7114
  };
7120
7115
  store.upsertMission(record);
7121
7116
  const saved = store.getMission(meshId, id);
7122
- return { ...saved, status: normalizeMissionStatus(saved.status) };
7117
+ const result = { ...saved, status: normalizeMissionStatus(saved.status) };
7118
+ appendMissionLedgerEntries(meshId, {
7119
+ isCreate: !existing,
7120
+ record: result,
7121
+ prevStatus,
7122
+ prevGoal
7123
+ });
7124
+ return result;
7125
+ }
7126
+ function appendMissionLedgerEntries(meshId, args) {
7127
+ const { isCreate, record, prevStatus, prevGoal } = args;
7128
+ try {
7129
+ if (isCreate) {
7130
+ const goal = record.goal ?? "";
7131
+ appendLedgerEntry(meshId, {
7132
+ kind: "mission_created",
7133
+ payload: {
7134
+ missionId: record.id,
7135
+ title: record.title,
7136
+ goalSummary: summarizeGoalForLedger(goal),
7137
+ goalLength: goal.length,
7138
+ goalTruncated: goal.length > LEDGER_GOAL_SUMMARY_MAX,
7139
+ status: record.status
7140
+ }
7141
+ });
7142
+ return;
7143
+ }
7144
+ if (prevStatus !== null && prevStatus !== record.status) {
7145
+ appendLedgerEntry(meshId, {
7146
+ kind: "mission_status_changed",
7147
+ payload: {
7148
+ missionId: record.id,
7149
+ title: record.title,
7150
+ fromStatus: prevStatus,
7151
+ toStatus: record.status
7152
+ }
7153
+ });
7154
+ }
7155
+ const nextGoal = record.goal ?? "";
7156
+ if (nextGoal !== prevGoal) {
7157
+ appendLedgerEntry(meshId, {
7158
+ kind: "mission_goal_updated",
7159
+ payload: {
7160
+ missionId: record.id,
7161
+ title: record.title,
7162
+ prevGoalSummary: summarizeGoalForLedger(prevGoal),
7163
+ nextGoalSummary: summarizeGoalForLedger(nextGoal),
7164
+ prevGoalLength: prevGoal.length,
7165
+ nextGoalLength: nextGoal.length,
7166
+ goalTruncated: prevGoal.length > LEDGER_GOAL_SUMMARY_MAX || nextGoal.length > LEDGER_GOAL_SUMMARY_MAX
7167
+ }
7168
+ });
7169
+ }
7170
+ } catch {
7171
+ }
7123
7172
  }
7124
7173
  function getMeshMissions(meshId, statuses) {
7125
7174
  return MeshRuntimeStore.getInstance().getMissions(meshId, statuses).map((m) => ({ ...m, status: normalizeMissionStatus(m.status) }));
@@ -7223,7 +7272,7 @@ function buildMissionPromptSection(meshId) {
7223
7272
  );
7224
7273
  return lines.join("\n");
7225
7274
  }
7226
- var import_crypto7, MESH_MISSION_STATUSES, GOAL_PREVIEW_MAX, COMPACT_STATUS_GOAL_PREVIEW_MAX;
7275
+ var import_crypto7, LEDGER_GOAL_SUMMARY_MAX, MESH_MISSION_STATUSES, GOAL_PREVIEW_MAX, COMPACT_STATUS_GOAL_PREVIEW_MAX;
7227
7276
  var init_mesh_missions = __esm({
7228
7277
  "src/mesh/mesh-missions.ts"() {
7229
7278
  "use strict";
@@ -7231,6 +7280,8 @@ var init_mesh_missions = __esm({
7231
7280
  init_mesh_runtime_store();
7232
7281
  init_mesh_work_queue();
7233
7282
  init_mesh_task_stats();
7283
+ init_mesh_ledger();
7284
+ LEDGER_GOAL_SUMMARY_MAX = 200;
7234
7285
  MESH_MISSION_STATUSES = ["active", "paused", "completed", "abandoned"];
7235
7286
  GOAL_PREVIEW_MAX = 120;
7236
7287
  COMPACT_STATUS_GOAL_PREVIEW_MAX = 80;
@@ -8684,6 +8735,216 @@ var init_worktree_bootstrap_config = __esm({
8684
8735
  }
8685
8736
  });
8686
8737
 
8738
+ // src/config/mesh-json-config.ts
8739
+ var mesh_json_config_exports = {};
8740
+ __export(mesh_json_config_exports, {
8741
+ MESH_JSON_CONFIG_LOCATIONS: () => MESH_JSON_CONFIG_LOCATIONS,
8742
+ MESH_JSON_CONFIG_SCHEMA: () => MESH_JSON_CONFIG_SCHEMA,
8743
+ applyRepoMeshConfig: () => applyRepoMeshConfig,
8744
+ buildMeshJsonConfigScaffold: () => buildMeshJsonConfigScaffold,
8745
+ loadRepoMeshJsonConfig: () => loadRepoMeshJsonConfig,
8746
+ mergeEffectiveCoordinatorConfig: () => mergeEffectiveCoordinatorConfig,
8747
+ mergeEffectiveOperatingNotes: () => mergeEffectiveOperatingNotes,
8748
+ normalizeRepoMeshDeclarativeConfig: () => normalizeRepoMeshDeclarativeConfig,
8749
+ serializeMeshJsonConfigScaffold: () => serializeMeshJsonConfigScaffold
8750
+ });
8751
+ function isRecord3(value) {
8752
+ return !!value && typeof value === "object" && !Array.isArray(value);
8753
+ }
8754
+ function parseConfigText4(path43, text) {
8755
+ if (/\.json$/i.test(path43)) return JSON.parse(text);
8756
+ return yaml4.load(text);
8757
+ }
8758
+ function normalizeOperatingNote(value) {
8759
+ if (!isRecord3(value)) return null;
8760
+ const text = typeof value.text === "string" ? value.text.trim() : "";
8761
+ if (!text) return null;
8762
+ const category = value.category === "provider_quirk" || value.category === "pattern_to_avoid" || value.category === "recovery_lesson" ? value.category : void 0;
8763
+ return {
8764
+ text,
8765
+ ...category ? { category } : {},
8766
+ ...typeof value.createdAt === "string" ? { createdAt: value.createdAt } : {},
8767
+ ...typeof value.sourceCoordinator === "string" ? { sourceCoordinator: value.sourceCoordinator } : {}
8768
+ };
8769
+ }
8770
+ function normalizeRepoMeshDeclarativeConfig(parsed) {
8771
+ const errors = [];
8772
+ if (!isRecord3(parsed)) return { valid: false, errors: ["config must be an object"] };
8773
+ if (parsed.version !== 1) {
8774
+ return { valid: false, errors: [`version must be 1 (got ${JSON.stringify(parsed.version)})`] };
8775
+ }
8776
+ const config = { version: 1 };
8777
+ if (parsed.coordinator !== void 0) {
8778
+ if (isRecord3(parsed.coordinator)) {
8779
+ const coord = {};
8780
+ const c = parsed.coordinator;
8781
+ if (typeof c.systemPromptOverride === "string") coord.systemPromptOverride = c.systemPromptOverride;
8782
+ if (typeof c.systemPromptAppend === "string") coord.systemPromptAppend = c.systemPromptAppend;
8783
+ if (Number.isFinite(Number(c.maxPromptChars))) coord.maxPromptChars = Number(c.maxPromptChars);
8784
+ config.coordinator = coord;
8785
+ } else {
8786
+ errors.push("coordinator must be an object when provided");
8787
+ }
8788
+ }
8789
+ if (parsed.operatingNotes !== void 0) {
8790
+ if (Array.isArray(parsed.operatingNotes)) {
8791
+ const notes = parsed.operatingNotes.map(normalizeOperatingNote).filter((n) => n !== null);
8792
+ if (notes.length) config.operatingNotes = notes;
8793
+ } else {
8794
+ errors.push("operatingNotes must be an array when provided");
8795
+ }
8796
+ }
8797
+ if (parsed.limits !== void 0) {
8798
+ if (isRecord3(parsed.limits)) {
8799
+ const limits = {};
8800
+ if (Number.isFinite(Number(parsed.limits.maxNoteChars))) limits.maxNoteChars = Number(parsed.limits.maxNoteChars);
8801
+ if (Number.isFinite(Number(parsed.limits.maxNotes))) limits.maxNotes = Number(parsed.limits.maxNotes);
8802
+ if (Object.keys(limits).length) config.limits = limits;
8803
+ } else {
8804
+ errors.push("limits must be an object when provided");
8805
+ }
8806
+ }
8807
+ return { valid: true, config, errors };
8808
+ }
8809
+ function loadRepoMeshJsonConfig(workspace) {
8810
+ const bases = [];
8811
+ const ws = typeof workspace === "string" ? workspace.trim() : "";
8812
+ if (ws) bases.push(ws);
8813
+ let cwd = "";
8814
+ try {
8815
+ cwd = process.cwd();
8816
+ } catch {
8817
+ }
8818
+ if (cwd && cwd !== ws) bases.push(cwd);
8819
+ for (const base of bases) {
8820
+ for (const relative5 of MESH_JSON_CONFIG_LOCATIONS) {
8821
+ const configPath = (0, import_path9.join)(base, relative5);
8822
+ if (!(0, import_fs10.existsSync)(configPath)) continue;
8823
+ try {
8824
+ const parsed = parseConfigText4(configPath, (0, import_fs10.readFileSync)(configPath, "utf-8"));
8825
+ const result = normalizeRepoMeshDeclarativeConfig(parsed);
8826
+ if (!result.valid || !result.config) {
8827
+ return { source: relative5, sourceType: "invalid", path: configPath, error: result.errors.join("; ") };
8828
+ }
8829
+ return { config: result.config, source: relative5, sourceType: "repo_file", path: configPath };
8830
+ } catch (error) {
8831
+ return { source: relative5, sourceType: "invalid", path: configPath, error: error?.message || String(error) };
8832
+ }
8833
+ }
8834
+ }
8835
+ return {
8836
+ source: "unavailable",
8837
+ sourceType: "unavailable",
8838
+ error: `No repo mesh config found. Checked: ${MESH_JSON_CONFIG_LOCATIONS.join(", ")}`
8839
+ };
8840
+ }
8841
+ function mergeEffectiveCoordinatorConfig(repoCoord, localCoord) {
8842
+ const out = { ...localCoord || {} };
8843
+ const localOverride = localCoord?.systemPromptOverride?.trim();
8844
+ const repoOverride = repoCoord?.systemPromptOverride?.trim();
8845
+ if (localOverride) {
8846
+ out.systemPromptOverride = localCoord.systemPromptOverride;
8847
+ } else if (repoOverride) {
8848
+ out.systemPromptOverride = repoCoord.systemPromptOverride;
8849
+ } else {
8850
+ delete out.systemPromptOverride;
8851
+ }
8852
+ const repoAppend = repoCoord?.systemPromptAppend?.trim() ? repoCoord.systemPromptAppend.trim() : "";
8853
+ const localAppendRaw = localCoord?.systemPromptAppend ?? localCoord?.systemPromptSuffix;
8854
+ const localAppend = localAppendRaw?.trim() ? localAppendRaw.trim() : "";
8855
+ const stacked = [repoAppend, localAppend].filter(Boolean).join("\n\n");
8856
+ if (stacked) {
8857
+ out.systemPromptAppend = stacked;
8858
+ delete out.systemPromptSuffix;
8859
+ }
8860
+ return out;
8861
+ }
8862
+ function mergeEffectiveOperatingNotes(repoNotes, ledgerNotes) {
8863
+ const usable = (notes) => Array.isArray(notes) ? notes.filter((n) => n && typeof n.text === "string" && n.text.trim()) : [];
8864
+ const repo = usable(repoNotes);
8865
+ const ledger = usable(ledgerNotes);
8866
+ const ledgerTexts = new Set(ledger.map((n) => n.text.trim()));
8867
+ const repoKept = repo.filter((n) => !ledgerTexts.has(n.text.trim()));
8868
+ const merged = [...repoKept, ...ledger];
8869
+ return merged.length ? merged : void 0;
8870
+ }
8871
+ function applyRepoMeshConfig(mesh, repoConfig) {
8872
+ if (!repoConfig) return mesh;
8873
+ return {
8874
+ ...mesh,
8875
+ coordinator: mergeEffectiveCoordinatorConfig(repoConfig.coordinator, mesh.coordinator)
8876
+ };
8877
+ }
8878
+ function buildMeshJsonConfigScaffold(mesh) {
8879
+ const scaffold = { version: 1 };
8880
+ const coord = {};
8881
+ const override = mesh.coordinator?.systemPromptOverride;
8882
+ if (typeof override === "string" && override.trim()) coord.systemPromptOverride = override;
8883
+ const append = mesh.coordinator?.systemPromptAppend ?? mesh.coordinator?.systemPromptSuffix;
8884
+ if (typeof append === "string" && append.trim()) coord.systemPromptAppend = append;
8885
+ if (Object.keys(coord).length) scaffold.coordinator = coord;
8886
+ return scaffold;
8887
+ }
8888
+ function serializeMeshJsonConfigScaffold(config) {
8889
+ return JSON.stringify(config, null, 2);
8890
+ }
8891
+ var import_fs10, import_path9, yaml4, MESH_JSON_CONFIG_LOCATIONS, MESH_JSON_CONFIG_SCHEMA;
8892
+ var init_mesh_json_config = __esm({
8893
+ "src/config/mesh-json-config.ts"() {
8894
+ "use strict";
8895
+ import_fs10 = require("fs");
8896
+ import_path9 = require("path");
8897
+ yaml4 = __toESM(require("js-yaml"));
8898
+ MESH_JSON_CONFIG_LOCATIONS = [
8899
+ ".adhdev/mesh.json",
8900
+ ".adhdev/mesh.yaml",
8901
+ ".adhdev/mesh.yml"
8902
+ ];
8903
+ MESH_JSON_CONFIG_SCHEMA = {
8904
+ $schema: "https://json-schema.org/draft/2020-12/schema",
8905
+ title: "ADHDev Repo Mesh Declarative Config",
8906
+ type: "object",
8907
+ additionalProperties: false,
8908
+ required: ["version"],
8909
+ properties: {
8910
+ version: { const: 1 },
8911
+ coordinator: {
8912
+ type: "object",
8913
+ additionalProperties: false,
8914
+ properties: {
8915
+ systemPromptOverride: { type: "string" },
8916
+ systemPromptAppend: { type: "string" },
8917
+ maxPromptChars: { type: "number", minimum: 1 }
8918
+ }
8919
+ },
8920
+ operatingNotes: {
8921
+ type: "array",
8922
+ maxItems: 200,
8923
+ items: {
8924
+ type: "object",
8925
+ additionalProperties: false,
8926
+ required: ["text"],
8927
+ properties: {
8928
+ text: { type: "string", minLength: 1 },
8929
+ category: { enum: ["provider_quirk", "pattern_to_avoid", "recovery_lesson"] },
8930
+ createdAt: { type: "string" },
8931
+ sourceCoordinator: { type: "string" }
8932
+ }
8933
+ }
8934
+ },
8935
+ limits: {
8936
+ type: "object",
8937
+ additionalProperties: false,
8938
+ properties: {
8939
+ maxNoteChars: { type: "number", minimum: 1 },
8940
+ maxNotes: { type: "number", minimum: 1 }
8941
+ }
8942
+ }
8943
+ }
8944
+ };
8945
+ }
8946
+ });
8947
+
8687
8948
  // src/mesh/mesh-fast-forward.ts
8688
8949
  async function fastForwardMeshNode(args) {
8689
8950
  const workspace = typeof args.workspace === "string" ? args.workspace.trim() : "";
@@ -10151,9 +10412,9 @@ function getPendingEventsPath(meshId, coordinatorDaemonId) {
10151
10412
  const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
10152
10413
  if (coordinatorDaemonId) {
10153
10414
  const safeDaemon = coordinatorDaemonId.replace(/[^a-zA-Z0-9_-]/g, "_");
10154
- return (0, import_path9.join)(getLedgerDir(), `${safe}-${safeDaemon}.pending-events.jsonl`);
10415
+ return (0, import_path10.join)(getLedgerDir(), `${safe}-${safeDaemon}.pending-events.jsonl`);
10155
10416
  }
10156
- return (0, import_path9.join)(getLedgerDir(), `${safe}.pending-events.jsonl`);
10417
+ return (0, import_path10.join)(getLedgerDir(), `${safe}.pending-events.jsonl`);
10157
10418
  }
10158
10419
  function readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId) {
10159
10420
  if (!meshId) return [];
@@ -10162,9 +10423,9 @@ function readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId) {
10162
10423
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
10163
10424
  const events = [];
10164
10425
  for (const path43 of paths) {
10165
- if (!(0, import_fs10.existsSync)(path43)) continue;
10426
+ if (!(0, import_fs11.existsSync)(path43)) continue;
10166
10427
  try {
10167
- const raw = (0, import_fs10.readFileSync)(path43, "utf-8");
10428
+ const raw = (0, import_fs11.readFileSync)(path43, "utf-8");
10168
10429
  const parsed = raw.split("\n").filter(Boolean).flatMap((line) => {
10169
10430
  try {
10170
10431
  return [JSON.parse(line)];
@@ -10239,9 +10500,9 @@ function reconcilePendingMeshCoordinatorEvents(meshId, events) {
10239
10500
  }
10240
10501
  function trimPendingEventsIfNeeded(path43) {
10241
10502
  try {
10242
- if (!(0, import_fs10.existsSync)(path43)) return;
10243
- if ((0, import_fs10.statSync)(path43).size <= MAX_PENDING_EVENTS_BYTES) return;
10244
- const lines = (0, import_fs10.readFileSync)(path43, "utf-8").split("\n").filter(Boolean);
10503
+ if (!(0, import_fs11.existsSync)(path43)) return;
10504
+ if ((0, import_fs11.statSync)(path43).size <= MAX_PENDING_EVENTS_BYTES) return;
10505
+ const lines = (0, import_fs11.readFileSync)(path43, "utf-8").split("\n").filter(Boolean);
10245
10506
  if (lines.length <= MAX_PENDING_EVENTS_KEEP) return;
10246
10507
  const dropped = lines.slice(0, lines.length - MAX_PENDING_EVENTS_KEEP);
10247
10508
  for (const line of dropped) {
@@ -10274,7 +10535,7 @@ function trimPendingEventsIfNeeded(path43) {
10274
10535
  LOG.warn("MeshEvents", `Failed to ledger-record trim-dropped ${event.event} for mesh ${event.meshId}: ${e?.message || e}`);
10275
10536
  }
10276
10537
  }
10277
- (0, import_fs10.writeFileSync)(path43, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
10538
+ (0, import_fs11.writeFileSync)(path43, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
10278
10539
  } catch {
10279
10540
  }
10280
10541
  }
@@ -10306,7 +10567,7 @@ function queuePendingMeshCoordinatorEvent(event) {
10306
10567
  try {
10307
10568
  const path43 = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
10308
10569
  trimPendingEventsIfNeeded(path43);
10309
- (0, import_fs10.appendFileSync)(path43, JSON.stringify(event) + "\n", "utf-8");
10570
+ (0, import_fs11.appendFileSync)(path43, JSON.stringify(event) + "\n", "utf-8");
10310
10571
  } catch (e) {
10311
10572
  if (!sqliteOk) throw e;
10312
10573
  LOG.warn("MeshEvents", `JSONL append failed for mesh ${event.meshId}; SQLite holds the event: ${e?.message || e}`);
@@ -10320,20 +10581,20 @@ function queuePendingMeshCoordinatorEvent(event) {
10320
10581
  function atomicDrainFile(path43) {
10321
10582
  const tmpPath = `${path43}.draining`;
10322
10583
  try {
10323
- (0, import_fs10.renameSync)(path43, tmpPath);
10584
+ (0, import_fs11.renameSync)(path43, tmpPath);
10324
10585
  } catch {
10325
10586
  return null;
10326
10587
  }
10327
10588
  try {
10328
- const content = (0, import_fs10.readFileSync)(tmpPath, "utf-8");
10589
+ const content = (0, import_fs11.readFileSync)(tmpPath, "utf-8");
10329
10590
  try {
10330
- (0, import_fs10.unlinkSync)(tmpPath);
10591
+ (0, import_fs11.unlinkSync)(tmpPath);
10331
10592
  } catch {
10332
10593
  }
10333
10594
  return content;
10334
10595
  } catch {
10335
10596
  try {
10336
- (0, import_fs10.unlinkSync)(tmpPath);
10597
+ (0, import_fs11.unlinkSync)(tmpPath);
10337
10598
  } catch {
10338
10599
  }
10339
10600
  return null;
@@ -10342,16 +10603,16 @@ function atomicDrainFile(path43) {
10342
10603
  function selectiveDrainFile(path43, predicate) {
10343
10604
  const tmpPath = `${path43}.draining`;
10344
10605
  try {
10345
- (0, import_fs10.renameSync)(path43, tmpPath);
10606
+ (0, import_fs11.renameSync)(path43, tmpPath);
10346
10607
  } catch {
10347
10608
  return [];
10348
10609
  }
10349
10610
  let content;
10350
10611
  try {
10351
- content = (0, import_fs10.readFileSync)(tmpPath, "utf-8");
10612
+ content = (0, import_fs11.readFileSync)(tmpPath, "utf-8");
10352
10613
  } catch {
10353
10614
  try {
10354
- (0, import_fs10.unlinkSync)(tmpPath);
10615
+ (0, import_fs11.unlinkSync)(tmpPath);
10355
10616
  } catch {
10356
10617
  }
10357
10618
  return [];
@@ -10374,12 +10635,12 @@ function selectiveDrainFile(path43, predicate) {
10374
10635
  }
10375
10636
  try {
10376
10637
  if (keptLines.length > 0) {
10377
- (0, import_fs10.writeFileSync)(path43, keptLines.join("\n") + "\n", "utf-8");
10638
+ (0, import_fs11.writeFileSync)(path43, keptLines.join("\n") + "\n", "utf-8");
10378
10639
  }
10379
- (0, import_fs10.unlinkSync)(tmpPath);
10640
+ (0, import_fs11.unlinkSync)(tmpPath);
10380
10641
  } catch {
10381
10642
  try {
10382
- if ((0, import_fs10.existsSync)(tmpPath) && !(0, import_fs10.existsSync)(path43)) (0, import_fs10.renameSync)(tmpPath, path43);
10643
+ if ((0, import_fs11.existsSync)(tmpPath) && !(0, import_fs11.existsSync)(path43)) (0, import_fs11.renameSync)(tmpPath, path43);
10383
10644
  } catch {
10384
10645
  }
10385
10646
  return [];
@@ -10474,18 +10735,18 @@ function clearPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
10474
10735
  }
10475
10736
  const paths = coordinatorDaemonId ? [getPendingEventsPath(meshId, coordinatorDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
10476
10737
  for (const path43 of paths) {
10477
- if ((0, import_fs10.existsSync)(path43)) try {
10478
- (0, import_fs10.unlinkSync)(path43);
10738
+ if ((0, import_fs11.existsSync)(path43)) try {
10739
+ (0, import_fs11.unlinkSync)(path43);
10479
10740
  } catch {
10480
10741
  }
10481
10742
  }
10482
10743
  }
10483
- var import_fs10, import_path9, import_crypto8, REFINE_TERMINAL_EVENTS, TERMINAL_COMPLETION_EVENTS, MAX_PENDING_EVENTS_BYTES, MAX_PENDING_EVENTS_KEEP;
10744
+ var import_fs11, import_path10, import_crypto8, REFINE_TERMINAL_EVENTS, TERMINAL_COMPLETION_EVENTS, MAX_PENDING_EVENTS_BYTES, MAX_PENDING_EVENTS_KEEP;
10484
10745
  var init_mesh_events_pending = __esm({
10485
10746
  "src/mesh/mesh-events-pending.ts"() {
10486
10747
  "use strict";
10487
- import_fs10 = require("fs");
10488
- import_path9 = require("path");
10748
+ import_fs11 = require("fs");
10749
+ import_path10 = require("path");
10489
10750
  import_crypto8 = require("crypto");
10490
10751
  init_logger();
10491
10752
  init_mesh_ledger();
@@ -11257,7 +11518,7 @@ function resolveCommandPath(command) {
11257
11518
  if (isExplicitCommandPath(trimmed)) {
11258
11519
  const expanded = expandHome(trimmed);
11259
11520
  const candidate = path12.isAbsolute(expanded) ? expanded : path12.resolve(expanded);
11260
- return (0, import_fs11.existsSync)(candidate) ? candidate : null;
11521
+ return (0, import_fs12.existsSync)(candidate) ? candidate : null;
11261
11522
  }
11262
11523
  return null;
11263
11524
  }
@@ -11267,7 +11528,7 @@ async function resolveDetectionPath(command, whichCmd) {
11267
11528
  const whichResult = await execAsync(`${whichCmd} ${shellQuote(command)}`);
11268
11529
  if (whichResult) return whichResult.split("\n")[0];
11269
11530
  const resolved = findBinary(command);
11270
- if (path12.isAbsolute(resolved) && (0, import_fs11.existsSync)(resolved)) return resolved;
11531
+ if (path12.isAbsolute(resolved) && (0, import_fs12.existsSync)(resolved)) return resolved;
11271
11532
  return null;
11272
11533
  }
11273
11534
  function execAsync(cmd, timeoutMs = 5e3) {
@@ -11362,14 +11623,14 @@ async function detectCLI(cliId, providerLoader, options) {
11362
11623
  const all = await detectCLIs(providerLoader, options);
11363
11624
  return all.find((c) => c.id === resolvedId && c.installed) || null;
11364
11625
  }
11365
- var import_child_process2, os6, path12, import_fs11;
11626
+ var import_child_process2, os6, path12, import_fs12;
11366
11627
  var init_cli_detector = __esm({
11367
11628
  "src/detection/cli-detector.ts"() {
11368
11629
  "use strict";
11369
11630
  import_child_process2 = require("child_process");
11370
11631
  os6 = __toESM(require("os"));
11371
11632
  path12 = __toESM(require("path"));
11372
- import_fs11 = require("fs");
11633
+ import_fs12 = require("fs");
11373
11634
  init_provider_cli_shared();
11374
11635
  }
11375
11636
  });
@@ -11490,345 +11751,6 @@ var init_mesh_warmup_deadline = __esm({
11490
11751
  }
11491
11752
  });
11492
11753
 
11493
- // src/config/mesh-json-config.ts
11494
- var mesh_json_config_exports = {};
11495
- __export(mesh_json_config_exports, {
11496
- MESH_JSON_CONFIG_LOCATIONS: () => MESH_JSON_CONFIG_LOCATIONS,
11497
- MESH_JSON_CONFIG_SCHEMA: () => MESH_JSON_CONFIG_SCHEMA,
11498
- __resetMeshJsonConfigCacheForTests: () => __resetMeshJsonConfigCacheForTests,
11499
- applyRepoMeshConfig: () => applyRepoMeshConfig,
11500
- buildMeshJsonConfigScaffold: () => buildMeshJsonConfigScaffold,
11501
- diffPolicyFromDefault: () => diffPolicyFromDefault,
11502
- loadMeshJsonConfig: () => loadMeshJsonConfig,
11503
- loadRepoMeshJsonConfig: () => loadRepoMeshJsonConfig,
11504
- mergeEffectiveCoordinatorConfig: () => mergeEffectiveCoordinatorConfig,
11505
- mergeEffectiveMeshPolicy: () => mergeEffectiveMeshPolicy,
11506
- mergeEffectiveOperatingNotes: () => mergeEffectiveOperatingNotes,
11507
- normalizeRepoMeshDeclarativeConfig: () => normalizeRepoMeshDeclarativeConfig,
11508
- serializeMeshJsonConfigScaffold: () => serializeMeshJsonConfigScaffold,
11509
- validateMeshJsonConfig: () => validateMeshJsonConfig
11510
- });
11511
- function isRecord3(value) {
11512
- return !!value && typeof value === "object" && !Array.isArray(value);
11513
- }
11514
- function parseConfigText4(path43, text) {
11515
- if (/\.json$/i.test(path43)) return JSON.parse(text);
11516
- return yaml4.load(text);
11517
- }
11518
- function normalizeOperatingNote(value) {
11519
- if (!isRecord3(value)) return null;
11520
- const text = typeof value.text === "string" ? value.text.trim() : "";
11521
- if (!text) return null;
11522
- const category = value.category === "provider_quirk" || value.category === "pattern_to_avoid" || value.category === "recovery_lesson" ? value.category : void 0;
11523
- return {
11524
- text,
11525
- ...category ? { category } : {},
11526
- ...typeof value.createdAt === "string" ? { createdAt: value.createdAt } : {},
11527
- ...typeof value.sourceCoordinator === "string" ? { sourceCoordinator: value.sourceCoordinator } : {}
11528
- };
11529
- }
11530
- function normalizeRepoMeshDeclarativeConfig(parsed) {
11531
- const errors = [];
11532
- if (!isRecord3(parsed)) return { valid: false, errors: ["config must be an object"] };
11533
- if (parsed.version !== 1) {
11534
- return { valid: false, errors: [`version must be 1 (got ${JSON.stringify(parsed.version)})`] };
11535
- }
11536
- const config = { version: 1 };
11537
- if (parsed.policy !== void 0) {
11538
- if (isRecord3(parsed.policy)) {
11539
- config.policy = parsed.policy;
11540
- } else {
11541
- errors.push("policy must be an object when provided");
11542
- }
11543
- }
11544
- if (parsed.coordinator !== void 0) {
11545
- if (isRecord3(parsed.coordinator)) {
11546
- const coord = {};
11547
- const c = parsed.coordinator;
11548
- if (typeof c.systemPromptOverride === "string") coord.systemPromptOverride = c.systemPromptOverride;
11549
- if (typeof c.systemPromptAppend === "string") coord.systemPromptAppend = c.systemPromptAppend;
11550
- if (Number.isFinite(Number(c.maxPromptChars))) coord.maxPromptChars = Number(c.maxPromptChars);
11551
- config.coordinator = coord;
11552
- } else {
11553
- errors.push("coordinator must be an object when provided");
11554
- }
11555
- }
11556
- if (parsed.operatingNotes !== void 0) {
11557
- if (Array.isArray(parsed.operatingNotes)) {
11558
- const notes = parsed.operatingNotes.map(normalizeOperatingNote).filter((n) => n !== null);
11559
- if (notes.length) config.operatingNotes = notes;
11560
- } else {
11561
- errors.push("operatingNotes must be an array when provided");
11562
- }
11563
- }
11564
- if (parsed.limits !== void 0) {
11565
- if (isRecord3(parsed.limits)) {
11566
- const limits = {};
11567
- if (Number.isFinite(Number(parsed.limits.maxNoteChars))) limits.maxNoteChars = Number(parsed.limits.maxNoteChars);
11568
- if (Number.isFinite(Number(parsed.limits.maxNotes))) limits.maxNotes = Number(parsed.limits.maxNotes);
11569
- if (Object.keys(limits).length) config.limits = limits;
11570
- } else {
11571
- errors.push("limits must be an object when provided");
11572
- }
11573
- }
11574
- return { valid: true, config, errors };
11575
- }
11576
- function loadRepoMeshJsonConfig(workspace) {
11577
- const bases = [];
11578
- const ws = typeof workspace === "string" ? workspace.trim() : "";
11579
- if (ws) bases.push(ws);
11580
- let cwd = "";
11581
- try {
11582
- cwd = process.cwd();
11583
- } catch {
11584
- }
11585
- if (cwd && cwd !== ws) bases.push(cwd);
11586
- for (const base of bases) {
11587
- for (const relative5 of MESH_JSON_CONFIG_LOCATIONS) {
11588
- const configPath = (0, import_path10.join)(base, relative5);
11589
- if (!(0, import_fs12.existsSync)(configPath)) continue;
11590
- try {
11591
- const parsed = parseConfigText4(configPath, (0, import_fs12.readFileSync)(configPath, "utf-8"));
11592
- const result = normalizeRepoMeshDeclarativeConfig(parsed);
11593
- if (!result.valid || !result.config) {
11594
- return { source: relative5, sourceType: "invalid", path: configPath, error: result.errors.join("; ") };
11595
- }
11596
- return { config: result.config, source: relative5, sourceType: "repo_file", path: configPath };
11597
- } catch (error) {
11598
- return { source: relative5, sourceType: "invalid", path: configPath, error: error?.message || String(error) };
11599
- }
11600
- }
11601
- }
11602
- return {
11603
- source: "unavailable",
11604
- sourceType: "unavailable",
11605
- error: `No repo mesh config found. Checked: ${MESH_JSON_CONFIG_LOCATIONS.join(", ")}`
11606
- };
11607
- }
11608
- function deepEqual(a, b) {
11609
- if (a === b) return true;
11610
- try {
11611
- return JSON.stringify(a) === JSON.stringify(b);
11612
- } catch {
11613
- return false;
11614
- }
11615
- }
11616
- function diffPolicyFromDefault(local) {
11617
- if (!local || typeof local !== "object") return {};
11618
- const out = {};
11619
- const def = mergeAndNormalizePolicy(void 0, void 0);
11620
- for (const [key, value] of Object.entries(local)) {
11621
- if (value === void 0) continue;
11622
- if (!deepEqual(value, def[key])) out[key] = value;
11623
- }
11624
- return out;
11625
- }
11626
- function mergeEffectiveMeshPolicy(repoPolicy, localPolicy) {
11627
- const repoMerged = mergeAndNormalizePolicy(void 0, repoPolicy);
11628
- const localOverrides = diffPolicyFromDefault(localPolicy);
11629
- return mergeAndNormalizePolicy(repoMerged, localOverrides);
11630
- }
11631
- function mergeEffectiveCoordinatorConfig(repoCoord, localCoord) {
11632
- const out = { ...localCoord || {} };
11633
- const localOverride = localCoord?.systemPromptOverride?.trim();
11634
- const repoOverride = repoCoord?.systemPromptOverride?.trim();
11635
- if (localOverride) {
11636
- out.systemPromptOverride = localCoord.systemPromptOverride;
11637
- } else if (repoOverride) {
11638
- out.systemPromptOverride = repoCoord.systemPromptOverride;
11639
- } else {
11640
- delete out.systemPromptOverride;
11641
- }
11642
- const repoAppend = repoCoord?.systemPromptAppend?.trim() ? repoCoord.systemPromptAppend.trim() : "";
11643
- const localAppendRaw = localCoord?.systemPromptAppend ?? localCoord?.systemPromptSuffix;
11644
- const localAppend = localAppendRaw?.trim() ? localAppendRaw.trim() : "";
11645
- const stacked = [repoAppend, localAppend].filter(Boolean).join("\n\n");
11646
- if (stacked) {
11647
- out.systemPromptAppend = stacked;
11648
- delete out.systemPromptSuffix;
11649
- }
11650
- return out;
11651
- }
11652
- function mergeEffectiveOperatingNotes(repoNotes, ledgerNotes) {
11653
- const usable = (notes) => Array.isArray(notes) ? notes.filter((n) => n && typeof n.text === "string" && n.text.trim()) : [];
11654
- const repo = usable(repoNotes);
11655
- const ledger = usable(ledgerNotes);
11656
- const ledgerTexts = new Set(ledger.map((n) => n.text.trim()));
11657
- const repoKept = repo.filter((n) => !ledgerTexts.has(n.text.trim()));
11658
- const merged = [...repoKept, ...ledger];
11659
- return merged.length ? merged : void 0;
11660
- }
11661
- function applyRepoMeshConfig(mesh, repoConfig) {
11662
- if (!repoConfig) return mesh;
11663
- return {
11664
- ...mesh,
11665
- policy: mergeEffectiveMeshPolicy(repoConfig.policy, mesh.policy),
11666
- coordinator: mergeEffectiveCoordinatorConfig(repoConfig.coordinator, mesh.coordinator)
11667
- };
11668
- }
11669
- function buildMeshJsonConfigScaffold(mesh) {
11670
- const scaffold = {
11671
- version: 1,
11672
- policy: mergeAndNormalizePolicy(void 0, mesh.policy)
11673
- };
11674
- const coord = {};
11675
- const override = mesh.coordinator?.systemPromptOverride;
11676
- if (typeof override === "string" && override.trim()) coord.systemPromptOverride = override;
11677
- const append = mesh.coordinator?.systemPromptAppend ?? mesh.coordinator?.systemPromptSuffix;
11678
- if (typeof append === "string" && append.trim()) coord.systemPromptAppend = append;
11679
- if (Object.keys(coord).length) scaffold.coordinator = coord;
11680
- return scaffold;
11681
- }
11682
- function serializeMeshJsonConfigScaffold(config) {
11683
- return JSON.stringify(config, null, 2);
11684
- }
11685
- function validateMeshJsonConfig(raw, source = "inline") {
11686
- const errors = [];
11687
- if (!isRecord3(raw)) {
11688
- return { valid: false, errors: [`${source}: config must be an object`] };
11689
- }
11690
- const config = {};
11691
- const policy = raw.policy;
11692
- const schedulingRaw = isRecord3(policy) ? policy.scheduling : void 0;
11693
- if (schedulingRaw !== void 0) {
11694
- if (!isRecord3(schedulingRaw)) {
11695
- errors.push("policy.scheduling must be an object");
11696
- } else {
11697
- const scheduling = {};
11698
- if (schedulingRaw.distribution !== void 0) {
11699
- if (typeof schedulingRaw.distribution !== "string" || !["spread", "in_order"].includes(schedulingRaw.distribution.trim())) {
11700
- errors.push("policy.scheduling.distribution must be 'spread' or 'in_order'");
11701
- } else {
11702
- scheduling.distribution = normalizeMeshDistribution(schedulingRaw.distribution);
11703
- }
11704
- }
11705
- if (schedulingRaw.maxParallel !== void 0) {
11706
- const n = Number(schedulingRaw.maxParallel);
11707
- if (!Number.isFinite(n) || n < MESH_MAX_PARALLEL_TASKS_MIN || n > MESH_MAX_PARALLEL_TASKS_MAX) {
11708
- errors.push(`policy.scheduling.maxParallel must be a number in [${MESH_MAX_PARALLEL_TASKS_MIN}, ${MESH_MAX_PARALLEL_TASKS_MAX}]`);
11709
- } else {
11710
- scheduling.maxParallel = Math.floor(n);
11711
- }
11712
- }
11713
- if (schedulingRaw.readonlyMultiplier !== void 0) {
11714
- const n = Number(schedulingRaw.readonlyMultiplier);
11715
- if (!Number.isFinite(n) || n < 1) {
11716
- errors.push("policy.scheduling.readonlyMultiplier must be a number >= 1");
11717
- } else {
11718
- scheduling.readonlyMultiplier = Math.floor(n);
11719
- }
11720
- }
11721
- for (const key of Object.keys(schedulingRaw)) {
11722
- if (!["distribution", "maxParallel", "readonlyMultiplier"].includes(key)) {
11723
- errors.push(`policy.scheduling.${key} is not a recognized field`);
11724
- }
11725
- }
11726
- if (Object.keys(scheduling).length) config.scheduling = scheduling;
11727
- }
11728
- }
11729
- return { valid: errors.length === 0, errors, config: errors.length === 0 ? config : void 0 };
11730
- }
11731
- function loadMeshJsonConfig(repoRoot) {
11732
- if (!repoRoot) {
11733
- return { source: "unavailable", sourceType: "unavailable", error: "no repo root", sourceKey: "unavailable" };
11734
- }
11735
- for (const relative5 of MESH_JSON_CONFIG_LOCATIONS) {
11736
- const configPath = (0, import_path10.join)(repoRoot, relative5);
11737
- if (!(0, import_fs12.existsSync)(configPath)) continue;
11738
- let mtimeMs = 0;
11739
- try {
11740
- mtimeMs = (0, import_fs12.statSync)(configPath).mtimeMs;
11741
- } catch {
11742
- mtimeMs = 0;
11743
- }
11744
- const cacheKey = configPath;
11745
- const sourceKey = `file:${configPath}:${mtimeMs}`;
11746
- const cached3 = cache.get(cacheKey);
11747
- if (cached3 && cached3.sourceKey === sourceKey) return cached3.result;
11748
- let result;
11749
- try {
11750
- const text = (0, import_fs12.readFileSync)(configPath, "utf-8");
11751
- const parsed = parseConfigText4(configPath, text);
11752
- const validation = validateMeshJsonConfig(parsed, relative5);
11753
- 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}` };
11754
- } catch (error) {
11755
- result = { source: relative5, sourceType: "invalid", path: configPath, error: error?.message || String(error), sourceKey: `error:${configPath}` };
11756
- }
11757
- cache.set(cacheKey, { sourceKey: result.sourceKey, result });
11758
- return result;
11759
- }
11760
- return {
11761
- source: "unavailable",
11762
- sourceType: "unavailable",
11763
- error: `No .adhdev/mesh config found. Checked: ${MESH_JSON_CONFIG_LOCATIONS.join(", ")}`,
11764
- sourceKey: "unavailable"
11765
- };
11766
- }
11767
- function __resetMeshJsonConfigCacheForTests() {
11768
- cache.clear();
11769
- }
11770
- var import_fs12, import_path10, yaml4, MESH_JSON_CONFIG_LOCATIONS, MESH_JSON_CONFIG_SCHEMA, cache;
11771
- var init_mesh_json_config = __esm({
11772
- "src/config/mesh-json-config.ts"() {
11773
- "use strict";
11774
- import_fs12 = require("fs");
11775
- import_path10 = require("path");
11776
- yaml4 = __toESM(require("js-yaml"));
11777
- init_repo_mesh_types();
11778
- MESH_JSON_CONFIG_LOCATIONS = [
11779
- ".adhdev/mesh.json",
11780
- ".adhdev/mesh.yaml",
11781
- ".adhdev/mesh.yml"
11782
- ];
11783
- MESH_JSON_CONFIG_SCHEMA = {
11784
- $schema: "https://json-schema.org/draft/2020-12/schema",
11785
- title: "ADHDev Repo Mesh Declarative Config",
11786
- type: "object",
11787
- additionalProperties: false,
11788
- required: ["version"],
11789
- properties: {
11790
- version: { const: 1 },
11791
- // policy is validated/normalized through mergeAndNormalizePolicy at merge
11792
- // time; the schema here only asserts it is an object.
11793
- policy: { type: "object" },
11794
- coordinator: {
11795
- type: "object",
11796
- additionalProperties: false,
11797
- properties: {
11798
- systemPromptOverride: { type: "string" },
11799
- systemPromptAppend: { type: "string" },
11800
- maxPromptChars: { type: "number", minimum: 1 }
11801
- }
11802
- },
11803
- operatingNotes: {
11804
- type: "array",
11805
- maxItems: 200,
11806
- items: {
11807
- type: "object",
11808
- additionalProperties: false,
11809
- required: ["text"],
11810
- properties: {
11811
- text: { type: "string", minLength: 1 },
11812
- category: { enum: ["provider_quirk", "pattern_to_avoid", "recovery_lesson"] },
11813
- createdAt: { type: "string" },
11814
- sourceCoordinator: { type: "string" }
11815
- }
11816
- }
11817
- },
11818
- limits: {
11819
- type: "object",
11820
- additionalProperties: false,
11821
- properties: {
11822
- maxNoteChars: { type: "number", minimum: 1 },
11823
- maxNotes: { type: "number", minimum: 1 }
11824
- }
11825
- }
11826
- }
11827
- };
11828
- cache = /* @__PURE__ */ new Map();
11829
- }
11830
- });
11831
-
11832
11754
  // src/mesh/mesh-queue-assignment.ts
11833
11755
  function __resetIdleAutoFastForwardForTests() {
11834
11756
  idleAutoFastForwardLastAttempt.clear();
@@ -12244,26 +12166,7 @@ function nodeHasActiveAssignment(meshId, nodeId) {
12244
12166
  function nodeActiveLoad(meshId, nodeId) {
12245
12167
  return MeshRuntimeStore.getInstance().nodeActiveAssignmentCount(meshId, nodeId);
12246
12168
  }
12247
- function resolveMeshRepoRootForScheduling(mesh) {
12248
- const nodes = Array.isArray(mesh?.nodes) ? mesh.nodes : [];
12249
- const pickRoot = (n) => readNonEmptyString2(n?.repoRoot) || readNonEmptyString2(n?.workspace);
12250
- const base = nodes.find((n) => n?.isLocalWorktree !== true && pickRoot(n));
12251
- if (base) return pickRoot(base);
12252
- const anyNode = nodes.find((n) => pickRoot(n));
12253
- return anyNode ? pickRoot(anyNode) : "";
12254
- }
12255
- function resolveMeshSchedulingOverride(mesh) {
12256
- const repoRoot = resolveMeshRepoRootForScheduling(mesh);
12257
- if (!repoRoot) return void 0;
12258
- try {
12259
- return loadMeshJsonConfig(repoRoot).config?.scheduling;
12260
- } catch {
12261
- return void 0;
12262
- }
12263
- }
12264
12169
  function resolveSchedulingStrategy(mesh) {
12265
- const override = resolveMeshSchedulingOverride(mesh);
12266
- if (override?.distribution) return distributionToStrategy(override.distribution);
12267
12170
  return normalizeMeshSchedulingStrategy(mesh?.policy?.schedulingStrategy);
12268
12171
  }
12269
12172
  function orderEligibleNodes(meshId, strategy, nodes, opts) {
@@ -12406,11 +12309,8 @@ async function maybeAutoLaunchOneQueueSession(components, meshId, mesh) {
12406
12309
  const queue = getQueue(meshId);
12407
12310
  const pending = queue.filter((task) => task.status === "pending");
12408
12311
  if (!pending.length) return false;
12409
- const schedulingOverride = resolveMeshSchedulingOverride(mesh);
12410
- const maxParallelTasks = resolveMaxParallelTasks(
12411
- schedulingOverride?.maxParallel ?? mesh?.policy?.maxParallelTasks
12412
- );
12413
- const maxReadonlyParallelTasks = resolveMaxReadonlyParallelTasks(maxParallelTasks, schedulingOverride?.readonlyMultiplier);
12312
+ const maxParallelTasks = resolveMaxParallelTasks(mesh?.policy?.maxParallelTasks);
12313
+ const maxReadonlyParallelTasks = resolveMaxReadonlyParallelTasks(maxParallelTasks);
12414
12314
  for (const task of pending) {
12415
12315
  const isReadonly = isTaskReadonly(task);
12416
12316
  if (isReadonly) {
@@ -12824,7 +12724,6 @@ var init_mesh_queue_assignment = __esm({
12824
12724
  init_mesh_event_trace();
12825
12725
  init_mesh_warmup_deadline();
12826
12726
  init_repo_mesh_types();
12827
- init_mesh_json_config();
12828
12727
  init_dist();
12829
12728
  init_mesh_events_stale();
12830
12729
  init_mesh_events_utils();
@@ -15039,11 +14938,11 @@ function buildRecentReadDebugSignature(snapshot) {
15039
14938
  String(snapshot.messageUpdatedAt)
15040
14939
  ].join("|");
15041
14940
  }
15042
- function shouldEmitRecentReadDebugLog(cache2, snapshot) {
14941
+ function shouldEmitRecentReadDebugLog(cache, snapshot) {
15043
14942
  const nextSignature = buildRecentReadDebugSignature(snapshot);
15044
- const previousSignature = cache2.get(snapshot.sessionId);
14943
+ const previousSignature = cache.get(snapshot.sessionId);
15045
14944
  if (previousSignature === nextSignature) return false;
15046
- cache2.set(snapshot.sessionId, nextSignature);
14945
+ cache.set(snapshot.sessionId, nextSignature);
15047
14946
  return true;
15048
14947
  }
15049
14948
  function buildDetectedIdeInfos(detectedIdes, cdpManagers) {
@@ -23258,6 +23157,7 @@ __export(index_exports, {
23258
23157
  loadMeshCoordinatorRegistry: () => loadMeshCoordinatorRegistry,
23259
23158
  loadMeshRefineConfig: () => loadMeshRefineConfig,
23260
23159
  loadMeshWorktreeBootstrapConfig: () => loadMeshWorktreeBootstrapConfig,
23160
+ loadRepoSettings: () => loadRepoSettings,
23261
23161
  loadState: () => loadState,
23262
23162
  logCommand: () => logCommand,
23263
23163
  machineCoreFromDaemonId: () => machineCoreFromDaemonId,
@@ -24634,6 +24534,29 @@ init_mesh_review_inbox();
24634
24534
  init_coordinator_registry();
24635
24535
  init_refine_config();
24636
24536
  init_worktree_bootstrap_config();
24537
+
24538
+ // src/config/repo-settings.ts
24539
+ init_mesh_json_config();
24540
+ init_refine_config();
24541
+ init_worktree_bootstrap_config();
24542
+ init_change_impact_config();
24543
+ function loadRepoSettings(opts) {
24544
+ const workspace = typeof opts.workspace === "string" ? opts.workspace : "";
24545
+ const mesh = opts.mesh;
24546
+ const repoRoot = typeof opts.repoRoot === "string" && opts.repoRoot ? opts.repoRoot : workspace;
24547
+ const meshJson = loadRepoMeshJsonConfig(workspace);
24548
+ return {
24549
+ coordinator: meshJson.config?.coordinator,
24550
+ operatingNotes: meshJson.config?.operatingNotes,
24551
+ limits: meshJson.config?.limits,
24552
+ meshJson,
24553
+ refine: loadMeshRefineConfig(mesh, workspace),
24554
+ worktreeBootstrap: loadMeshWorktreeBootstrapConfig(mesh, workspace),
24555
+ changeImpact: loadChangeImpactConfig(repoRoot)
24556
+ };
24557
+ }
24558
+
24559
+ // src/index.ts
24637
24560
  init_mesh_ledger();
24638
24561
  init_mesh_fast_forward();
24639
24562
 
@@ -48660,6 +48583,21 @@ init_mesh_host_ownership();
48660
48583
  init_worktree_bootstrap_config();
48661
48584
  init_mesh_events();
48662
48585
  init_config();
48586
+ async function decideOssCloneSync(ossCtx, worktreeOssSha, sourceSha, rg) {
48587
+ if (!worktreeOssSha || !sourceSha || worktreeOssSha === sourceSha) return "noop";
48588
+ const isAncestor = async (ancestor, descendant) => {
48589
+ try {
48590
+ await rg(ossCtx, ["merge-base", "--is-ancestor", ancestor, descendant], { timeoutMs: 1e4 });
48591
+ return true;
48592
+ } catch (err) {
48593
+ if (err?.exitCode === 1 || err?.code === 1) return false;
48594
+ throw err;
48595
+ }
48596
+ };
48597
+ if (await isAncestor(sourceSha, worktreeOssSha)) return "skip_rewind";
48598
+ if (await isAncestor(worktreeOssSha, sourceSha)) return "advance";
48599
+ return "skip_diverged";
48600
+ }
48663
48601
  var meshCrudHandlers = {
48664
48602
  list_meshes: async (_ctx, _args) => {
48665
48603
  try {
@@ -48750,7 +48688,8 @@ var meshCrudHandlers = {
48750
48688
  // entry. This is an export scaffold for the operator to review and commit to
48751
48689
  // the repo, NOT an automatic data migration: nothing is written to disk and
48752
48690
  // meshes.json is untouched. The returned `scaffold` (object) + `scaffoldJson`
48753
- // (2-space text) capture the local policy + coordinator prompt override/append.
48691
+ // (2-space text) capture the coordinator prompt override/append (policy is
48692
+ // machine-local and is intentionally NOT exported into mesh.json).
48754
48693
  export_mesh_json_config: async (_ctx, args) => {
48755
48694
  const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
48756
48695
  if (!meshId) return { success: false, error: "meshId required" };
@@ -49121,7 +49060,7 @@ var meshCrudHandlers = {
49121
49060
  }
49122
49061
  };
49123
49062
  const initSubmodules = sourceNode.policy?.initSubmodulesOnClone !== false;
49124
- const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, result.worktreePath);
49063
+ const loadedBootstrap = loadRepoSettings({ workspace: result.worktreePath, mesh }).worktreeBootstrap;
49125
49064
  const runningBootstrapState = {
49126
49065
  status: "running",
49127
49066
  required: loadedBootstrap.config?.required !== false,
@@ -49155,12 +49094,25 @@ var meshCrudHandlers = {
49155
49094
  const ossCtx = { workspace: `${result.worktreePath}/oss`, repoRoot: `${result.worktreePath}/oss`, isGitRepo: true };
49156
49095
  const worktreeOssHeadOut = await rg(ossCtx, ["rev-parse", "HEAD"], { timeoutMs: 1e4 });
49157
49096
  const worktreeOssSha = (typeof worktreeOssHeadOut === "string" ? worktreeOssHeadOut : worktreeOssHeadOut?.stdout ?? "").trim();
49158
- if (worktreeOssSha !== sourceSha) {
49097
+ if (worktreeOssSha && worktreeOssSha !== sourceSha) {
49159
49098
  await rg(ossCtx, ["fetch", `${sourceWorkspace}/oss`, "HEAD"], { timeoutMs: 6e4 });
49160
- await rg(ossCtx, ["checkout", sourceSha], { timeoutMs: 1e4 });
49161
- await rg(worktreeCtx, ["add", "oss"], { timeoutMs: 1e4 });
49162
- await rg(worktreeCtx, ["commit", "-m", "chore: sync oss to source node HEAD on clone"], { timeoutMs: 1e4 });
49163
- console.log(`[mesh] Synced oss submodule to source HEAD ${sourceSha.slice(0, 8)} in worktree`);
49099
+ let ossAction;
49100
+ try {
49101
+ ossAction = await decideOssCloneSync(ossCtx, worktreeOssSha, sourceSha, rg);
49102
+ } catch (decideErr) {
49103
+ ossAction = "skip_diverged";
49104
+ console.warn(`[mesh] oss submodule sync guard could not resolve ancestry (kept fresh worktree HEAD): ${decideErr?.message ?? decideErr}`);
49105
+ }
49106
+ if (ossAction === "advance") {
49107
+ await rg(ossCtx, ["checkout", sourceSha], { timeoutMs: 1e4 });
49108
+ await rg(worktreeCtx, ["add", "oss"], { timeoutMs: 1e4 });
49109
+ await rg(worktreeCtx, ["commit", "-m", "chore: sync oss to source node HEAD on clone"], { timeoutMs: 1e4 });
49110
+ console.log(`[mesh] Advanced oss submodule to newer source HEAD ${sourceSha.slice(0, 8)} in worktree`);
49111
+ } else if (ossAction === "skip_rewind") {
49112
+ 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`);
49113
+ } else if (ossAction === "skip_diverged") {
49114
+ 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)`);
49115
+ }
49164
49116
  }
49165
49117
  }
49166
49118
  } catch (ossErr) {
@@ -64643,6 +64595,7 @@ var V1_CONTRACT_VERSION = "1.0.0";
64643
64595
  loadMeshCoordinatorRegistry,
64644
64596
  loadMeshRefineConfig,
64645
64597
  loadMeshWorktreeBootstrapConfig,
64598
+ loadRepoSettings,
64646
64599
  loadState,
64647
64600
  logCommand,
64648
64601
  machineCoreFromDaemonId,