stratagate-dsh 0.3.44 → 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 } : {},
@@ -653,8 +656,8 @@ function effectiveGraphNodeView(node, edges, events) {
653
656
  if ((record3.status === "active" || record3.status === "disputed") && activeSources.length > 0) {
654
657
  return { current: { ...record3, sourceEventIds: activeSources } };
655
658
  }
656
- if (visibleSources.length > 0 && record3.status === "superseded") {
657
- return { historical: { ...record3, sourceEventIds: visibleSources } };
659
+ if (visibleSources.length > 0 && (record3.status === "superseded" || activeSources.length === 0)) {
660
+ return { historical: { ...record3, status: "superseded", sourceEventIds: visibleSources } };
658
661
  }
659
662
  return {};
660
663
  };
@@ -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]);
@@ -7319,7 +7327,7 @@ var StrataGate = class _StrataGate {
7319
7327
  throw new TypeError("Turn userMessageId must not be empty");
7320
7328
  }
7321
7329
  const existingUserMessage = requestedUserMessageId ? this.openTail.find((message) => message.id === requestedUserMessageId && message.role === "user") : void 0;
7322
- if (existingUserMessage && (existingUserMessage.content !== input.user || existingUserMessage.threadId !== threadId)) {
7330
+ if (existingUserMessage && existingUserMessage.threadId !== threadId) {
7323
7331
  throw new Error(`Reserved user message ${requestedUserMessageId} does not match the appended turn`);
7324
7332
  }
7325
7333
  const userMessage = existingUserMessage ?? {
@@ -7349,8 +7357,13 @@ var StrataGate = class _StrataGate {
7349
7357
  if (index < 0) tail.push(assistant);
7350
7358
  else tail.splice(index + 1, 0, assistant);
7351
7359
  };
7360
+ const reservedContentChanged = existingUserMessage !== void 0 && existingUserMessage.content !== input.user;
7352
7361
  const appendInMemory = () => {
7353
7362
  if (receiptId && this.ingestionReceipts.has(receiptId)) return false;
7363
+ if (existingUserMessage) {
7364
+ existingUserMessage.content = input.user;
7365
+ if (input.userToolCalls !== void 0) existingUserMessage.toolCalls = structuredClone(input.userToolCalls);
7366
+ }
7354
7367
  this.currentTurn += 1;
7355
7368
  placeTurnMessages(this.openTail, false);
7356
7369
  if (receiptId) this.ingestionReceipts.set(receiptId, { id: receiptId, createdAt });
@@ -7358,7 +7371,7 @@ var StrataGate = class _StrataGate {
7358
7371
  };
7359
7372
  const appended = this.storage?.commitRecords ? await this.withMutationQueue(async () => {
7360
7373
  const reservedIsLast = !existingUserMessage || this.openTail.at(-1)?.id === existingUserMessage.id;
7361
- if (this.hasPendingRecordChanges() || !reservedIsLast) return this.applyMutation(appendInMemory);
7374
+ if (this.hasPendingRecordChanges() || !reservedIsLast || reservedContentChanged) return this.applyMutation(appendInMemory);
7362
7375
  if (receiptId && this.ingestionReceipts.has(receiptId)) return false;
7363
7376
  const receipt = receiptId ? { id: receiptId, createdAt } : void 0;
7364
7377
  const committed = await this.storage.commitRecords(this.namespace, this.revision, {
@@ -9463,17 +9476,18 @@ ${duplicate.summary}` : duplicate.summary;
9463
9476
  pendingBlockMessages(threadId) {
9464
9477
  const messages = this.threadOpenTail(threadId);
9465
9478
  let users = 0;
9466
- let end = 0;
9479
+ const selected = [];
9467
9480
  for (const [index, message] of messages.entries()) {
9468
9481
  if (message.role !== "user") continue;
9469
- if (!userTurnHasAssistant(messages, index)) break;
9482
+ if (!userTurnHasAssistant(messages, index)) continue;
9470
9483
  users += 1;
9471
- if (users !== this.blockTurnSize) continue;
9472
9484
  const nextUserOffset = messages.slice(index + 1).findIndex((candidate) => candidate.role === "user");
9473
- end = nextUserOffset === -1 ? messages.length : index + 1 + nextUserOffset;
9485
+ const end = nextUserOffset === -1 ? messages.length : index + 1 + nextUserOffset;
9486
+ selected.push(...messages.slice(index, end));
9487
+ if (users !== this.blockTurnSize) continue;
9474
9488
  break;
9475
9489
  }
9476
- return messages.slice(0, end);
9490
+ return selected;
9477
9491
  }
9478
9492
  async sealOpenTail(threadId) {
9479
9493
  const raw = this.pendingBlockMessages(threadId);
@@ -12179,17 +12193,17 @@ Use project scope for repository decisions, user scope for stable preferences/id
12179
12193
  }));
12180
12194
  return { candidates: parsed.candidates, reason: text2(raw.reason, parsed.reason) };
12181
12195
  };
12182
- async maintainProfile(profile) {
12196
+ async maintainProfile(profile, totalMaxLength = PROFILE_TOTAL_MAX_LENGTH) {
12183
12197
  const raw = object(await this.callStructured(
12184
12198
  "profileMaintenance",
12185
- `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.`,
12186
12200
  { profile, fieldDefinitions: PROFILE_FIELDS }
12187
12201
  ));
12188
12202
  if (Object.keys(raw).length !== Object.keys(PROFILE_FIELDS).length || Object.keys(raw).some((field) => !(field in PROFILE_FIELDS))) {
12189
12203
  throw new Error("Profile maintenance returned unexpected fields");
12190
12204
  }
12191
12205
  const proposed = raw;
12192
- validateProfile(proposed);
12206
+ validateProfile(proposed, totalMaxLength);
12193
12207
  for (const field of PROFILE_PROTECTED_SHORT_FIELDS) {
12194
12208
  if (proposed[field].trim() !== profile[field].trim()) throw new Error(`Profile maintenance changed protected short field ${field}`);
12195
12209
  }
@@ -12910,6 +12924,25 @@ var DailyNotes = class {
12910
12924
  throw error;
12911
12925
  }
12912
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
+ }
12913
12946
  load(namespace, date) {
12914
12947
  return readFile(join(this.directory(namespace), `${validDate(date)}.md`), "utf8");
12915
12948
  }
@@ -13845,6 +13878,11 @@ function sourceContext(event, snapshot) {
13845
13878
  }
13846
13879
 
13847
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
+ }
13848
13886
  function dreamingConflict(error) {
13849
13887
  return error instanceof Error && /^(Directory changed during Dreaming|Dreaming sources changed|Dreaming evidence changed)/.test(error.message);
13850
13888
  }
@@ -13876,6 +13914,7 @@ var VECTOR_SETTING_KEYS = [
13876
13914
  "rerankModel"
13877
13915
  ];
13878
13916
  var VECTOR_SECRET_MASK = "********";
13917
+ var PROFILE_LIMIT_SETTING_KEY = "profile.totalMaxLength";
13879
13918
  function projectKey(cwd) {
13880
13919
  const canonical2 = resolve3(cwd ?? process.cwd()).replaceAll("\\", "/").toLowerCase();
13881
13920
  return createHash6("sha256").update(canonical2).digest("hex").slice(0, 20);
@@ -14025,10 +14064,31 @@ var StrataGateRuntime = class _StrataGateRuntime {
14025
14064
  }
14026
14065
  return snapshot;
14027
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
+ }
14028
14087
  diagnostics;
14029
14088
  diagnosticSessionNamespaces = /* @__PURE__ */ new Map();
14030
14089
  diagnosticMemoryEstimates = /* @__PURE__ */ new Map();
14031
14090
  profileStorage;
14091
+ profileTotalMaxLength = PROFILE_TOTAL_MAX_LENGTH;
14032
14092
  folder = new TurnFolder();
14033
14093
  spaces = /* @__PURE__ */ new Map();
14034
14094
  batches = /* @__PURE__ */ new Map();
@@ -14088,7 +14148,8 @@ var StrataGateRuntime = class _StrataGateRuntime {
14088
14148
  return this.graphMetadata;
14089
14149
  }
14090
14150
  graphSettings() {
14091
- return this.graphMetadata?.graphSettings() ?? readGraphSettings(this.config.database);
14151
+ if (this.graphMetadata) return this.graphMetadata.graphSettings();
14152
+ return readGraphSettings(this.config.database);
14092
14153
  }
14093
14154
  get graphEnabled() {
14094
14155
  return this.graphSettings().enabled;
@@ -14216,7 +14277,7 @@ var StrataGateRuntime = class _StrataGateRuntime {
14216
14277
  const run = (async () => {
14217
14278
  const current = this.profileStore().getPersistentProfile();
14218
14279
  try {
14219
- 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));
14220
14281
  return this.profileStore().applyProfileMaintenance(current, proposed, new Date(now).toISOString());
14221
14282
  } catch (error) {
14222
14283
  this.profileStore().recordProfileMaintenanceFailure(current, now);
@@ -14414,21 +14475,64 @@ var StrataGateRuntime = class _StrataGateRuntime {
14414
14475
  return this.profileStore().getPersistentProfile();
14415
14476
  }
14416
14477
  getProfileSnapshot() {
14417
- return this.profileStore().getProfileSnapshot();
14478
+ return this.readProfileOverview()?.snapshot ?? this.profileStore().getProfileSnapshot();
14418
14479
  }
14419
14480
  renderProfileContext() {
14420
14481
  return renderPersistentProfile(this.getPersistentProfile());
14421
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
+ }
14422
14503
  getProfileChanges() {
14504
+ const stored = this.readProfileOverview();
14505
+ if (stored) return stored.changes;
14423
14506
  return this.profileStore().getProfileChanges();
14424
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
+ }
14425
14529
  updatePersistentProfile(field, value, source, sourceMessageId, expectedValue, expectedRevision) {
14426
14530
  const result = this.profileStore().updateProfileField(field, value, source, sourceMessageId, expectedValue, expectedRevision);
14427
14531
  if (result.modified) this.wakeBackgroundWorker();
14428
14532
  return result;
14429
14533
  }
14430
14534
  profileStore() {
14431
- 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 });
14432
14536
  }
14433
14537
  updatePersistentProfileFromTool(field, value) {
14434
14538
  return this.updatePersistentProfile(field, value, "agent_tool");
@@ -16042,6 +16146,10 @@ var StrataGateRuntime = class _StrataGateRuntime {
16042
16146
  this.blockTurnSize = metadata2.blockTurnSize() ?? this.config.blockTurnSize;
16043
16147
  this.blockDecayLambda = metadata2.blockDecayLambda() ?? this.config.blockDecayLambda;
16044
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
+ }
16045
16153
  const storedEmbeddingUrl = this.readVectorSetting("embeddingUrl");
16046
16154
  if (storedEmbeddingUrl !== null) this.config.embeddingUrl = storedEmbeddingUrl;
16047
16155
  const storedEmbeddingKey = this.readVectorSetting("embeddingKey");
@@ -16706,6 +16814,43 @@ var StrataGateRuntime = class _StrataGateRuntime {
16706
16814
  database.close();
16707
16815
  }
16708
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
+ }
16709
16854
  adminWorkspaceName(namespace) {
16710
16855
  const remembered = this.workspaceNames.get(namespace);
16711
16856
  if (remembered) return remembered;
@@ -17352,6 +17497,8 @@ function renderMessages(messages) {
17352
17497
  }).join("\n\n");
17353
17498
  }
17354
17499
  function dshTurnAtBlockEnd(session, block) {
17500
+ const sourceTurns = sourceTurnNumbersForBlock(block);
17501
+ if (sourceTurns.length > 0) return sourceTurns.at(-1) ?? null;
17355
17502
  const blockEnd = Date.parse(block.createdAt);
17356
17503
  const events = session.snapshotEvents();
17357
17504
  for (let index = events.length - 1; index >= 0; index -= 1) {
@@ -17372,6 +17519,7 @@ function recoverableSealedSurfaceSources(session, blocks) {
17372
17519
  }
17373
17520
  const ends = /* @__PURE__ */ new Map();
17374
17521
  const visibleEnds = /* @__PURE__ */ new Set();
17522
+ const visibleTurns = /* @__PURE__ */ new Set();
17375
17523
  const compactedBlocks = /* @__PURE__ */ new Set();
17376
17524
  let open2;
17377
17525
  for (const event of session.snapshotEvents()) {
@@ -17387,6 +17535,7 @@ function recoverableSealedSurfaceSources(session, blocks) {
17387
17535
  if (open2?.turn === event.data.turn) {
17388
17536
  ends.set(event.time, event.data.turn);
17389
17537
  if (open2.visible) visibleEnds.add(event.time);
17538
+ if (open2.visible) visibleTurns.add(event.data.turn);
17390
17539
  }
17391
17540
  open2 = void 0;
17392
17541
  } else if (open2 && visible2.has(event.seq)) open2.visible = true;
@@ -17396,10 +17545,11 @@ function recoverableSealedSurfaceSources(session, blocks) {
17396
17545
  result.retired.add(block.id);
17397
17546
  continue;
17398
17547
  }
17548
+ const sourceTurns = sourceTurnNumbersForBlock(block);
17399
17549
  const endTime = Date.parse(block.createdAt);
17400
- const endTurn = ends.get(endTime);
17550
+ const endTurn = sourceTurns.at(-1) ?? ends.get(endTime);
17401
17551
  if (endTurn === void 0) continue;
17402
- if (!visibleEnds.has(endTime)) {
17552
+ if (sourceTurns.length > 0 ? !visibleTurns.has(endTurn) : !visibleEnds.has(endTime)) {
17403
17553
  result.retired.add(block.id);
17404
17554
  continue;
17405
17555
  }
@@ -17414,6 +17564,8 @@ function sealedSurfaceSeqs(session, endTurn, block) {
17414
17564
  const completed = [];
17415
17565
  let open2;
17416
17566
  const events = session.snapshotEvents();
17567
+ const sourceTurnNumbers = sourceTurnNumbersForBlock(block);
17568
+ const sourceTurnSet = new Set(sourceTurnNumbers);
17417
17569
  for (const event of events) {
17418
17570
  if (event.type === "turn/start") {
17419
17571
  open2 = { turn: event.data.turn, start: event.seq };
@@ -17422,7 +17574,7 @@ function sealedSurfaceSeqs(session, endTurn, block) {
17422
17574
  if (event.type !== "turn/end" || !open2 || event.data.turn !== open2.turn) continue;
17423
17575
  const turnEvents = events.slice(open2.start + 1, event.seq);
17424
17576
  const hasHumanMessage = turnEvents.some((candidate) => candidate.type === "user/message" && candidate.data.source.kind === "user");
17425
- if (hasHumanMessage && event.data.turn <= endTurn) {
17577
+ if (hasHumanMessage && (sourceTurnSet.size > 0 ? sourceTurnSet.has(event.data.turn) : event.data.turn <= endTurn)) {
17426
17578
  completed.push({
17427
17579
  turn: event.data.turn,
17428
17580
  endTime: event.time,
@@ -17439,10 +17591,9 @@ function sealedSurfaceSeqs(session, endTurn, block) {
17439
17591
  }
17440
17592
  open2 = void 0;
17441
17593
  }
17442
- const sourceTimes = block.l5Raw.filter((message) => message.role === "user").map((message) => Date.parse(message.createdAt));
17443
17594
  const turnCount = block.endTurn - block.startTurn + 1;
17444
- const selected = completed.slice(-turnCount);
17445
- if (selected.length !== turnCount || selected.at(-1)?.turn !== endTurn || sourceTimes.length !== turnCount || selected.some((turn, index) => turn.endTime !== sourceTimes[index])) return null;
17595
+ const selected = sourceTurnNumbers.length === turnCount ? sourceTurnNumbers.flatMap((turn) => completed.find((candidate) => candidate.turn === turn) ?? []) : completed.slice(-turnCount);
17596
+ if (selected.length !== turnCount || selected.at(-1)?.turn !== (sourceTurnNumbers.at(-1) ?? endTurn) || sourceTurnNumbers.length !== turnCount && selected.some((turn, index) => turn.endTime !== Date.parse(block.l5Raw.filter((message) => message.role === "user")[index].createdAt))) return null;
17446
17597
  const firstTurn = selected[0];
17447
17598
  const lastTurn = selected.at(-1);
17448
17599
  if (events.some((event) => {
@@ -17473,9 +17624,22 @@ function turnAtSurfaceSeq(session, seq) {
17473
17624
  return turn;
17474
17625
  }
17475
17626
  function sourceTurnsForBlock(session, block) {
17627
+ const stableTurns = sourceTurnNumbersForBlock(block);
17628
+ if (stableTurns.length > 0) return new Set(stableTurns);
17476
17629
  const sourceTimes = new Set(block.l5Raw.filter((message) => message.role === "user").map((message) => Date.parse(message.createdAt)));
17477
17630
  return new Set(session.snapshotEvents().filter((event) => event.type === "turn/end" && sourceTimes.has(event.time)).map((event) => event.data.turn));
17478
17631
  }
17632
+ function sourceTurnNumbersForBlock(block) {
17633
+ const turns = [];
17634
+ for (const message of block.l5Raw) {
17635
+ if (message.role !== "user") continue;
17636
+ const match = message.id.match(/:turn:(\d+):user$/u);
17637
+ if (!match) continue;
17638
+ const turn = Number(match[1]);
17639
+ if (Number.isSafeInteger(turn) && !turns.includes(turn)) turns.push(turn);
17640
+ }
17641
+ return turns;
17642
+ }
17479
17643
  function surfaceEventTurns(session, event) {
17480
17644
  if (event.surfaceOp !== "append" && event.sourceEventSeqs?.length) {
17481
17645
  const sourceTurns = event.sourceEventSeqs.flatMap((source) => {
@@ -17516,13 +17680,29 @@ function appendBlockSurface(session, block, text3, seqs) {
17516
17680
  throw Object.assign(new Error("StrataGate surface replacement no longer owns its complete source range"), { retryable: false });
17517
17681
  }
17518
17682
  session.append("user/message", createUserMessage2({
17519
- content: [{ type: "text", text: text3 }],
17683
+ content: [{ type: "text", text: text3 }, ...sourceAttachmentBlocks(session, seqs)],
17520
17684
  source: dshMessageSource()
17521
17685
  }), {
17522
17686
  surfaceOp: dshReplaceSurfaceOp(seqs[0], seqs.at(-1)),
17523
17687
  sourceEventSeqs: seqs
17524
17688
  });
17525
17689
  }
17690
+ function sourceAttachmentBlocks(session, seqs) {
17691
+ const attachments = [];
17692
+ const seen = /* @__PURE__ */ new Set();
17693
+ for (const seq of seqs) {
17694
+ const event = session.eventAt(seq);
17695
+ if (event?.type !== "user/message") continue;
17696
+ for (const block of event.data.content) {
17697
+ if (block.type !== "image" && block.type !== "file") continue;
17698
+ const key = `${block.type}:${String(block.attachment.attachmentId)}`;
17699
+ if (seen.has(key)) continue;
17700
+ seen.add(key);
17701
+ attachments.push(structuredClone(block));
17702
+ }
17703
+ }
17704
+ return attachments;
17705
+ }
17526
17706
  function surfaceMaintenanceInput(state) {
17527
17707
  return `${state.memory.storageRevision}:${surfaceCapacityKey(state.session)}:${state.session.surface?.nodes.join(",") ?? ""}`;
17528
17708
  }
@@ -18697,6 +18877,114 @@ function clusterKnowledgeGraph(rawNodes, rawEdges) {
18697
18877
  }).sort((left, right) => right.nodeIds.length - left.nodeIds.length || left.label.localeCompare(right.label));
18698
18878
  }
18699
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
+
18700
18988
  // src/web.ts
18701
18989
  var LEGACY_THREAD_ID = "__legacy__";
18702
18990
  var nodeRequire2 = createRequire3(import.meta.url);
@@ -19014,22 +19302,22 @@ var AdminHttpError = class extends Error {
19014
19302
  details;
19015
19303
  };
19016
19304
  function topicDirectoryProjection(snapshot, agentMemoryWeight) {
19017
- 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");
19018
19306
  const directory = new MemoryTopicDirectory();
19019
19307
  directory.restore(snapshot.memoryTopicState);
19020
- const state = directory.snapshot(visibleEvents);
19308
+ const state = directory.snapshot(visibleEvents2);
19021
19309
  directory.restore(state);
19022
- let topics = directory.list(visibleEvents);
19310
+ let topics = directory.list(visibleEvents2);
19023
19311
  if (agentMemoryWeight <= 0) {
19024
19312
  topics = topics.filter((topic) => !topic.isFallback);
19025
19313
  const assigned = new Set(topics.flatMap((topic) => topic.sourceEventIds));
19026
- topics.push(...new MemoryTopicDirectory().list(visibleEvents.filter(({ id }) => !assigned.has(id))));
19314
+ topics.push(...new MemoryTopicDirectory().list(visibleEvents2.filter(({ id }) => !assigned.has(id))));
19027
19315
  }
19028
19316
  topics = sortMemoryTopics(topics);
19029
19317
  const chapters = topics.filter((topic) => !topic.isFallback);
19030
19318
  const pendingIds = new Set(topics.filter((topic) => topic.isFallback).flatMap((topic) => topic.sourceEventIds));
19031
- const pending = visibleEvents.filter(({ id }) => pendingIds.has(id)).sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id));
19032
- 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)]));
19033
19321
  const frozen = state.bootstrap?.projectorVersion === MEMORY_TOPIC_PROJECTOR_VERSION ? state.bootstrap : null;
19034
19322
  const relationKey = (topicId, id, version) => JSON.stringify([topicId ?? null, id, version]);
19035
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 })));
@@ -19080,7 +19368,7 @@ function topicDirectoryProjection(snapshot, agentMemoryWeight) {
19080
19368
  agentMemoryWeight
19081
19369
  })).digest("hex");
19082
19370
  return {
19083
- visibleEvents,
19371
+ visibleEvents: visibleEvents2,
19084
19372
  pending,
19085
19373
  chapters,
19086
19374
  failures,
@@ -19088,7 +19376,7 @@ function topicDirectoryProjection(snapshot, agentMemoryWeight) {
19088
19376
  navigationOnly: true,
19089
19377
  dreaming: dreamingStatus(snapshot.memoryTopicState?.dreaming),
19090
19378
  revision,
19091
- context: renderMemoryDirectory(topics, visibleEvents),
19379
+ context: renderMemoryDirectory(topics, visibleEvents2),
19092
19380
  topics: chapters.map((topic) => ({
19093
19381
  id: topic.id,
19094
19382
  title: topic.title,
@@ -19223,12 +19511,50 @@ function liveGraphProjection(snapshot, processing = true) {
19223
19511
  }
19224
19512
  };
19225
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
+ }
19226
19550
  async function overview(runtime, cachedEntries) {
19227
- 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) => ({
19228
19552
  namespace,
19229
19553
  revision: 0,
19230
19554
  snapshot: await runtime.adminSnapshot(namespace)
19231
19555
  })));
19556
+ const entries = loaded.flatMap((entry) => entry.snapshot ? [entry] : []);
19557
+ const memoryOverviewByNamespace = await memoryOverviewRows(runtime, entries);
19232
19558
  const rows = [];
19233
19559
  for (const { namespace, snapshot } of entries) {
19234
19560
  if (!snapshot) continue;
@@ -19356,11 +19682,18 @@ async function overview(runtime, cachedEntries) {
19356
19682
  ].sort();
19357
19683
  let topicDirectoryRevision = null;
19358
19684
  let topicDirectoryReadError = false;
19685
+ let directoryLayer = null;
19359
19686
  try {
19360
- 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
+ };
19361
19693
  } catch {
19362
19694
  topicDirectoryReadError = true;
19363
19695
  }
19696
+ const usage = memoryOverviewByNamespace.get(namespace);
19364
19697
  rows.push({
19365
19698
  namespace,
19366
19699
  duplicateRepair: runtime.adminDuplicateRepairStatus?.(namespace) ?? null,
@@ -19390,6 +19723,11 @@ async function overview(runtime, cachedEntries) {
19390
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)),
19391
19724
  usageReceipts: snapshot.usageReceipts.length,
19392
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,
19393
19731
  failedJobs,
19394
19732
  processingJobs,
19395
19733
  failedJobDetails,
@@ -19459,8 +19797,9 @@ async function updateSettings(runtime, url, req) {
19459
19797
  const hasBody = req.body !== void 0 || typeof req[Symbol.asyncIterator] === "function";
19460
19798
  const body = hasBody ? await jsonBody(req, "Embedding settings") : {};
19461
19799
  const suppliedVectorParams = vectorParams.filter((name2) => Object.hasOwn(body, name2));
19462
- if (rawTurnSize === void 0 && rawLambda === void 0 && rawAgentWeight === void 0 && suppliedVectorParams.length === 0) {
19463
- 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");
19464
19803
  }
19465
19804
  let turnSize;
19466
19805
  let lambda;
@@ -19490,6 +19829,16 @@ async function updateSettings(runtime, url, req) {
19490
19829
  if (turnSize !== void 0) result.blockTurnSize = await runtime.adminSetBlockTurnSize(turnSize);
19491
19830
  if (lambda !== void 0) result.blockDecayLambda = await runtime.adminSetBlockDecayLambda(lambda);
19492
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
+ }
19493
19842
  if (suppliedVectorParams.length > 0) {
19494
19843
  const paramText = (name2) => {
19495
19844
  const value = body[name2];
@@ -19524,7 +19873,7 @@ async function updateSettings(runtime, url, req) {
19524
19873
  async function persistentProfile(runtime, req) {
19525
19874
  if (req.method === "GET") {
19526
19875
  const snapshot = runtime.getProfileSnapshot();
19527
- return { ...snapshot.profile, _revisions: snapshot.revisions };
19876
+ return { ...snapshot.profile, _revisions: snapshot.revisions, _limits: { totalMaxLength: runtime.getProfileTotalMaxLength?.() ?? void 0 } };
19528
19877
  }
19529
19878
  if (req.method !== "PATCH") throw new AdminHttpError(405, "Persistent Profile requires GET or PATCH");
19530
19879
  let suppliedBody = req.body;
@@ -19556,7 +19905,7 @@ async function persistentProfile(runtime, req) {
19556
19905
  const result = runtime.updatePersistentProfile(input.field, input.value, "settings", null, input.expectedValue, input.expectedRevision);
19557
19906
  if (result.conflict) throw new AdminHttpError(409, "\u8BE5\u9879\u521A\u521A\u5728\u5176\u4ED6\u4F4D\u7F6E\u66F4\u65B0");
19558
19907
  const snapshot = runtime.getProfileSnapshot();
19559
- return { ...result, snapshot: { ...snapshot.profile, _revisions: snapshot.revisions } };
19908
+ return { ...result, snapshot: { ...snapshot.profile, _revisions: snapshot.revisions, _limits: { totalMaxLength: runtime.getProfileTotalMaxLength?.() ?? void 0 } } };
19560
19909
  } catch (error) {
19561
19910
  if (error instanceof TypeError || error instanceof RangeError) throw new AdminHttpError(400, error.message);
19562
19911
  throw error;
@@ -20977,6 +21326,17 @@ async function apply(ctx, config) {
20977
21326
  }, () => feedbackWebOrigin(ctx));
20978
21327
  runtime.setDreamingHost(new DshDreamingSessions(ctx, runtime, () => models.dreamingModelOptions()));
20979
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
+ });
20980
21340
  const effortEntry = {
20981
21341
  ...resolved.memoryModel ? { memoryModel: resolved.memoryModel } : {},
20982
21342
  structuredReasoningEffort: resolved.structuredReasoningEffort ?? "auto",