stratagate-dsh 0.3.21 → 0.3.23

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
@@ -6770,6 +6770,11 @@ var StrataGate = class _StrataGate {
6770
6770
  };
6771
6771
  });
6772
6772
  }
6773
+ /** Query-independent availability in this namespace, before filters/pagination. */
6774
+ hasSearchableEvents(options = {}) {
6775
+ const visible2 = (event) => event.status === "active" || event.status === "superseded";
6776
+ return this.events.some(visible2) || Math.max(0, options.agentMemoryWeight ?? 1) > 0 && this.agentEvents.some(visible2);
6777
+ }
6773
6778
  async searchEvents(query, options = {}) {
6774
6779
  const limit = Math.max(1, Math.min(20, options.limit ?? 6));
6775
6780
  const offset = options.offset ?? 0;
@@ -7076,6 +7081,10 @@ var StrataGate = class _StrataGate {
7076
7081
  if (!element) throw new Error(`Unknown element: ${id}`);
7077
7082
  return elementViewAt(element, at);
7078
7083
  }
7084
+ /** Only sealed source messages are searched; open tails are native context. */
7085
+ hasSearchableRawMessages(options = {}) {
7086
+ return this.blocks.some((block) => block.l5Raw.some((message) => (options.threadId === void 0 || message.threadId === options.threadId || options.includeUnthreaded === true && message.threadId === void 0) && searchTokens(message.content).length > 0));
7087
+ }
7079
7088
  searchRawMemory(query, limit = 6, options = {}) {
7080
7089
  const tokens = searchTokens(query);
7081
7090
  if (tokens.length === 0) return [];
@@ -7820,6 +7829,11 @@ ${duplicate.summary}` : duplicate.summary;
7820
7829
  if (!job) throw new Error(`Unknown element projection: ${id}`);
7821
7830
  return job;
7822
7831
  }
7832
+ /** Use the same Event-authoritative visibility boundary as Graph search. */
7833
+ hasSearchableGraphNodes() {
7834
+ const events = this.listAllEvents();
7835
+ return this.graphNodes.some((node) => effectiveGraphNodeView(node, this.graphEdges, events) !== null);
7836
+ }
7823
7837
  async searchGraphNodes(query, limit = 8) {
7824
7838
  const queryTokens = [...new Set(searchTokens(query))];
7825
7839
  if (queryTokens.length === 0) return [];
@@ -12508,12 +12522,15 @@ var StrataGateRuntime = class {
12508
12522
  }
12509
12523
  })),
12510
12524
  results.map(({ event, score }) => compactEvent2(event, score)),
12511
- topicId !== void 0 ? {
12512
- topicId,
12513
- totalSourceEvents,
12514
- offset,
12515
- nextOffset: results.length === Math.max(1, Math.min(20, searchOptions.limit ?? 6)) && (totalSourceEvents === null || offset + results.length < totalSourceEvents) ? offset + results.length : null
12516
- } : {}
12525
+ {
12526
+ ...searchStatus(results, () => memory.hasSearchableEvents?.({ agentMemoryWeight: this.agentMemoryRetrievalWeight })),
12527
+ ...topicId !== void 0 ? {
12528
+ topicId,
12529
+ totalSourceEvents,
12530
+ offset,
12531
+ nextOffset: results.length === Math.max(1, Math.min(20, searchOptions.limit ?? 6)) && (totalSourceEvents === null || offset + results.length < totalSourceEvents) ? offset + results.length : null
12532
+ } : {}
12533
+ }
12517
12534
  );
12518
12535
  }
12519
12536
  /** A navigation read never creates a retrieval batch or reinforces sources. */
@@ -12611,7 +12628,12 @@ var StrataGateRuntime = class {
12611
12628
  elementIds: [],
12612
12629
  citation: citation("block", result.blockId, blockTitles.get(result.blockId) ?? "Block", `raw:${result.blockId}:${result.message.id}:${index}`, "blockId")
12613
12630
  }
12614
- })), results.map(compactRawHit), { scope, namespace: this.namespaceFor(session), threadId });
12631
+ })), results.map(compactRawHit), {
12632
+ scope,
12633
+ namespace: this.namespaceFor(session),
12634
+ threadId,
12635
+ ...searchStatus(results, () => memory.hasSearchableRawMessages?.(scope === "namespace" ? {} : { threadId }))
12636
+ });
12615
12637
  }
12616
12638
  async blocks(session, scope = "session", options = {}) {
12617
12639
  await this.flush();
@@ -14086,7 +14108,8 @@ var StrataGateRuntime = class {
14086
14108
  }
14087
14109
  async searchGraph(session, query, limit = 8) {
14088
14110
  await this.flush();
14089
- const results = await (await this.space(session)).searchGraphNodes(query, limit);
14111
+ const memory = await this.space(session);
14112
+ const results = await memory.searchGraphNodes(query, limit);
14090
14113
  return this.batch(session, results.map(({ node, provenanceEventIds }) => ({
14091
14114
  ref: `graph-node:${node.id}`,
14092
14115
  target: {
@@ -14094,7 +14117,7 @@ var StrataGateRuntime = class {
14094
14117
  elementIds: [],
14095
14118
  citation: citation("graph", node.id, node.name, `graph-node:${node.id}`, "nodeId")
14096
14119
  }
14097
- })), results.map(compactGraphNode));
14120
+ })), results.map(compactGraphNode), searchStatus(results, () => memory.hasSearchableGraphNodes?.()));
14098
14121
  }
14099
14122
  async expandGraphNode(session, id) {
14100
14123
  await this.flush();
@@ -14677,6 +14700,18 @@ function activatedElements(memory, relevance) {
14677
14700
  weight
14678
14701
  ]).map(({ item }) => item);
14679
14702
  }
14703
+ function searchStatus(results, hasSearchableRecords) {
14704
+ if (results.length > 0) return { retrievalStatus: "matched" };
14705
+ const available = hasSearchableRecords();
14706
+ if (available === false) return {
14707
+ retrievalStatus: "scope_empty",
14708
+ retrievalHint: "\u5F53\u524D\u641C\u7D22\u8303\u56F4\u5185\u6CA1\u6709\u53EF\u641C\u7D22\u8BB0\u5F55\uFF1B\u4E0D\u80FD\u636E\u6B64\u65AD\u8A00\u5176\u4ED6\u8303\u56F4\u6216\u4ECE\u524D\u672A\u8BB0\u5F55\u8FC7\u3002"
14709
+ };
14710
+ return {
14711
+ retrievalStatus: available === true ? "no_match" : "unknown",
14712
+ retrievalHint: available === true ? "\u672C\u6B21\u68C0\u7D22\u672A\u627E\u5230\u5339\u914D\uFF0C\u4E0D\u80FD\u636E\u6B64\u65AD\u8A00\u76F8\u5173\u8BB0\u5FC6\u4E0D\u5B58\u5728\u3002" : "\u672C\u6B21\u672A\u8FD4\u56DE\u5339\u914D\uFF0C\u65E0\u6CD5\u53EF\u9760\u5224\u65AD\u5F53\u524D\u8303\u56F4\u662F\u5426\u6709\u53EF\u641C\u7D22\u8BB0\u5F55\uFF1B\u4E0D\u80FD\u636E\u6B64\u65AD\u8A00\u76F8\u5173\u8BB0\u5FC6\u4E0D\u5B58\u5728\u3002"
14713
+ };
14714
+ }
14680
14715
  function renderActivatedMemory(events, graphResults) {
14681
14716
  const heading = [
14682
14717
  "[Activated long-term memory]",
@@ -14733,7 +14768,7 @@ KnowledgeGraph:
14733
14768
  tokens += cost;
14734
14769
  nodeCount += 1;
14735
14770
  }
14736
- if (eventCount === 0 && nodeCount === 0) lines.push("(no activated memory)");
14771
+ if (eventCount === 0 && nodeCount === 0) lines.push("(no memory selected for automatic context)");
14737
14772
  return lines.join("\n");
14738
14773
  }
14739
14774
  function activeTurn(session) {
@@ -15115,6 +15150,7 @@ import { defineTool as defineTool2 } from "@deepseek-ai/dsh-tools";
15115
15150
  var AGENT_FEEDBACK_ENABLED = true;
15116
15151
 
15117
15152
  // src/tools.ts
15153
+ var SEARCH_RESULT_GUIDANCE = " Read retrievalStatus and retrievalHint: scope_empty applies only to this search scope; no_match means this query found no match; unknown means scope availability could not be determined. An empty result never proves a memory was never recorded. \u4E0D\u5F97\u628A\u7A7A\u7ED3\u679C\u8868\u8FF0\u6210\u201C\u6CA1\u6709\u8FD9\u6761\u8BB0\u5FC6\u201D\u6216\u201C\u4F60\u6CA1\u8BF4\u8FC7\u201D\u3002\u68C0\u7D22\u5F02\u5E38\u6309\u5DE5\u5177\u9519\u8BEF\u5904\u7406\uFF0C\u4E0D\u662F\u6B63\u5E38\u7A7A\u7ED3\u679C\u3002\u72B6\u6001\u63D0\u793A\u4E0D\u662F\u4E8B\u5B9E\u8BC1\u636E\uFF0C\u4E0D\u5F97\u91C7\u7528\u6216\u5F3A\u5316\u3002";
15118
15154
  var jsonOutput = {
15119
15155
  schema: { type: "json" },
15120
15156
  render: (_args, value) => [{
@@ -15210,7 +15246,7 @@ function registerMemoryTools(ctx, runtime) {
15210
15246
  }));
15211
15247
  ctx.tools.register(defineTool2({
15212
15248
  name: "memory_search_events",
15213
- description: "This tool is provided by the StrataGate plugin. Search durable Event memories for past facts, decisions, plans, changes, preferences, outcomes, and timing. Use a focused query with the most distinctive known names, entities, versions, tools, decisions, or outcomes. Results are compact candidates; rankScore reflects retrieval order only, not confidence or factual accuracy. Expand a relevant Event when its compact fields are not enough to verify the needed detail. Optionally pass topic_id to search within a navigated topic; query may be empty to browse its events, offset continues pagination, and temporalIntent first/latest controls chronology.",
15249
+ description: "This tool is provided by the StrataGate plugin. Search durable Event memories for past facts, decisions, plans, changes, preferences, outcomes, and timing. Use a focused query with the most distinctive known names, entities, versions, tools, decisions, or outcomes. Results are compact candidates; rankScore reflects retrieval order only, not confidence or factual accuracy. Expand a relevant Event when its compact fields are not enough to verify the needed detail. Optionally pass topic_id to search within a navigated topic; query may be empty to browse its events, offset continues pagination, and temporalIntent first/latest controls chronology." + SEARCH_RESULT_GUIDANCE,
15214
15250
  parameters: {
15215
15251
  query: { type: "string", required: true, description: "A focused query for the target historical memory. Prefer explicit names, entities, versions, tools, decisions, or outcomes over vague references. May be empty when browsing a supplied topic_id." },
15216
15252
  topic_id: { type: "string", description: "\u76EE\u5F55\u4E2D\u7684\u4E3B\u9898 ID\uFF1B\u9650\u5B9A\u771F\u5B9E\u6765\u6E90\u4E8B\u4EF6\uFF0C\u7A7A query \u53EF\u6D4F\u89C8\u3002" },
@@ -15232,7 +15268,7 @@ function registerMemoryTools(ctx, runtime) {
15232
15268
  }));
15233
15269
  ctx.tools.register(defineTool2({
15234
15270
  name: "memory_search_graph",
15235
- description: "This tool is provided by the StrataGate plugin. Search the Event-backed Knowledge Graph for current state and query-relevant history. Results explicitly label current, historical, or both; historical matches never imply current truth, disputed records remain marked, and Event evidence is bounded to the match. Endpoint names and aliases can match relations, while relation text alone is ranking context. rankScore is ranking-only, never confidence or factual accuracy.",
15271
+ description: "This tool is provided by the StrataGate plugin. Search the Event-backed Knowledge Graph for current state and query-relevant history. Results explicitly label current, historical, or both; historical matches never imply current truth, disputed records remain marked, and Event evidence is bounded to the match. Endpoint names and aliases can match relations, while relation text alone is ranking context. rankScore is ranking-only, never confidence or factual accuracy." + SEARCH_RESULT_GUIDANCE,
15236
15272
  parameters: {
15237
15273
  query: { type: "string", required: true },
15238
15274
  limit: { type: "integer", description: "Maximum results, 1-20." }
@@ -15249,7 +15285,7 @@ function registerMemoryTools(ctx, runtime) {
15249
15285
  }));
15250
15286
  ctx.tools.register(defineTool2({
15251
15287
  name: "memory_search_raw",
15252
- description: "This tool is provided by the StrataGate plugin. Search archived messages when summarized memories are insufficient. Returns compact raw hits (message id, blockId, excerpt, role, and time); use memory_expand_block with blockId for complete source details. By default searches the whole current namespace; use scope=session for the active thread. Returns evidence refs and batchId for assessment.",
15288
+ description: "This tool is provided by the StrataGate plugin. Search archived messages when summarized memories are insufficient. Returns compact raw hits (message id, blockId, excerpt, role, and time); use memory_expand_block with blockId for complete source details. By default searches the whole current namespace; use scope=session for the active thread. Returns evidence refs and batchId for assessment." + SEARCH_RESULT_GUIDANCE,
15253
15289
  parameters: {
15254
15290
  query: { type: "string", required: true },
15255
15291
  limit: { type: "integer" },
@@ -15997,7 +16033,8 @@ async function overview(runtime, cachedEntries) {
15997
16033
  title: block2.source.l0Title ?? null,
15998
16034
  threadId: block2.threadId,
15999
16035
  turnRange: block2.turnRange,
16000
- shouldExtract: block2.source.shouldExtract ?? null
16036
+ shouldExtract: block2.source.shouldExtract ?? null,
16037
+ rawAvailable: block2.messages.some(({ content }) => Boolean(content.trim()))
16001
16038
  }));
16002
16039
  }
16003
16040
  const block = snapshot.blocks.find(({ id }) => id === blockId);
@@ -16008,7 +16045,8 @@ async function overview(runtime, cachedEntries) {
16008
16045
  title: block.l0Title ?? null,
16009
16046
  threadId: block.threadId ?? null,
16010
16047
  turnRange: [block.startTurn, block.endTurn],
16011
- shouldExtract: block.shouldExtract ?? null
16048
+ shouldExtract: block.shouldExtract ?? null,
16049
+ rawAvailable: block.l5Raw.some(({ content }) => Boolean(content.trim()))
16012
16050
  }] : [];
16013
16051
  });
16014
16052
  const describeBlockJob = (kind, job) => {
@@ -16105,6 +16143,13 @@ async function overview(runtime, cachedEntries) {
16105
16143
  ...snapshot.graphNodes.map(({ updatedAt }) => updatedAt),
16106
16144
  ...snapshot.usageReceipts.map(({ createdAt }) => createdAt)
16107
16145
  ].sort();
16146
+ let topicDirectoryRevision = null;
16147
+ let topicDirectoryReadError = false;
16148
+ try {
16149
+ topicDirectoryRevision = topicDirectoryProjection(snapshot, runtime.adminAgentMemoryRetrievalWeight?.() ?? 1).data.revision;
16150
+ } catch {
16151
+ topicDirectoryReadError = true;
16152
+ }
16108
16153
  rows.push({
16109
16154
  namespace,
16110
16155
  duplicateRepair: runtime.adminDuplicateRepairStatus?.(namespace) ?? null,
@@ -16127,7 +16172,11 @@ async function overview(runtime, cachedEntries) {
16127
16172
  graphProjection: graphStatus,
16128
16173
  topicProjection: topicStatus
16129
16174
  },
16175
+ topicDirectoryRevision,
16176
+ topicDirectoryReadError,
16130
16177
  graphMigration: graphWork.migration,
16178
+ // Only a live source Block in this namespace establishes a retrieval gap.
16179
+ 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)),
16131
16180
  usageReceipts: snapshot.usageReceipts.length,
16132
16181
  memoryUseCount: snapshot.usageReceipts.filter((receipt) => receipt.eventIds.length > 0 || receipt.elementIds.length > 0).length,
16133
16182
  failedJobs,
@@ -16390,6 +16439,9 @@ function recoverSnapshotView(snapshot) {
16390
16439
  messages.push(item.message);
16391
16440
  groups.set(item.threadId, messages);
16392
16441
  }
16442
+ if (groups.size === 0 && snapshot.summaryJobs.some((job) => job.blockId === source.id && derivationJobState(job, job.status === "succeeded") === "terminal-failed")) {
16443
+ groups.set(source.threadId?.trim() || LEGACY_THREAD_ID, []);
16444
+ }
16393
16445
  const entries = [...groups];
16394
16446
  for (const [threadId, messages] of entries) {
16395
16447
  const virtual = !source.threadId && (entries.length > 1 || threadId !== LEGACY_THREAD_ID);
@@ -16535,10 +16587,12 @@ async function memories(runtime, url) {
16535
16587
  const eventIds = new Set(relatedEvents.map(({ id }) => id));
16536
16588
  const projections = snapshot.graphProjectionJobs.filter(({ sourceEventIds }) => sourceEventIds.some((id) => eventIds.has(id)));
16537
16589
  const relatedNodes = snapshot.graphNodes.filter(({ sourceEventIds }) => sourceEventIds.some((id) => eventIds.has(id))).map(({ id, name: name2, type }) => ({ id, name: name2, type }));
16538
- const failedProjection = projections.find(({ status: status2 }) => status2 === "failed");
16539
- const pendingProjection = projections.some(({ status: status2 }) => status2 === "pending" || status2 === "running");
16590
+ const failedProjection = projections.find((job) => derivationJobState(job, job.status === "completed") === "terminal-failed");
16591
+ const pendingProjection = projections.some(graphProjectionIsProcessing);
16540
16592
  const needsExtraction = source.shouldExtract === true;
16541
- const status = summary?.status === "failed" ? "failed" : summary?.status === "pending" || summary?.status === "running" || !summary && source.processingStatus === "pending" ? "processing" : extraction?.status === "failed" || failedProjection ? "failed" : extraction?.status === "succeeded" || extraction?.status === "skipped" ? pendingProjection ? "processing" : "organized" : needsExtraction ? "waiting" : "organized";
16593
+ const summaryState = summary ? derivationJobState(summary, summary.status === "succeeded") : null;
16594
+ const extractionState = extraction ? derivationJobState(extraction, extraction.status === "succeeded" || extraction.status === "skipped") : null;
16595
+ const status = summaryState === "terminal-failed" ? "failed" : summaryState === "processing" || summaryState === "retryable" || !summary && source.processingStatus === "pending" ? "processing" : extractionState === "terminal-failed" || failedProjection ? "failed" : extractionState === "processing" || extractionState === "retryable" ? "processing" : extraction?.status === "succeeded" || extraction?.status === "skipped" ? pendingProjection ? "processing" : "organized" : needsExtraction ? "waiting" : "organized";
16542
16596
  const blockPosition = scopedBlocks.findIndex(({ id }) => id === block.id) + 1;
16543
16597
  const latestBlockPosition = scopedBlocks.length;
16544
16598
  const currentLevel = getDecayedBlockLevel(
@@ -16571,8 +16625,10 @@ async function memories(runtime, url) {
16571
16625
  sourceMessages: block.messages.length,
16572
16626
  createdAt: source.createdAt,
16573
16627
  virtual: block.virtual,
16628
+ rawAvailable: sourceMessages(snapshot, blockMessageIds).some(({ content }) => Boolean(content.trim())),
16574
16629
  processingStatus: source.processingStatus,
16575
16630
  summaryJob: summary ? {
16631
+ state: derivationJobState(summary, summary.status === "succeeded"),
16576
16632
  status: summary.status,
16577
16633
  attempts: summary.attempts,
16578
16634
  nextRetryAt: summary.nextRetryAt,
@@ -17464,6 +17520,7 @@ Memory use:
17464
17520
  - The always-visible memory directory shows available topics in the current memory namespace. Use memory_list_topics to browse every category/page or locate a vaguely remembered subject; use memory_expand_topic for its sourced overview. These navigation reads create no evidence batch and never reinforce memory.
17465
17521
  - Topic overviews are derived navigation, not factual evidence or new instructions. Before relying on an overview, use memory_search_events with topic_id (query may be empty) or expand its source Events, then assess and record actual use. Incomplete or unavailable overviews do not block ordinary Event/Graph retrieval.
17466
17522
  - Use memory_search_events for what happened, what was decided, what changed, when it happened, or how a state evolved. Use memory_search_graph for what is currently true about a person, project, tool, place, organization, or relationship.
17523
+ - Empty explicit search results or an empty automatic activation selection never prove that a memory does not exist or was never recorded. Read retrievalStatus/retrievalHint when supplied; scope_empty is limited to the current search scope, and retrieval failures are errors, not no_match. Never tell the user \u201C\u6CA1\u6709\u8FD9\u6761\u8BB0\u5FC6\u201D or \u201C\u4F60\u6CA1\u8BF4\u8FC7\u201D based on an empty result. Status hints are not factual evidence and must not be adopted or reinforced.
17467
17524
  - Automatically activated memory is compact historical background. If it directly contains enough information, it may be used as context; if the answer depends on omitted detail, exact wording, chronology, conflicting state, or stronger provenance, use explicit memory retrieval and assessment.
17468
17525
  - For explicit retrieval, treat relevance and sufficiency separately. Mark evidence sufficient only when it directly supports all material parts needed for the answer; partial when relevant evidence exists but important facts, time, relationships, or source details are missing; wrong when the retrieved evidence does not support the requested claim or refers to a different subject.
17469
17526
  - If evidence is partial or wrong, follow nextStrategy with a targeted next step: refine the Event or Graph search, expand the relevant Event, Graph node, or Block, or inspect raw memory. Do not repeat the same failed search unchanged, and do not present uncertain memory as fact.