stratagate-dsh 0.3.45 → 0.3.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugin.js CHANGED
@@ -29,9 +29,9 @@ function volatileIfSupported(schema) {
29
29
  return schema.volatile?.() ?? schema;
30
30
  }
31
31
  var Config = z.object({
32
- dailyNotesEnabled: z.boolean().default(true),
33
- dailyNotesTimeZone: z.string(),
34
- dailyNotesInjectionDays: z.natural().min(1).max(30).default(3),
32
+ dailyNotesEnabled: volatileIfSupported(z.boolean().default(true)),
33
+ dailyNotesTimeZone: volatileIfSupported(z.string()),
34
+ dailyNotesInjectionDays: volatileIfSupported(z.natural().min(1).max(30).default(3)),
35
35
  dailyNotesContextMaxChars: z.natural().min(1024).default(12e3),
36
36
  database: z.string().required(),
37
37
  sessionRoot: z.string(),
@@ -69,6 +69,9 @@ function isLiveConfigValue(value) {
69
69
  return value !== null && typeof value === "object" && "get" in value && typeof value.get === "function";
70
70
  }
71
71
  function resolveConfig(config) {
72
+ const dailyNotesEnabled = liveConfigValue(config.dailyNotesEnabled);
73
+ const dailyNotesTimeZone = liveConfigValue(config.dailyNotesTimeZone);
74
+ const dailyNotesInjectionDays = liveConfigValue(config.dailyNotesInjectionDays);
72
75
  const database = config.database?.trim() ?? "";
73
76
  const sessionRoot = config.sessionRoot?.trim();
74
77
  const namespacePrefix = config.namespacePrefix?.trim() || "dsh";
@@ -80,13 +83,13 @@ function resolveConfig(config) {
80
83
  if (Boolean(provider) !== Boolean(model)) {
81
84
  throw new TypeError("StrataGate provider and model must be configured together");
82
85
  }
83
- if (config.dailyNotesTimeZone !== void 0) new Intl.DateTimeFormat("en-US", { timeZone: config.dailyNotesTimeZone }).format();
86
+ if (dailyNotesTimeZone !== void 0) new Intl.DateTimeFormat("en-US", { timeZone: dailyNotesTimeZone }).format();
84
87
  if (config.dailyNotesContextMaxChars !== void 0 && (!Number.isSafeInteger(config.dailyNotesContextMaxChars) || config.dailyNotesContextMaxChars < 1024)) throw new TypeError("dailyNotesContextMaxChars must be an integer >= 1024");
85
- if (config.dailyNotesInjectionDays !== void 0 && (!Number.isSafeInteger(config.dailyNotesInjectionDays) || config.dailyNotesInjectionDays < 1 || config.dailyNotesInjectionDays > 30)) throw new TypeError("dailyNotesInjectionDays must be an integer between 1 and 30");
88
+ if (dailyNotesInjectionDays !== void 0 && (!Number.isSafeInteger(dailyNotesInjectionDays) || dailyNotesInjectionDays < 1 || dailyNotesInjectionDays > 30)) throw new TypeError("dailyNotesInjectionDays must be an integer between 1 and 30");
86
89
  return {
87
- dailyNotesInjectionDays: config.dailyNotesInjectionDays ?? 3,
88
- dailyNotesEnabled: config.dailyNotesEnabled ?? true,
89
- ...config.dailyNotesTimeZone !== void 0 ? { dailyNotesTimeZone: config.dailyNotesTimeZone } : {},
90
+ dailyNotesInjectionDays: dailyNotesInjectionDays ?? 3,
91
+ dailyNotesEnabled: dailyNotesEnabled ?? true,
92
+ ...dailyNotesTimeZone !== void 0 ? { dailyNotesTimeZone } : {},
90
93
  dailyNotesContextMaxChars: config.dailyNotesContextMaxChars ?? 12e3,
91
94
  database,
92
95
  ...sessionRoot ? { sessionRoot } : {},
@@ -1943,6 +1946,8 @@ var PROFILE_FIELDS = {
1943
1946
  var PROFILE_PROTECTED_SHORT_FIELDS = ["userPreferredName", "assistantPreferredName", "preferredLanguage", "reasoningLanguage", "defaultLocation", "homeCity", "currentCity"];
1944
1947
  var PROFILE_MAINTAINABLE_FIELDS = Object.keys(PROFILE_FIELDS).filter((field) => !PROFILE_PROTECTED_SHORT_FIELDS.includes(field));
1945
1948
  var PROFILE_TOTAL_MAX_LENGTH = 6e3;
1949
+ var PROFILE_TOTAL_MAX_LENGTH_MIN = 2e3;
1950
+ var PROFILE_TOTAL_MAX_LENGTH_MAX = 12e3;
1946
1951
  var PROFILE_MAINTENANCE_INTERVAL_MS = 24 * 60 * 60 * 1e3;
1947
1952
  var PROFILE_MAINTENANCE_TOTAL_THRESHOLD = 4800;
1948
1953
  function profileLength(value) {
@@ -1954,7 +1959,7 @@ function emptyProfile() {
1954
1959
  function isProfileField(value) {
1955
1960
  return Object.prototype.hasOwnProperty.call(PROFILE_FIELDS, value);
1956
1961
  }
1957
- function validateProfile(profile) {
1962
+ function validateProfile(profile, totalMaxLength = PROFILE_TOTAL_MAX_LENGTH) {
1958
1963
  let total = 0;
1959
1964
  for (const field of Object.keys(PROFILE_FIELDS)) {
1960
1965
  if (typeof profile[field] !== "string") throw new TypeError(`${field} must be a string`);
@@ -1962,14 +1967,15 @@ function validateProfile(profile) {
1962
1967
  if (length > PROFILE_FIELDS[field].maxLength) throw new RangeError(`${field} exceeds ${PROFILE_FIELDS[field].maxLength} characters`);
1963
1968
  total += length;
1964
1969
  }
1965
- if (total > PROFILE_TOTAL_MAX_LENGTH) throw new RangeError(`Persistent Profile exceeds ${PROFILE_TOTAL_MAX_LENGTH} characters`);
1970
+ if (total > totalMaxLength) throw new RangeError(`Persistent Profile exceeds ${totalMaxLength} characters`);
1966
1971
  }
1967
- function profileMaintenanceDue(profile, timeBasisAt, now = Date.now()) {
1972
+ function profileMaintenanceDue(profile, timeBasisAt, now = Date.now(), totalMaxLength = PROFILE_TOTAL_MAX_LENGTH) {
1968
1973
  const lengths = Object.keys(PROFILE_FIELDS).map((field) => ({ field, length: profileLength(profile[field]) }));
1969
1974
  const total = lengths.reduce((sum, item) => sum + item.length, 0);
1970
1975
  const maintainableLengths = lengths.filter(({ field }) => PROFILE_MAINTAINABLE_FIELDS.includes(field));
1971
1976
  if (!maintainableLengths.some(({ length }) => length > 0)) return false;
1972
- return timeBasisAt !== null && now - Date.parse(timeBasisAt) >= PROFILE_MAINTENANCE_INTERVAL_MS || total >= PROFILE_MAINTENANCE_TOTAL_THRESHOLD || maintainableLengths.some(({ field, length }) => length >= PROFILE_FIELDS[field].maxLength * 0.8);
1977
+ const totalThreshold = Math.min(PROFILE_MAINTENANCE_TOTAL_THRESHOLD, Math.floor(totalMaxLength * 0.8));
1978
+ return timeBasisAt !== null && now - Date.parse(timeBasisAt) >= PROFILE_MAINTENANCE_INTERVAL_MS || total >= totalThreshold || maintainableLengths.some(({ field, length }) => length >= PROFILE_FIELDS[field].maxLength * 0.8);
1973
1979
  }
1974
1980
  function renderPersistentProfile(profile) {
1975
1981
  const lines = Object.keys(PROFILE_FIELDS).filter((field) => profile[field].length > 0).map((field) => `${PROFILE_FIELDS[field].label}: ${profile[field]}`);
@@ -4368,8 +4374,10 @@ var SqliteStorage = class _SqliteStorage {
4368
4374
  database;
4369
4375
  rawSearchFtsAvailable = false;
4370
4376
  closed = false;
4377
+ profileTotalMaxLength;
4371
4378
  constructor(options) {
4372
4379
  this.graphPolicy = options.graphPolicy;
4380
+ this.profileTotalMaxLength = Number.isSafeInteger(options.profileTotalMaxLength) && options.profileTotalMaxLength > 0 ? options.profileTotalMaxLength : PROFILE_TOTAL_MAX_LENGTH;
4373
4381
  if (!options.filename.trim()) throw new TypeError("SQLite filename must not be empty");
4374
4382
  this.readonly = options.readonly ?? false;
4375
4383
  this.filename = options.filename === ":memory:" ? ":memory:" : resolve(options.filename);
@@ -5043,7 +5051,7 @@ var SqliteStorage = class _SqliteStorage {
5043
5051
  if (expectedValue !== void 0 && oldValue !== expectedValue) return { field, value: oldValue, modified: false, conflict: true };
5044
5052
  if (oldValue === value) return { field, value, modified: false };
5045
5053
  profile[field] = value;
5046
- validateProfile(profile);
5054
+ validateProfile(profile, this.profileTotalMaxLength);
5047
5055
  const now = (/* @__PURE__ */ new Date()).toISOString();
5048
5056
  this.writeProfileField(field, oldValue, value, source, sourceMessageId ?? null, now);
5049
5057
  const isNonempty = Object.values(profile).some((entry) => entry.length > 0);
@@ -5060,7 +5068,7 @@ var SqliteStorage = class _SqliteStorage {
5060
5068
  /** Compare the complete input snapshot before writing a model result. */
5061
5069
  applyProfileMaintenance(expected, proposed, now = (/* @__PURE__ */ new Date()).toISOString()) {
5062
5070
  this.assertOpen();
5063
- validateProfile(proposed);
5071
+ validateProfile(proposed, this.profileTotalMaxLength);
5064
5072
  if (Object.keys(proposed).length !== Object.keys(PROFILE_FIELDS).length || Object.keys(proposed).some((field) => !isProfileField(field))) throw new TypeError("Maintenance returned unknown or missing Profile fields");
5065
5073
  for (const field of PROFILE_PROTECTED_SHORT_FIELDS) {
5066
5074
  if (proposed[field].trim() !== expected[field].trim()) throw new Error(`Profile maintenance changed protected short field ${field}`);
@@ -5081,7 +5089,7 @@ var SqliteStorage = class _SqliteStorage {
5081
5089
  const failed = this.database.prepare("SELECT input_json, failure_count, next_retry_at FROM persistent_profile_maintenance_failures WHERE id = 1").get();
5082
5090
  if (failed?.input_json === JSON.stringify(profile) && now < Date.parse(failed.next_retry_at)) return false;
5083
5091
  const state = this.getProfileMaintenanceState();
5084
- if (!profileMaintenanceDue(profile, state?.lastSucceededAt ?? this.getProfileMaintenanceStartedAt(), now)) return false;
5092
+ if (!profileMaintenanceDue(profile, state?.lastSucceededAt ?? this.getProfileMaintenanceStartedAt(), now, this.profileTotalMaxLength)) return false;
5085
5093
  if (!state) return true;
5086
5094
  const maintained = JSON.parse(state.inputJson);
5087
5095
  return PROFILE_MAINTAINABLE_FIELDS.some((field) => maintained[field] !== profile[field]);
@@ -12185,17 +12193,17 @@ Use project scope for repository decisions, user scope for stable preferences/id
12185
12193
  }));
12186
12194
  return { candidates: parsed.candidates, reason: text2(raw.reason, parsed.reason) };
12187
12195
  };
12188
- async maintainProfile(profile) {
12196
+ async maintainProfile(profile, totalMaxLength = PROFILE_TOTAL_MAX_LENGTH) {
12189
12197
  const raw = object(await this.callStructured(
12190
12198
  "profileMaintenance",
12191
- `You maintain only the supplied StrataGate Persistent Profile. Call ${STRUCTURED_TOOLS.profileMaintenance.name} exactly once with all ${Object.keys(PROFILE_FIELDS).length} string fields. You may deduplicate, merge repeated meaning, shorten redundant wording, and improve organization. Preserve every unique fact, uncertainty, constraint, and instruction. Never infer or add facts, broaden meaning, or read Event, Graph, or conversation history. If two statements might conflict or cannot safely merge, retain both. Keep ${PROFILE_PROTECTED_SHORT_FIELDS.join(", ")} unchanged except necessary whitespace cleanup. defaultLocation is the reference when a task specifies no location and no currentCity is set; homeCity is the stable city of residence. They are independent, neither means temporary/current location, and travel must not overwrite either. currentCity is the current location, possibly temporary travel or business travel; it persists across sessions until the user updates or clears it. Never expire currentCity automatically, clear it because a trip seems temporary, or copy it into either stable field. preferredLanguage and reasoningLanguage are independent: never infer, copy, or merge either language field into the other. reasoningLanguage is only for user-visible reasoning/thinking text when supported, not hidden chain-of-thought. Character limits (Unicode code points): ${JSON.stringify(Object.fromEntries(Object.entries(PROFILE_FIELDS).map(([field, spec]) => [field, spec.maxLength])))}. Total maximum: 6000. If safe compression is impossible, return the original value.`,
12199
+ `You maintain only the supplied StrataGate Persistent Profile. Call ${STRUCTURED_TOOLS.profileMaintenance.name} exactly once with all ${Object.keys(PROFILE_FIELDS).length} string fields. You may deduplicate, merge repeated meaning, shorten redundant wording, and improve organization. Preserve every unique fact, uncertainty, constraint, and instruction. Never infer or add facts, broaden meaning, or read Event, Graph, or conversation history. If two statements might conflict or cannot safely merge, retain both. Keep ${PROFILE_PROTECTED_SHORT_FIELDS.join(", ")} unchanged except necessary whitespace cleanup. defaultLocation is the reference when a task specifies no location and no currentCity is set; homeCity is the stable city of residence. They are independent, neither means temporary/current location, and travel must not overwrite either. currentCity is the current location, possibly temporary travel or business travel; it persists across sessions until the user updates or clears it. Never expire currentCity automatically, clear it because a trip seems temporary, or copy it into either stable field. preferredLanguage and reasoningLanguage are independent: never infer, copy, or merge either language field into the other. reasoningLanguage is only for user-visible reasoning/thinking text when supported, not hidden chain-of-thought. Character limits (Unicode code points): ${JSON.stringify(Object.fromEntries(Object.entries(PROFILE_FIELDS).map(([field, spec]) => [field, spec.maxLength])))}. Total maximum: ${totalMaxLength}. If safe compression is impossible, return the original value.`,
12192
12200
  { profile, fieldDefinitions: PROFILE_FIELDS }
12193
12201
  ));
12194
12202
  if (Object.keys(raw).length !== Object.keys(PROFILE_FIELDS).length || Object.keys(raw).some((field) => !(field in PROFILE_FIELDS))) {
12195
12203
  throw new Error("Profile maintenance returned unexpected fields");
12196
12204
  }
12197
12205
  const proposed = raw;
12198
- validateProfile(proposed);
12206
+ validateProfile(proposed, totalMaxLength);
12199
12207
  for (const field of PROFILE_PROTECTED_SHORT_FIELDS) {
12200
12208
  if (proposed[field].trim() !== profile[field].trim()) throw new Error(`Profile maintenance changed protected short field ${field}`);
12201
12209
  }
@@ -12916,6 +12924,25 @@ var DailyNotes = class {
12916
12924
  throw error;
12917
12925
  }
12918
12926
  }
12927
+ /** 总览用:事项条数与最近一次写入时间。只读本地 Markdown,不建证据批次。 */
12928
+ async usage(namespace) {
12929
+ const dates = await this.dates(namespace);
12930
+ let count = 0;
12931
+ let updatedAt = null;
12932
+ for (const date of dates) {
12933
+ let content;
12934
+ try {
12935
+ content = await this.load(namespace, date);
12936
+ } catch (error) {
12937
+ if (missing(error)) continue;
12938
+ throw error;
12939
+ }
12940
+ count += items(content).length;
12941
+ const day = Date.parse(`${date}T00:00:00+08:00`);
12942
+ if (Number.isFinite(day) && (updatedAt === null || day > Date.parse(updatedAt))) updatedAt = new Date(day).toISOString();
12943
+ }
12944
+ return { items: count, updatedAt };
12945
+ }
12919
12946
  load(namespace, date) {
12920
12947
  return readFile(join(this.directory(namespace), `${validDate(date)}.md`), "utf8");
12921
12948
  }
@@ -13851,6 +13878,11 @@ function sourceContext(event, snapshot) {
13851
13878
  }
13852
13879
 
13853
13880
  // src/runtime.ts
13881
+ function emptyProfileOverview() {
13882
+ const profile = emptyProfile();
13883
+ const revisions = Object.fromEntries(Object.keys(PROFILE_FIELDS).map((field) => [field, 0]));
13884
+ return { profile, revisions };
13885
+ }
13854
13886
  function dreamingConflict(error) {
13855
13887
  return error instanceof Error && /^(Directory changed during Dreaming|Dreaming sources changed|Dreaming evidence changed)/.test(error.message);
13856
13888
  }
@@ -13882,6 +13914,7 @@ var VECTOR_SETTING_KEYS = [
13882
13914
  "rerankModel"
13883
13915
  ];
13884
13916
  var VECTOR_SECRET_MASK = "********";
13917
+ var PROFILE_LIMIT_SETTING_KEY = "profile.totalMaxLength";
13885
13918
  function projectKey(cwd) {
13886
13919
  const canonical2 = resolve3(cwd ?? process.cwd()).replaceAll("\\", "/").toLowerCase();
13887
13920
  return createHash6("sha256").update(canonical2).digest("hex").slice(0, 20);
@@ -14031,10 +14064,31 @@ var StrataGateRuntime = class _StrataGateRuntime {
14031
14064
  }
14032
14065
  return snapshot;
14033
14066
  }
14067
+ /**
14068
+ * Apply a live daily-notes edit. The time zone and lookback window are
14069
+ * captured by DailyNotes, so a changed value needs a fresh reader; cached
14070
+ * session snapshots are discarded so the next session start sees the edit.
14071
+ */
14072
+ applyLiveDailyNotes(enabled, timeZone, injectionDays) {
14073
+ if (injectionDays !== void 0 && (!Number.isSafeInteger(injectionDays) || injectionDays < 1 || injectionDays > 30)) {
14074
+ throw new TypeError("dailyNotesInjectionDays must be an integer between 1 and 30");
14075
+ }
14076
+ const nextTimeZone = timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
14077
+ const nextDays = injectionDays ?? this.dailyNotes.injectionDays;
14078
+ const nextEnabled = enabled ?? this.dailyNotesEnabled;
14079
+ if (nextTimeZone === this.dailyNotes.timeZone && nextDays === this.dailyNotes.injectionDays && nextEnabled === this.dailyNotesEnabled) return;
14080
+ this.config.dailyNotesEnabled = nextEnabled;
14081
+ if (timeZone !== void 0) this.config.dailyNotesTimeZone = timeZone;
14082
+ else delete this.config.dailyNotesTimeZone;
14083
+ this.config.dailyNotesInjectionDays = nextDays;
14084
+ this.dailyNotes = new DailyNotes(this.config.database, nextTimeZone, this.config.dailyNotesContextMaxChars, nextDays);
14085
+ this.dailySnapshots.clear();
14086
+ }
14034
14087
  diagnostics;
14035
14088
  diagnosticSessionNamespaces = /* @__PURE__ */ new Map();
14036
14089
  diagnosticMemoryEstimates = /* @__PURE__ */ new Map();
14037
14090
  profileStorage;
14091
+ profileTotalMaxLength = PROFILE_TOTAL_MAX_LENGTH;
14038
14092
  folder = new TurnFolder();
14039
14093
  spaces = /* @__PURE__ */ new Map();
14040
14094
  batches = /* @__PURE__ */ new Map();
@@ -14094,7 +14148,8 @@ var StrataGateRuntime = class _StrataGateRuntime {
14094
14148
  return this.graphMetadata;
14095
14149
  }
14096
14150
  graphSettings() {
14097
- return this.graphMetadata?.graphSettings() ?? readGraphSettings(this.config.database);
14151
+ if (this.graphMetadata) return this.graphMetadata.graphSettings();
14152
+ return readGraphSettings(this.config.database);
14098
14153
  }
14099
14154
  get graphEnabled() {
14100
14155
  return this.graphSettings().enabled;
@@ -14222,7 +14277,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
14222
14277
  const run = (async () => {
14223
14278
  const current = this.profileStore().getPersistentProfile();
14224
14279
  try {
14225
- const proposed = await this.models.runDetached("stratagate-profile-maintenance", () => this.models.maintainProfile(current));
14280
+ const proposed = await this.models.runDetached("stratagate-profile-maintenance", () => this.models.maintainProfile(current, this.profileTotalMaxLength));
14226
14281
  return this.profileStore().applyProfileMaintenance(current, proposed, new Date(now).toISOString());
14227
14282
  } catch (error) {
14228
14283
  this.profileStore().recordProfileMaintenanceFailure(current, now);
@@ -14420,21 +14475,64 @@ var StrataGateRuntime = class _StrataGateRuntime {
14420
14475
  return this.profileStore().getPersistentProfile();
14421
14476
  }
14422
14477
  getProfileSnapshot() {
14423
- return this.profileStore().getProfileSnapshot();
14478
+ return this.readProfileOverview()?.snapshot ?? this.profileStore().getProfileSnapshot();
14424
14479
  }
14425
14480
  renderProfileContext() {
14426
14481
  return renderPersistentProfile(this.getPersistentProfile());
14427
14482
  }
14483
+ getProfileTotalMaxLength() {
14484
+ return this.profileTotalMaxLength;
14485
+ }
14486
+ /** Persist the install-wide Profile capacity and apply it to the live store. */
14487
+ adminSetProfileTotalMaxLength(value) {
14488
+ if (!Number.isSafeInteger(value) || value < PROFILE_TOTAL_MAX_LENGTH_MIN || value > PROFILE_TOTAL_MAX_LENGTH_MAX) {
14489
+ throw new RangeError(`profile character limit must be an integer between ${PROFILE_TOTAL_MAX_LENGTH_MIN} and ${PROFILE_TOTAL_MAX_LENGTH_MAX}`);
14490
+ }
14491
+ const used = Object.values(this.getPersistentProfile()).reduce((sum, entry) => sum + Array.from(entry).length, 0);
14492
+ if (value < used) throw new RangeError(`profile character limit cannot be lower than the ${used} characters already used`);
14493
+ if (value === this.profileTotalMaxLength) return value;
14494
+ this.writeRuntimeSetting(PROFILE_LIMIT_SETTING_KEY, String(value));
14495
+ this.profileTotalMaxLength = value;
14496
+ if (this.profileStorage) {
14497
+ const previous = this.profileStorage;
14498
+ this.profileStorage = new SqliteStorage({ filename: this.config.database, graphPolicy: (namespace) => this.graphPolicyFor(namespace), profileTotalMaxLength: value });
14499
+ void previous.close();
14500
+ }
14501
+ return value;
14502
+ }
14428
14503
  getProfileChanges() {
14504
+ const stored = this.readProfileOverview();
14505
+ if (stored) return stored.changes;
14429
14506
  return this.profileStore().getProfileChanges();
14430
14507
  }
14508
+ /** 只读已有画像;表不存在就返回 null,绝不打开可写存储。 */
14509
+ readProfileOverview() {
14510
+ if (this.config.database === ":memory:" || !existsSync2(this.config.database)) return null;
14511
+ const database = new DatabaseSync5(this.config.database, { readOnly: true });
14512
+ try {
14513
+ const names = new Set(database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('persistent_profile', 'persistent_profile_changes')").all().map((row) => row.name));
14514
+ if (!names.has("persistent_profile") || !names.has("persistent_profile_changes")) return null;
14515
+ const snapshot = emptyProfileOverview();
14516
+ const rows = database.prepare("SELECT p.field, p.value, COALESCE(r.revision, 0) AS revision FROM persistent_profile p LEFT JOIN (SELECT field, MAX(id) AS revision FROM persistent_profile_changes GROUP BY field) r ON r.field = p.field").all();
14517
+ for (const row of rows) if (isProfileField(row.field)) {
14518
+ snapshot.profile[row.field] = row.value;
14519
+ snapshot.revisions[row.field] = row.revision;
14520
+ }
14521
+ const changes = database.prepare("SELECT field, old_value, new_value, source, updated_at, source_message_id FROM persistent_profile_changes ORDER BY id").all().map((row) => ({ field: row.field, oldValue: row.old_value, newValue: row.new_value, source: row.source, updatedAt: row.updated_at, sourceMessageId: row.source_message_id }));
14522
+ return { snapshot, changes };
14523
+ } catch {
14524
+ return null;
14525
+ } finally {
14526
+ database.close();
14527
+ }
14528
+ }
14431
14529
  updatePersistentProfile(field, value, source, sourceMessageId, expectedValue, expectedRevision) {
14432
14530
  const result = this.profileStore().updateProfileField(field, value, source, sourceMessageId, expectedValue, expectedRevision);
14433
14531
  if (result.modified) this.wakeBackgroundWorker();
14434
14532
  return result;
14435
14533
  }
14436
14534
  profileStore() {
14437
- return this.profileStorage ??= new SqliteStorage({ filename: this.config.database, graphPolicy: (namespace) => this.graphPolicyFor(namespace) });
14535
+ return this.profileStorage ??= new SqliteStorage({ filename: this.config.database, graphPolicy: (namespace) => this.graphPolicyFor(namespace), profileTotalMaxLength: this.profileTotalMaxLength });
14438
14536
  }
14439
14537
  updatePersistentProfileFromTool(field, value) {
14440
14538
  return this.updatePersistentProfile(field, value, "agent_tool");
@@ -16048,6 +16146,10 @@ var StrataGateRuntime = class _StrataGateRuntime {
16048
16146
  this.blockTurnSize = metadata2.blockTurnSize() ?? this.config.blockTurnSize;
16049
16147
  this.blockDecayLambda = metadata2.blockDecayLambda() ?? this.config.blockDecayLambda;
16050
16148
  this.agentMemoryRetrievalWeight = metadata2.agentMemoryRetrievalWeight() ?? this.config.agentMemoryRetrievalWeight ?? 1;
16149
+ const savedProfileLimit = Number(this.readRuntimeSetting(PROFILE_LIMIT_SETTING_KEY));
16150
+ if (Number.isSafeInteger(savedProfileLimit) && savedProfileLimit >= PROFILE_TOTAL_MAX_LENGTH_MIN && savedProfileLimit <= PROFILE_TOTAL_MAX_LENGTH_MAX) {
16151
+ this.profileTotalMaxLength = savedProfileLimit;
16152
+ }
16051
16153
  const storedEmbeddingUrl = this.readVectorSetting("embeddingUrl");
16052
16154
  if (storedEmbeddingUrl !== null) this.config.embeddingUrl = storedEmbeddingUrl;
16053
16155
  const storedEmbeddingKey = this.readVectorSetting("embeddingKey");
@@ -16712,6 +16814,43 @@ var StrataGateRuntime = class _StrataGateRuntime {
16712
16814
  database.close();
16713
16815
  }
16714
16816
  }
16817
+ /** Read one scalar runtime setting from the shared settings table. */
16818
+ readRuntimeSetting(key) {
16819
+ if (this.config.database === ":memory:" || !existsSync2(this.config.database)) return null;
16820
+ const database = new DatabaseSync5(this.config.database, { readOnly: true });
16821
+ try {
16822
+ if (!database.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'stratagate_dsh_settings'").get()) return null;
16823
+ const row = database.prepare("SELECT value FROM stratagate_dsh_settings WHERE key = ?").get(key);
16824
+ return row?.value ?? null;
16825
+ } catch {
16826
+ return null;
16827
+ } finally {
16828
+ database.close();
16829
+ }
16830
+ }
16831
+ /** Persist one scalar runtime setting, creating the settings table on first use. */
16832
+ writeRuntimeSetting(key, value) {
16833
+ if (this.config.database === ":memory:") return;
16834
+ this.profileStore();
16835
+ const database = new DatabaseSync5(this.config.database);
16836
+ try {
16837
+ database.exec("PRAGMA busy_timeout = 5000");
16838
+ database.exec(`
16839
+ CREATE TABLE IF NOT EXISTS stratagate_dsh_settings (
16840
+ key TEXT PRIMARY KEY,
16841
+ value TEXT NOT NULL,
16842
+ updated_at TEXT NOT NULL
16843
+ ) STRICT
16844
+ `);
16845
+ database.prepare(`
16846
+ INSERT INTO stratagate_dsh_settings (key, value, updated_at)
16847
+ VALUES (?, ?, ?)
16848
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
16849
+ `).run(key, value, (/* @__PURE__ */ new Date()).toISOString());
16850
+ } finally {
16851
+ database.close();
16852
+ }
16853
+ }
16715
16854
  adminWorkspaceName(namespace) {
16716
16855
  const remembered = this.workspaceNames.get(namespace);
16717
16856
  if (remembered) return remembered;
@@ -18738,6 +18877,114 @@ function clusterKnowledgeGraph(rawNodes, rawEdges) {
18738
18877
  }).sort((left, right) => right.nodeIds.length - left.nodeIds.length || left.label.localeCompare(right.label));
18739
18878
  }
18740
18879
 
18880
+ // src/memory-overview.ts
18881
+ var MEMORY_USAGE_WINDOW_DAYS = 7;
18882
+ var MEMORY_HEATMAP_DAYS = 28;
18883
+ var TIME_ZONE = "Asia/Shanghai";
18884
+ var DAY_MS = 864e5;
18885
+ function dayKey(time) {
18886
+ return new Intl.DateTimeFormat("en-CA", { timeZone: TIME_ZONE, year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date(time));
18887
+ }
18888
+ function dayStart(day) {
18889
+ return Date.parse(`${day}T00:00:00+08:00`);
18890
+ }
18891
+ function shiftDay(day, offset) {
18892
+ return dayKey(dayStart(day) + offset * DAY_MS);
18893
+ }
18894
+ function timestamp(value) {
18895
+ if (!value) return null;
18896
+ const parsed = Date.parse(value);
18897
+ return Number.isFinite(parsed) ? parsed : null;
18898
+ }
18899
+ function latestTimestamp(values) {
18900
+ let latest = null;
18901
+ for (const value of values) {
18902
+ const parsed = timestamp(value ?? void 0);
18903
+ if (parsed !== null && (latest === null || parsed > latest)) latest = parsed;
18904
+ }
18905
+ return latest;
18906
+ }
18907
+ var iso = (value) => value === null ? null : new Date(value).toISOString();
18908
+ function answerAdoptionKey(receipt) {
18909
+ const sessionId = receipt.audit?.sessionId?.trim();
18910
+ const turn = receipt.audit?.turn;
18911
+ if (sessionId && Number.isSafeInteger(turn) && turn >= 0) return `answer:${sessionId}#${turn}`;
18912
+ return `receipt:${receipt.id}`;
18913
+ }
18914
+ function answerAdoptions(receipts) {
18915
+ const byAnswer = /* @__PURE__ */ new Map();
18916
+ for (const receipt of receipts) {
18917
+ if (receipt.eventIds.length === 0 && receipt.elementIds.length === 0) continue;
18918
+ const at = timestamp(receipt.createdAt);
18919
+ if (at === null) continue;
18920
+ const key = answerAdoptionKey(receipt);
18921
+ const existing = byAnswer.get(key);
18922
+ if (!existing) {
18923
+ byAnswer.set(key, { key, at, eventIds: [...new Set(receipt.eventIds)], elementIds: [...new Set(receipt.elementIds)] });
18924
+ continue;
18925
+ }
18926
+ existing.at = Math.max(existing.at, at);
18927
+ for (const id of receipt.eventIds) if (!existing.eventIds.includes(id)) existing.eventIds.push(id);
18928
+ for (const id of receipt.elementIds) if (!existing.elementIds.includes(id)) existing.elementIds.push(id);
18929
+ }
18930
+ return [...byAnswer.values()].sort((left, right) => right.at - left.at || left.key.localeCompare(right.key));
18931
+ }
18932
+ function visibleEvents(snapshot, agentMemoryWeight) {
18933
+ return [...snapshot.events, ...agentMemoryWeight > 0 ? snapshot.agentEvents : []].filter((event) => event.status === "active" || event.status === "superseded");
18934
+ }
18935
+ function directoryChapters(snapshot, events) {
18936
+ try {
18937
+ const directory = new MemoryTopicDirectory();
18938
+ directory.restore(snapshot.memoryTopicState);
18939
+ const state = directory.snapshot(events);
18940
+ directory.restore(state);
18941
+ return directory.list(events).filter((topic) => !topic.isFallback);
18942
+ } catch {
18943
+ return [];
18944
+ }
18945
+ }
18946
+ function memoryOverview(snapshot, extras = {}, options = {}) {
18947
+ const now = options.now ?? Date.now();
18948
+ const agentMemoryWeight = options.agentMemoryWeight ?? 1;
18949
+ const events = visibleEvents(snapshot, agentMemoryWeight);
18950
+ const titles = /* @__PURE__ */ new Map();
18951
+ for (const event of [...snapshot.events, ...snapshot.agentEvents]) {
18952
+ const title = event.title?.trim();
18953
+ if (title) titles.set(event.id, title);
18954
+ }
18955
+ const longTerm = answerAdoptions(snapshot.usageReceipts);
18956
+ const today = dayKey(now);
18957
+ const heatmap = Array.from({ length: MEMORY_HEATMAP_DAYS }, (_, index) => shiftDay(today, index - (MEMORY_HEATMAP_DAYS - 1)));
18958
+ const counts = new Map(heatmap.map((day) => [day, 0]));
18959
+ for (const adoption of longTerm) {
18960
+ const day = dayKey(adoption.at);
18961
+ if (counts.has(day)) counts.set(day, counts.get(day) + 1);
18962
+ }
18963
+ const elementNames = new Map(snapshot.elements.map((element) => [element.id, element.name]));
18964
+ const recallTitle = (adoption) => {
18965
+ const eventId = adoption.eventIds.find((id) => titles.has(id));
18966
+ if (eventId) return titles.get(eventId);
18967
+ const elementId = adoption.elementIds.find((id) => elementNames.has(id));
18968
+ return elementId ? elementNames.get(elementId) : null;
18969
+ };
18970
+ const latest = longTerm.find((adoption) => recallTitle(adoption) !== null);
18971
+ const chapters = extras.directory !== void 0 ? null : directoryChapters(snapshot, events);
18972
+ return {
18973
+ windowDays: MEMORY_USAGE_WINDOW_DAYS,
18974
+ heatmapDays: MEMORY_HEATMAP_DAYS,
18975
+ answeredLast7Days: heatmap.slice(-MEMORY_USAGE_WINDOW_DAYS).reduce((sum, day) => sum + counts.get(day), 0),
18976
+ lastRecall: latest ? { title: recallTitle(latest), at: new Date(latest.at).toISOString() } : null,
18977
+ heatmap: heatmap.map((day) => ({ day, answers: counts.get(day) })),
18978
+ layers: {
18979
+ profile: extras.profile ?? null,
18980
+ directory: extras.directory !== void 0 ? extras.directory : { chapters: chapters.length, updatedAt: iso(latestTimestamp(chapters.map((chapter) => chapter.updatedAt))) },
18981
+ session: { blocks: snapshot.blocks.length, updatedAt: iso(latestTimestamp(snapshot.blocks.map((block) => block.createdAt))) },
18982
+ shortTerm: extras.shortTerm ?? null,
18983
+ longTerm: { events: events.length, answers: longTerm.length, updatedAt: iso(latestTimestamp(events.map((event) => event.updatedAt))) }
18984
+ }
18985
+ };
18986
+ }
18987
+
18741
18988
  // src/web.ts
18742
18989
  var LEGACY_THREAD_ID = "__legacy__";
18743
18990
  var nodeRequire2 = createRequire3(import.meta.url);
@@ -19055,22 +19302,22 @@ var AdminHttpError = class extends Error {
19055
19302
  details;
19056
19303
  };
19057
19304
  function topicDirectoryProjection(snapshot, agentMemoryWeight) {
19058
- const visibleEvents = [...snapshot.events, ...agentMemoryWeight > 0 ? snapshot.agentEvents : []].filter((event) => event.status === "active" || event.status === "superseded");
19305
+ const visibleEvents2 = [...snapshot.events, ...agentMemoryWeight > 0 ? snapshot.agentEvents : []].filter((event) => event.status === "active" || event.status === "superseded");
19059
19306
  const directory = new MemoryTopicDirectory();
19060
19307
  directory.restore(snapshot.memoryTopicState);
19061
- const state = directory.snapshot(visibleEvents);
19308
+ const state = directory.snapshot(visibleEvents2);
19062
19309
  directory.restore(state);
19063
- let topics = directory.list(visibleEvents);
19310
+ let topics = directory.list(visibleEvents2);
19064
19311
  if (agentMemoryWeight <= 0) {
19065
19312
  topics = topics.filter((topic) => !topic.isFallback);
19066
19313
  const assigned = new Set(topics.flatMap((topic) => topic.sourceEventIds));
19067
- topics.push(...new MemoryTopicDirectory().list(visibleEvents.filter(({ id }) => !assigned.has(id))));
19314
+ topics.push(...new MemoryTopicDirectory().list(visibleEvents2.filter(({ id }) => !assigned.has(id))));
19068
19315
  }
19069
19316
  topics = sortMemoryTopics(topics);
19070
19317
  const chapters = topics.filter((topic) => !topic.isFallback);
19071
19318
  const pendingIds = new Set(topics.filter((topic) => topic.isFallback).flatMap((topic) => topic.sourceEventIds));
19072
- const pending = visibleEvents.filter(({ id }) => pendingIds.has(id)).sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id));
19073
- const versions = new Map(visibleEvents.map((event) => [event.id, memoryTopicEventFingerprint(event)]));
19319
+ const pending = visibleEvents2.filter(({ id }) => pendingIds.has(id)).sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id));
19320
+ const versions = new Map(visibleEvents2.map((event) => [event.id, memoryTopicEventFingerprint(event)]));
19074
19321
  const frozen = state.bootstrap?.projectorVersion === MEMORY_TOPIC_PROJECTOR_VERSION ? state.bootstrap : null;
19075
19322
  const relationKey = (topicId, id, version) => JSON.stringify([topicId ?? null, id, version]);
19076
19323
  const backfillRelations = Object.entries(state.sectionBackfill ?? {}).flatMap(([topicId, pending2]) => Object.entries(pending2).filter(([id, version]) => versions.get(id) === version).map(([id, version]) => ({ topicId, id, version })));
@@ -19121,7 +19368,7 @@ function topicDirectoryProjection(snapshot, agentMemoryWeight) {
19121
19368
  agentMemoryWeight
19122
19369
  })).digest("hex");
19123
19370
  return {
19124
- visibleEvents,
19371
+ visibleEvents: visibleEvents2,
19125
19372
  pending,
19126
19373
  chapters,
19127
19374
  failures,
@@ -19129,7 +19376,7 @@ function topicDirectoryProjection(snapshot, agentMemoryWeight) {
19129
19376
  navigationOnly: true,
19130
19377
  dreaming: dreamingStatus(snapshot.memoryTopicState?.dreaming),
19131
19378
  revision,
19132
- context: renderMemoryDirectory(topics, visibleEvents),
19379
+ context: renderMemoryDirectory(topics, visibleEvents2),
19133
19380
  topics: chapters.map((topic) => ({
19134
19381
  id: topic.id,
19135
19382
  title: topic.title,
@@ -19264,12 +19511,50 @@ function liveGraphProjection(snapshot, processing = true) {
19264
19511
  }
19265
19512
  };
19266
19513
  }
19514
+ function latestIso(values) {
19515
+ let latest = Number.NEGATIVE_INFINITY;
19516
+ for (const value of values) {
19517
+ const parsed = value ? Date.parse(value) : Number.NaN;
19518
+ if (Number.isFinite(parsed) && parsed > latest) latest = parsed;
19519
+ }
19520
+ return Number.isFinite(latest) ? new Date(latest).toISOString() : null;
19521
+ }
19522
+ async function memoryOverviewRows(runtime, entries) {
19523
+ const result = /* @__PURE__ */ new Map();
19524
+ let profile = null;
19525
+ try {
19526
+ const snapshot = runtime.getProfileSnapshot?.();
19527
+ if (snapshot) {
19528
+ const characters = Object.keys(PROFILE_FIELDS).reduce((sum, field) => sum + profileLength(snapshot.profile[field] ?? ""), 0);
19529
+ const updatedAt = runtime.getProfileChanges?.().map((change) => Date.parse(change.updatedAt)).filter((value) => Number.isFinite(value)).reduce((latest, value) => Math.max(latest, value), Number.NEGATIVE_INFINITY);
19530
+ profile = { characters, updatedAt: updatedAt !== void 0 && Number.isFinite(updatedAt) ? new Date(updatedAt).toISOString() : null };
19531
+ }
19532
+ } catch {
19533
+ profile = null;
19534
+ }
19535
+ await Promise.all(entries.map(async ({ namespace }) => {
19536
+ let shortTerm = null;
19537
+ try {
19538
+ const notes = runtime.dailyNotes;
19539
+ if (notes) {
19540
+ const usage = await notes.usage(namespace);
19541
+ shortTerm = { enabled: runtime.dailyNotesEnabled !== false, ...usage };
19542
+ }
19543
+ } catch {
19544
+ shortTerm = null;
19545
+ }
19546
+ result.set(namespace, { profile, shortTerm });
19547
+ }));
19548
+ return result;
19549
+ }
19267
19550
  async function overview(runtime, cachedEntries) {
19268
- const entries = cachedEntries ?? await Promise.all((await runtime.adminNamespaces()).map(async (namespace) => ({
19551
+ const loaded = cachedEntries ?? await Promise.all((await runtime.adminNamespaces()).map(async (namespace) => ({
19269
19552
  namespace,
19270
19553
  revision: 0,
19271
19554
  snapshot: await runtime.adminSnapshot(namespace)
19272
19555
  })));
19556
+ const entries = loaded.flatMap((entry) => entry.snapshot ? [entry] : []);
19557
+ const memoryOverviewByNamespace = await memoryOverviewRows(runtime, entries);
19273
19558
  const rows = [];
19274
19559
  for (const { namespace, snapshot } of entries) {
19275
19560
  if (!snapshot) continue;
@@ -19397,11 +19682,18 @@ async function overview(runtime, cachedEntries) {
19397
19682
  ].sort();
19398
19683
  let topicDirectoryRevision = null;
19399
19684
  let topicDirectoryReadError = false;
19685
+ let directoryLayer = null;
19400
19686
  try {
19401
- topicDirectoryRevision = topicDirectoryProjection(snapshot, runtime.adminAgentMemoryRetrievalWeight?.() ?? 1).data.revision;
19687
+ const projection = topicDirectoryProjection(snapshot, runtime.adminAgentMemoryRetrievalWeight?.() ?? 1);
19688
+ topicDirectoryRevision = projection.data.revision;
19689
+ directoryLayer = {
19690
+ chapters: projection.chapters.length,
19691
+ updatedAt: latestIso(projection.chapters.map((chapter) => chapter.updatedAt))
19692
+ };
19402
19693
  } catch {
19403
19694
  topicDirectoryReadError = true;
19404
19695
  }
19696
+ const usage = memoryOverviewByNamespace.get(namespace);
19405
19697
  rows.push({
19406
19698
  namespace,
19407
19699
  duplicateRepair: runtime.adminDuplicateRepairStatus?.(namespace) ?? null,
@@ -19431,6 +19723,11 @@ async function overview(runtime, cachedEntries) {
19431
19723
  longTermExtractionGap: snapshot.extractionJobs.some((job) => derivationJobState(job, job.status === "succeeded" || job.status === "skipped") === "terminal-failed" && snapshot.blocks.some((block) => block.id === job.blockId && block.shouldExtract === true)),
19432
19724
  usageReceipts: snapshot.usageReceipts.length,
19433
19725
  memoryUseCount: snapshot.usageReceipts.filter((receipt) => receipt.eventIds.length > 0 || receipt.elementIds.length > 0).length,
19726
+ memoryOverview: usage ? memoryOverview(snapshot, {
19727
+ profile: usage.profile,
19728
+ shortTerm: usage.shortTerm,
19729
+ ...directoryLayer ? { directory: directoryLayer } : {}
19730
+ }, { agentMemoryWeight: runtime.adminAgentMemoryRetrievalWeight?.() ?? 1 }) : null,
19434
19731
  failedJobs,
19435
19732
  processingJobs,
19436
19733
  failedJobDetails,
@@ -19500,8 +19797,9 @@ async function updateSettings(runtime, url, req) {
19500
19797
  const hasBody = req.body !== void 0 || typeof req[Symbol.asyncIterator] === "function";
19501
19798
  const body = hasBody ? await jsonBody(req, "Embedding settings") : {};
19502
19799
  const suppliedVectorParams = vectorParams.filter((name2) => Object.hasOwn(body, name2));
19503
- if (rawTurnSize === void 0 && rawLambda === void 0 && rawAgentWeight === void 0 && suppliedVectorParams.length === 0) {
19504
- throw new AdminHttpError(400, "blockTurnSize, blockDecayLambda, agentMemoryRetrievalWeight, or an embedding setting is required");
19800
+ const suppliedProfileLimit = Object.hasOwn(body, "profileMaxLength");
19801
+ if (rawTurnSize === void 0 && rawLambda === void 0 && rawAgentWeight === void 0 && suppliedVectorParams.length === 0 && !suppliedProfileLimit) {
19802
+ throw new AdminHttpError(400, "blockTurnSize, blockDecayLambda, agentMemoryRetrievalWeight, profileMaxLength, or an embedding setting is required");
19505
19803
  }
19506
19804
  let turnSize;
19507
19805
  let lambda;
@@ -19531,6 +19829,16 @@ async function updateSettings(runtime, url, req) {
19531
19829
  if (turnSize !== void 0) result.blockTurnSize = await runtime.adminSetBlockTurnSize(turnSize);
19532
19830
  if (lambda !== void 0) result.blockDecayLambda = await runtime.adminSetBlockDecayLambda(lambda);
19533
19831
  if (agentWeight !== void 0) result.agentMemoryRetrievalWeight = runtime.adminSetAgentMemoryRetrievalWeight(agentWeight);
19832
+ if (suppliedProfileLimit) {
19833
+ const value = body.profileMaxLength;
19834
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) throw new AdminHttpError(400, "profileMaxLength must be an integer");
19835
+ try {
19836
+ result.profileMaxLength = runtime.adminSetProfileTotalMaxLength(value);
19837
+ } catch (error) {
19838
+ if (error instanceof TypeError || error instanceof RangeError) throw new AdminHttpError(400, error.message);
19839
+ throw error;
19840
+ }
19841
+ }
19534
19842
  if (suppliedVectorParams.length > 0) {
19535
19843
  const paramText = (name2) => {
19536
19844
  const value = body[name2];
@@ -19565,7 +19873,7 @@ async function updateSettings(runtime, url, req) {
19565
19873
  async function persistentProfile(runtime, req) {
19566
19874
  if (req.method === "GET") {
19567
19875
  const snapshot = runtime.getProfileSnapshot();
19568
- return { ...snapshot.profile, _revisions: snapshot.revisions };
19876
+ return { ...snapshot.profile, _revisions: snapshot.revisions, _limits: { totalMaxLength: runtime.getProfileTotalMaxLength?.() ?? void 0 } };
19569
19877
  }
19570
19878
  if (req.method !== "PATCH") throw new AdminHttpError(405, "Persistent Profile requires GET or PATCH");
19571
19879
  let suppliedBody = req.body;
@@ -19597,7 +19905,7 @@ async function persistentProfile(runtime, req) {
19597
19905
  const result = runtime.updatePersistentProfile(input.field, input.value, "settings", null, input.expectedValue, input.expectedRevision);
19598
19906
  if (result.conflict) throw new AdminHttpError(409, "\u8BE5\u9879\u521A\u521A\u5728\u5176\u4ED6\u4F4D\u7F6E\u66F4\u65B0");
19599
19907
  const snapshot = runtime.getProfileSnapshot();
19600
- return { ...result, snapshot: { ...snapshot.profile, _revisions: snapshot.revisions } };
19908
+ return { ...result, snapshot: { ...snapshot.profile, _revisions: snapshot.revisions, _limits: { totalMaxLength: runtime.getProfileTotalMaxLength?.() ?? void 0 } } };
19601
19909
  } catch (error) {
19602
19910
  if (error instanceof TypeError || error instanceof RangeError) throw new AdminHttpError(400, error.message);
19603
19911
  throw error;
@@ -21018,6 +21326,17 @@ async function apply(ctx, config) {
21018
21326
  }, () => feedbackWebOrigin(ctx));
21019
21327
  runtime.setDreamingHost(new DshDreamingSessions(ctx, runtime, () => models.dreamingModelOptions()));
21020
21328
  await runtime.syncConfiguredSettings();
21329
+ ctx.on("loader/volatile-update", () => {
21330
+ try {
21331
+ runtime.applyLiveDailyNotes(
21332
+ liveConfigValue(config.dailyNotesEnabled),
21333
+ liveConfigValue(config.dailyNotesTimeZone),
21334
+ liveConfigValue(config.dailyNotesInjectionDays)
21335
+ );
21336
+ } catch (error) {
21337
+ ctx.logger.warn(`stratagate-memory daily-note live update failed: ${renderError(error)}`);
21338
+ }
21339
+ });
21021
21340
  const effortEntry = {
21022
21341
  ...resolved.memoryModel ? { memoryModel: resolved.memoryModel } : {},
21023
21342
  structuredReasoningEffort: resolved.structuredReasoningEffort ?? "auto",