@xopcai/xopc 0.0.228 → 0.0.229

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.
Files changed (129) hide show
  1. package/dist/browser-ext/manifest.json +1 -1
  2. package/dist/extensions/telegram/xopc.extension.json +1 -1
  3. package/dist/gateway/static/root/assets/{agent-avatar-dicebear-CjGZBs4C.js → agent-avatar-dicebear-CsFAJTIN.js} +1 -1
  4. package/dist/gateway/static/root/assets/{agents-B0NI4_NI.js → agents-DA4b6_0C.js} +1 -1
  5. package/dist/gateway/static/root/assets/{app-management-settings-panel--SjycrXk.js → app-management-settings-panel-7KcMWuah.js} +1 -1
  6. package/dist/gateway/static/root/assets/{appearance-settings-8G-TVUtg.js → appearance-settings-Cqlw7Fif.js} +1 -1
  7. package/dist/gateway/static/root/assets/{apps-page-2NiqD-YP.js → apps-page-CsnhdGZ2.js} +1 -1
  8. package/dist/gateway/static/root/assets/{attachment-load-Bx44zSpz.js → attachment-load-q4pDpqkF.js} +1 -1
  9. package/dist/gateway/static/root/assets/{automations-page-CrKAHqc0.js → automations-page-BuTqjKGX.js} +1 -1
  10. package/dist/gateway/static/root/assets/{automations-workspace-Q3g9cf0h.js → automations-workspace-CD0E2ThS.js} +1 -1
  11. package/dist/gateway/static/root/assets/{binary-plugins-DjDwnHAQ.js → binary-plugins-DUce1Bsc.js} +1 -1
  12. package/dist/gateway/static/root/assets/{block-editor-7aMOKoZM.js → block-editor-D8Ejp-QR.js} +1 -1
  13. package/dist/gateway/static/root/assets/{browser-settings-page-DTwPkmAC.js → browser-settings-page-CY1k3MMd.js} +1 -1
  14. package/dist/gateway/static/root/assets/{browser-workflows-page-DVLrWKz_.js → browser-workflows-page-BDvZbR9v.js} +1 -1
  15. package/dist/gateway/static/root/assets/{capabilities-settings-panel-YcP4FbN7.js → capabilities-settings-panel-D1VfotHQ.js} +1 -1
  16. package/dist/gateway/static/root/assets/{capability-presets-settings-panel-AcPjHHia.js → capability-presets-settings-panel-DXHqRLpU.js} +1 -1
  17. package/dist/gateway/static/root/assets/{channels-settings-Ca94Q1D-.js → channels-settings-DrFL57M_.js} +1 -1
  18. package/dist/gateway/static/root/assets/{chat-terminal-dock-BR-_7KC0.js → chat-terminal-dock-h1CKexNz.js} +1 -1
  19. package/dist/gateway/static/root/assets/{connectors-page-SGxfLTd6.js → connectors-page-DUAyfFCF.js} +1 -1
  20. package/dist/gateway/static/root/assets/{cron-expression-D8-c-Tkw.js → cron-expression-DlaQQOId.js} +1 -1
  21. package/dist/gateway/static/root/assets/{date-picker-kV-Jyl9J.js → date-picker-8R1sXJKb.js} +1 -1
  22. package/dist/gateway/static/root/assets/{dependency-picker-CwKcrfGj.js → dependency-picker-CWur0821.js} +1 -1
  23. package/dist/gateway/static/root/assets/{desktop-pet-D9rnchu3.js → desktop-pet-Knl-zNDU.js} +1 -1
  24. package/dist/gateway/static/root/assets/{desktop-pet-settings-CTs5WGzk.js → desktop-pet-settings-CAQMLVtd.js} +1 -1
  25. package/dist/gateway/static/root/assets/{directory-picker-path-field-CCl0aaDm.js → directory-picker-path-field-Caaz4Rw5.js} +1 -1
  26. package/dist/gateway/static/root/assets/{extension-debug-page-Cau40SvC.js → extension-debug-page-B965Mc15.js} +1 -1
  27. package/dist/gateway/static/root/assets/{extension-page-BsJXdvIL.js → extension-page-C0UnkBi5.js} +1 -1
  28. package/dist/gateway/static/root/assets/{extension-settings-page-qWqJyF7-.js → extension-settings-page-BUSIAZCR.js} +1 -1
  29. package/dist/gateway/static/root/assets/{gateway-config-api-BI0SELXm.js → gateway-config-api-DkH0eEgy.js} +1 -1
  30. package/dist/gateway/static/root/assets/{gateway-settings-6ZdOIC7F.js → gateway-settings-BBgLDm6I.js} +1 -1
  31. package/dist/gateway/static/root/assets/{heartbeat-settings-KBwhXeFD.js → heartbeat-settings-BtEHVXWD.js} +1 -1
  32. package/dist/gateway/static/root/assets/{home-page-BA2M4CLi.js → home-page-5SU2TNJj.js} +1 -1
  33. package/dist/gateway/static/root/assets/{index-BX0dz1JK.js → index-BNWhgmjs.js} +8 -8
  34. package/dist/gateway/static/root/assets/{keyboard-shortcuts-settings-kHtpnyEm.js → keyboard-shortcuts-settings-CsRz8NrS.js} +1 -1
  35. package/dist/gateway/static/root/assets/{local-app-workbench-page-D2nkn09R.js → local-app-workbench-page-DYPEUgpP.js} +1 -1
  36. package/dist/gateway/static/root/assets/{local-apps-page-BCXa0oUa.js → local-apps-page-CTBNUG4a.js} +1 -1
  37. package/dist/gateway/static/root/assets/{logs-page-D3sNst0K.js → logs-page-B0P7rG2B.js} +1 -1
  38. package/dist/gateway/static/root/assets/{management-settings-tHnlfOAQ.js → management-settings-YqUAEwQo.js} +1 -1
  39. package/dist/gateway/static/root/assets/{markdown-split-BMLqHHr5.js → markdown-split-dxpSCXb8.js} +1 -1
  40. package/dist/gateway/static/root/assets/{media-plugins-DybwqTgv.js → media-plugins-CJ00i1Lg.js} +1 -1
  41. package/dist/gateway/static/root/assets/{notes-page-C24SfF6r.js → notes-page-DEnbnkIt.js} +1 -1
  42. package/dist/gateway/static/root/assets/{notes-workbench-CTdZc3ov.js → notes-workbench-DmVYu_Oc.js} +2 -2
  43. package/dist/gateway/static/root/assets/{product-open-page-DBfCVlJq.js → product-open-page-BHxo9U95.js} +1 -1
  44. package/dist/gateway/static/root/assets/{project-detail-page-COHaEpbA.js → project-detail-page-DV2nGmsq.js} +1 -1
  45. package/dist/gateway/static/root/assets/{projects-page-lMnST7D_.js → projects-page-BNIFwFfc.js} +1 -1
  46. package/dist/gateway/static/root/assets/{remote-access-hub-BIRKBvO_.js → remote-access-hub-DLXqKiA_.js} +1 -1
  47. package/dist/gateway/static/root/assets/{runtime-tools-settings-panel-BPEGTip5.js → runtime-tools-settings-panel-BpQ2GI-0.js} +1 -1
  48. package/dist/gateway/static/root/assets/{schema-form-Dxlu60Td.js → schema-form-HE1G26Lx.js} +1 -1
  49. package/dist/gateway/static/root/assets/{sessions-page-CATO9G3y.js → sessions-page-DWaXf_25.js} +1 -1
  50. package/dist/gateway/static/root/assets/settings-advanced-gate-JFCbnCL2.js +1 -0
  51. package/dist/gateway/static/root/assets/{settings-form-section-ChXh3Bwk.js → settings-form-section-CXAn0Xhy.js} +1 -1
  52. package/dist/gateway/static/root/assets/{settings-loading-skeleton-BCAUqIe2.js → settings-loading-skeleton-DsFu7Bcv.js} +1 -1
  53. package/dist/gateway/static/root/assets/{settings-page-D25W9Okr.js → settings-page-C4iib9nO.js} +1 -1
  54. package/dist/gateway/static/root/assets/{setup-status-panel-DsN7Z4Fl.js → setup-status-panel-BA83Wr1d.js} +1 -1
  55. package/dist/gateway/static/root/assets/{share-preview-page-CRFnUaNb.js → share-preview-page-BOGl3s6M.js} +1 -1
  56. package/dist/gateway/static/root/assets/{shares-settings-CAX0eNaP.js → shares-settings-Q2MdGaBi.js} +1 -1
  57. package/dist/gateway/static/root/assets/{skill-reload-api-Doy1gghe.js → skill-reload-api-cFtfVeFU.js} +1 -1
  58. package/dist/gateway/static/root/assets/{skills-page-Cl7jjTK7.js → skills-page-CdaFtNw9.js} +1 -1
  59. package/dist/gateway/static/root/assets/{skills-page.utils-BiCl4nb5.js → skills-page.utils-DYaAddUL.js} +1 -1
  60. package/dist/gateway/static/root/assets/{system-settings-panel-BuESR7ZT.js → system-settings-panel-Co7gilRd.js} +1 -1
  61. package/dist/gateway/static/root/assets/{task-detail-page-BRiy8NL3.js → task-detail-page-5B1pswu8.js} +1 -1
  62. package/dist/gateway/static/root/assets/{use-autosave-Dg1mgJ_l.js → use-autosave-DnnZtMpA.js} +1 -1
  63. package/dist/gateway/static/root/assets/{user-context-page-CqoADNKu.js → user-context-page-Dr1FKjXv.js} +1 -1
  64. package/dist/gateway/static/root/assets/{voice-api-key-field-BDNexlVR.js → voice-api-key-field-wetUpi3i.js} +1 -1
  65. package/dist/gateway/static/root/assets/{work-discovery-overlay-BHTfeaWL.js → work-discovery-overlay-tbTWASJJ.js} +1 -1
  66. package/dist/gateway/static/root/assets/{workflow-run-setup-panel-Cf_w-NZy.js → workflow-run-setup-panel-Dy0fDs8w.js} +1 -1
  67. package/dist/gateway/static/root/assets/{workflows-page-j0P-uECz.js → workflows-page-IVP3GSkI.js} +1 -1
  68. package/dist/gateway/static/root/index.html +1 -1
  69. package/dist/package.js +1 -1
  70. package/dist/src/agent/agent-instance-gateway.d.ts +1 -1
  71. package/dist/src/agent/agent-manager.d.ts +1 -1
  72. package/dist/src/agent/agent-manager.js +18 -3
  73. package/dist/src/agent/background-review/prompts.d.ts +8 -2
  74. package/dist/src/agent/background-review/prompts.js +25 -12
  75. package/dist/src/agent/background-review/run-background-review.d.ts +7 -2
  76. package/dist/src/agent/background-review/run-background-review.js +175 -160
  77. package/dist/src/agent/memory/index.d.ts +1 -1
  78. package/dist/src/agent/memory/index.js +2 -2
  79. package/dist/src/agent/memory/manager.d.ts +1 -11
  80. package/dist/src/agent/memory/manager.js +0 -16
  81. package/dist/src/agent/memory/understanding/service.d.ts +0 -11
  82. package/dist/src/agent/memory/understanding/service.js +7 -173
  83. package/dist/src/agent/memory/user-context-coordinator.d.ts +1 -3
  84. package/dist/src/agent/memory/user-context-coordinator.js +3 -66
  85. package/dist/src/agent/orchestration/agent-orchestrator.js +1 -1
  86. package/dist/src/agent/service/direct-turn-helpers.js +1 -1
  87. package/dist/src/cli/commands/doctor/checks/database-schema.js +1 -1
  88. package/dist/src/config/schema.d.ts +4 -0
  89. package/dist/src/config/schema.js +1 -0
  90. package/dist/src/connectors/connected-source-understanding.js +35 -21
  91. package/dist/src/connectors/learning-coordinator.js +1 -42
  92. package/dist/src/gateway/chat-stream/mapper.d.ts +2 -0
  93. package/dist/src/gateway/chat-stream/mapper.js +5 -0
  94. package/dist/src/gateway/hono/routes/understanding-sources.js +4 -1
  95. package/dist/src/gateway/hono/routes/you.js +29 -11
  96. package/dist/src/gateway/service/run-gateway-agent.js +5 -1
  97. package/dist/src/knowledge/index.d.ts +0 -1
  98. package/dist/src/knowledge/index.js +1 -2
  99. package/dist/src/notifications/planner.js +5 -1
  100. package/dist/src/storage/sqlite/index.d.ts +1 -1
  101. package/dist/src/storage/sqlite/index.js +2 -2
  102. package/dist/src/storage/sqlite/migrations/137_understanding_status_audit.sql +71 -0
  103. package/dist/src/storage/sqlite/migrations/runner.d.ts +1 -1
  104. package/dist/src/storage/sqlite/migrations/runner.js +3 -3
  105. package/dist/src/storage/sqlite/migrations/runner.ts +1 -1
  106. package/dist/src/storage/sqlite/schema.js +1 -1
  107. package/dist/src/storage/sqlite/user-context-repository.d.ts +16 -4
  108. package/dist/src/storage/sqlite/user-context-repository.js +56 -12
  109. package/dist/src/user-context/config.d.ts +8 -0
  110. package/dist/src/user-context/config.js +3 -0
  111. package/dist/src/user-context/consolidation.js +16 -4
  112. package/dist/src/user-context/extraction/executor.d.ts +22 -0
  113. package/dist/src/user-context/extraction/executor.js +142 -0
  114. package/dist/src/user-context/extraction/registry.d.ts +1 -1
  115. package/dist/src/user-context/extraction/registry.js +5 -34
  116. package/dist/src/user-context/extraction/repair.js +4 -1
  117. package/dist/src/user-context/extraction/semantic.d.ts +18 -0
  118. package/dist/src/user-context/extraction/semantic.js +148 -0
  119. package/dist/src/user-context/understandingQuality.js +4 -0
  120. package/dist/src/work-discovery/analyzer.js +9 -4
  121. package/dist/src/work-discovery/service.d.ts +1 -0
  122. package/dist/src/work-discovery/service.js +5 -4
  123. package/dist/src/work-discovery/types.d.ts +1 -0
  124. package/package.json +14 -8
  125. package/dist/gateway/static/root/assets/settings-advanced-gate-Cco_W41x.js +0 -1
  126. package/dist/src/agent/memory/understanding/correction.d.ts +0 -3
  127. package/dist/src/agent/memory/understanding/correction.js +0 -39
  128. package/dist/src/knowledge/connected-understanding-pipeline.d.ts +0 -17
  129. package/dist/src/knowledge/connected-understanding-pipeline.js +0 -278
@@ -44,7 +44,7 @@ export interface AgentInstanceGateway {
44
44
  /** Build the bounded, policy-filtered context used for this model turn. */
45
45
  prepareUserTurnContext(userMessage: AgentMessage, sessionKey: string, turnId: string): Promise<import('./memory/context/types.js').UserContextPlan>;
46
46
  /** Post-turn: sync external memory providers, queue next prefetch. */
47
- afterAgentTurn(sessionKey: string, userPlainText: string): Promise<import('./memory/understanding/types.js').UnderstandingReviewResult | undefined>;
47
+ afterAgentTurn(sessionKey: string, userPlainText: string, turnId: string): Promise<import('./memory/understanding/types.js').UnderstandingReviewResult | undefined>;
48
48
  /** Bump the per-session "turns since memory review" counter. */
49
49
  beginBackgroundReviewUserTurn(sessionKey: string): void;
50
50
  /** Fire-and-forget review (memory + skill nudges) once the main turn finishes. */
@@ -206,7 +206,7 @@ export declare class AgentManager implements AgentInstanceGateway {
206
206
  * After a completed turn: sync external providers and queue next-turn prefetch.
207
207
  * Delegates to {@link UserContextCoordinator}.
208
208
  */
209
- afterAgentTurn(sessionKey: string, userPlainText: string): Promise<import('./memory/understanding/types.js').UnderstandingReviewResult | undefined>;
209
+ afterAgentTurn(sessionKey: string, userPlainText: string, turnId: string): Promise<import('./memory/understanding/types.js').UnderstandingReviewResult | undefined>;
210
210
  /**
211
211
  * Call once per user turn before the main embedded agent turn.
212
212
  * Delegates to {@link BackgroundReviewCoordinator}.
@@ -8,6 +8,7 @@ import { getAgentDefaultModelRef, init_schema } from "../config/schema.js";
8
8
  import { applyConfigOverrides } from "../config/runtime-overrides.js";
9
9
  import { expandWorkspacePathString, init_workspace_path } from "../config/workspace-path.js";
10
10
  import { init_agent_scope, resolveAgentProfileDir } from "./agent-scope.js";
11
+ import { init_session_key, parseSessionKey } from "../routing/session-key.js";
11
12
  import { resolveEffectiveAgentProfile, resolveEffectiveAgentProfileForSession } from "../config/agent-profile.js";
12
13
  import { init_paths, resolveBundledSkillsDir } from "../config/paths.js";
13
14
  import { init_sync_provider_auth, resolveProviderApiKeySync } from "../auth/sync-provider-auth.js";
@@ -36,6 +37,7 @@ import { evictAllEmbeddedSessionRunners, evictEmbeddedSessionRunner } from "./em
36
37
  import { isMemorySubsystemEnabled } from "./memory/memory-config.js";
37
38
  import { UserContextCoordinator } from "./memory/user-context-coordinator.js";
38
39
  import { WorkspaceRuntimeRegistry } from "./workspace-runtime/registry.js";
40
+ import { runTurnUnderstandingReview } from "./background-review/run-background-review.js";
39
41
  import { BackgroundReviewCoordinator } from "./background-review/coordinator.js";
40
42
  import { maybeRequestChannelExecApproval } from "../channels/exec-approval-runtime.js";
41
43
  import { checkBoundary } from "../agent-runtime/boundary-guard.js";
@@ -59,6 +61,7 @@ init_sync_provider_auth();
59
61
  init_providers();
60
62
  init_credentials();
61
63
  init_paths();
64
+ init_session_key();
62
65
  const log = createLogger("AgentManager");
63
66
  var AgentManager = class {
64
67
  agents = /* @__PURE__ */ new Map();
@@ -131,7 +134,6 @@ var AgentManager = class {
131
134
  this.userContext = new UserContextCoordinator({
132
135
  getConfig: () => this.config.config,
133
136
  isEnabledForSession: (sessionKey) => this.isUserContextEnabledForSession(sessionKey),
134
- getAgentIdForSession: (sk) => this.agents.get(sk)?.effectiveProfile.agentId ?? "main",
135
137
  getWorkspaceIdForSession: (sk) => this.getResolvedWorkspaceForSession(sk),
136
138
  getProjectIdForSession: (sk) => getSessionMetadata(sk)?.projectId,
137
139
  getMemoryManagerForSession: (sk) => this.getMemoryManagerForSession(sk),
@@ -299,8 +301,21 @@ var AgentManager = class {
299
301
  * After a completed turn: sync external providers and queue next-turn prefetch.
300
302
  * Delegates to {@link UserContextCoordinator}.
301
303
  */
302
- afterAgentTurn(sessionKey, userPlainText) {
303
- return this.userContext.afterTurn(sessionKey, userPlainText);
304
+ async afterAgentTurn(sessionKey, userPlainText, turnId) {
305
+ await this.userContext.afterTurn(sessionKey, userPlainText);
306
+ if (!this.isUserContextEnabledForSession(sessionKey)) return void 0;
307
+ const parsed = parseSessionKey(sessionKey);
308
+ if (parsed && parsed.peerKind !== "direct") return void 0;
309
+ const instance = this.agents.get(sessionKey);
310
+ if (!instance) return void 0;
311
+ return runTurnUnderstandingReview({
312
+ sessionKey,
313
+ turnId,
314
+ userText: userPlainText,
315
+ mainAgent: instance.agent,
316
+ memoryManager: this.getMemoryManagerForSession(sessionKey),
317
+ getConfig: () => this.mergedConfig()
318
+ });
304
319
  }
305
320
  /**
306
321
  * Call once per user turn before the main embedded agent turn.
@@ -1,2 +1,8 @@
1
- export declare const MEMORY_REVIEW_USER_PROMPT = "Review the conversation above and identify durable user-understanding candidates.\n\nFocus on:\n1. Has the user revealed things about themselves \u2014 persona, desires, preferences, or personal details worth remembering?\n2. Has the user expressed expectations about how you should behave, their work style, emotional-support preferences, boundaries, or how they want you to communicate?\n3. Has the user explicitly corrected a prior assumption? Prefer the correction and do not preserve the contradicted interpretation.\n\nReturn JSON only, with this shape:\n{\"candidates\":[{\"kind\":\"preference\",\"content\":\"...\",\"confidence\":0.8,\"importance\":0.7,\"durability\":\"durable\",\"sensitivity\":\"normal\",\"disclosurePolicy\":\"referenceable\",\"evidenceRefs\":[\"entry-id\"]}]}\n\nAllowed kinds: preference, boundary, relationship, routine, current_state, long_term_goal, project_context, task_lesson, derived_insight.\nEvery reviewed message is prefixed with an evidence_ref. Every candidate must list the exact one or more evidence_ref values that support it. Omit a candidate when no exact message supports it. Only include facts supported by the conversation and likely to matter in a future session. A temporary mood or one-off reaction is current context, not durable identity; omit it unless the user describes a recurring pattern that will matter later. Never include passwords, tokens, credentials, or speculative diagnoses. Use {\"candidates\":[]} when nothing qualifies.\n\nWrite each understanding as concise, neutral profile copy that can be shown directly to the person described, not as an internal note about \"the user\". Prefer a subject-omitted predicate or noun phrase. For example, write \u201C\u503E\u5411\u4F7F\u7528 pnpm \u4F5C\u4E3A\u5305\u7BA1\u7406\u5668\u201D or \u201Cxopc \u9879\u76EE\u7684\u6838\u5FC3\u5F00\u53D1\u8005\u201D, not \u201C\u7528\u6237\u503E\u5411\u4E8E\u4F7F\u7528 pnpm\u201D or \u201C\u7528\u6237\u662F xopc \u9879\u76EE\u7684\u5F00\u53D1\u8005\u201D; write \u201CPrefers pnpm as the package manager\u201D or \u201CCore maintainer of xopc\u201D, not \u201CThe user prefers pnpm\u201D or \u201CThe user is a maintainer of xopc\u201D. Do not begin with generic subject labels or pronouns such as \u201C\u7528\u6237\u201D, \u201C\u8BE5\u7528\u6237\u201D, \u201C\u6B64\u7528\u6237\u201D, \u201C\u4F60\u201D, \u201C\u6211\u201D, \u201Cthe user\u201D, \u201Cuser\u201D, \u201Cyou\u201D, or \u201CI\u201D.\n\nDo not turn a request about the current task into user understanding. Exclude requested outputs, follow-up instructions, project-note edits, investigations, and other one-off work. Every candidate must be a complete standalone profile statement or enduring pattern; never return a clause fragment beginning with a connector such as \"and\", \"also\", \"\u5E76\u4E14\", \"\u4EE5\u53CA\", or \"\u7684\u4E8B\u9879\". Use long_term_goal only when the person states an enduring personal goal, not when they ask the assistant to create, update, investigate, summarize, or track something.";
2
- export declare const UNDERSTANDING_REVIEW_SYSTEM_PROMPT = "You are the user-understanding synthesis stage for the same session. You do not chat with the user and cannot write storage directly. Extract only evidence-backed, durable candidates and return strict JSON matching the requested schema.";
1
+ export declare const UNDERSTANDING_INTERPRETER_SYSTEM_PROMPT = "You are xopc's user-understanding interpreter. You do not chat with the user and cannot write storage. Distinguish memory commands, memory questions, corrections, forgetting, durable user assertions, and ordinary task requests. Return strict JSON only. Never treat assistant text as evidence of a fact about the user.";
2
+ export declare function buildUnderstandingInterpreterPrompt(options: {
3
+ mode: 'turn' | 'transcript';
4
+ availableTargets?: Array<{
5
+ id: string;
6
+ statement: string;
7
+ }>;
8
+ }): string;
@@ -1,21 +1,34 @@
1
1
  import { USER_FACING_UNDERSTANDING_WRITING_GUIDANCE } from "../../user-context/understanding-writing.js";
2
2
  //#region src/agent/background-review/prompts.ts
3
- const MEMORY_REVIEW_USER_PROMPT = `Review the conversation above and identify durable user-understanding candidates.
3
+ const UNDERSTANDING_INTERPRETER_SYSTEM_PROMPT = `You are xopc's user-understanding interpreter. You do not chat with the user and cannot write storage. Distinguish memory commands, memory questions, corrections, forgetting, durable user assertions, and ordinary task requests. Return strict JSON only. Never treat assistant text as evidence of a fact about the user.`;
4
+ function buildUnderstandingInterpreterPrompt(options) {
5
+ const targets = options.availableTargets?.length ? `\nOnly these understanding IDs may be targeted for confirm, correction, or forgetting:\n${options.availableTargets.map((item) => `- ${item.id}: ${item.statement}`).join("\n")}` : "\nNo existing understanding IDs are available to target.";
6
+ return `Interpret the evidence-tagged conversation above for ${options.mode === "turn" ? "the latest user turn" : "durable transcript synthesis"}.
4
7
 
5
- Focus on:
6
- 1. Has the user revealed things about themselves — persona, desires, preferences, or personal details worth remembering?
7
- 2. Has the user expressed expectations about how you should behave, their work style, emotional-support preferences, boundaries, or how they want you to communicate?
8
- 3. Has the user explicitly corrected a prior assumption? Prefer the correction and do not preserve the contradicted interpretation.
8
+ Return exactly this JSON shape:
9
+ {"intent":"none","candidates":[],"targetUnderstandingIds":[],"abstentionReason":"..."}
9
10
 
10
- Return JSON only, with this shape:
11
- {"candidates":[{"kind":"preference","content":"...","confidence":0.8,"importance":0.7,"durability":"durable","sensitivity":"normal","disclosurePolicy":"referenceable","evidenceRefs":["entry-id"]}]}
11
+ Allowed intents: memory_create, memory_query, memory_confirm, memory_correct, memory_forget, user_assertion, task_request, none.
12
+
13
+ Candidate shape:
14
+ {"factKey":"communication:concise","statement":"...","kind":"preference","explicitness":"observed","durability":"durable","scopeHint":"global","confidence":0.8,"importance":0.7,"sensitivity":"normal","disclosurePolicy":"referenceable","evidence":[{"ref":"entry-id","quote":"exact quote from that user message"}],"selfContained":true,"unresolvedReferences":[]}
12
15
 
13
16
  Allowed kinds: preference, boundary, relationship, routine, current_state, long_term_goal, project_context, task_lesson, derived_insight.
14
- Every reviewed message is prefixed with an evidence_ref. Every candidate must list the exact one or more evidence_ref values that support it. Omit a candidate when no exact message supports it. Only include facts supported by the conversation and likely to matter in a future session. A temporary mood or one-off reaction is current context, not durable identity; omit it unless the user describes a recurring pattern that will matter later. Never include passwords, tokens, credentials, or speculative diagnoses. Use {"candidates":[]} when nothing qualifies.
15
17
 
16
- ${USER_FACING_UNDERSTANDING_WRITING_GUIDANCE}
18
+ Rules:
19
+ - A question such as “Do you remember this goal?” is memory_query and creates no candidate.
20
+ - A request to create, summarize, update, investigate, or track a goal is task_request, not a user goal.
21
+ - Every candidate needs an exact quote from one or more user messages. Assistant messages may resolve context but never count as evidence.
22
+ - Extract zero to eight independent candidates; do not collapse multiple facts into one.
23
+ - factKey must be a stable language-neutral lowercase identifier using letters, digits, colons, or hyphens. Equivalent facts in different languages must use the same factKey.
24
+ - Set selfContained=false and list unresolvedReferences for unresolved words such as this, that, it, 这个, 那个, or 它.
25
+ - Omit temporary reactions and one-off task instructions.
26
+ - Never include passwords, credentials, regulated identifiers, or speculative diagnoses.
27
+ - For transcript mode, use explicitness=inferred unless the latest user message is itself an explicit memory command or correction.
28
+ - If evidence is insufficient, return candidates=[] and explain abstentionReason.
17
29
 
18
- Do not turn a request about the current task into user understanding. Exclude requested outputs, follow-up instructions, project-note edits, investigations, and other one-off work. Every candidate must be a complete standalone profile statement or enduring pattern; never return a clause fragment beginning with a connector such as "and", "also", "并且", "以及", or "的事项". Use long_term_goal only when the person states an enduring personal goal, not when they ask the assistant to create, update, investigate, summarize, or track something.`;
19
- const UNDERSTANDING_REVIEW_SYSTEM_PROMPT = `You are the user-understanding synthesis stage for the same session. You do not chat with the user and cannot write storage directly. Extract only evidence-backed, durable candidates and return strict JSON matching the requested schema.`;
30
+ ${USER_FACING_UNDERSTANDING_WRITING_GUIDANCE}
31
+ ${targets}`;
32
+ }
20
33
  //#endregion
21
- export { MEMORY_REVIEW_USER_PROMPT, UNDERSTANDING_REVIEW_SYSTEM_PROMPT };
34
+ export { UNDERSTANDING_INTERPRETER_SYSTEM_PROMPT, buildUnderstandingInterpreterPrompt };
@@ -1,7 +1,7 @@
1
1
  import { Agent } from '@earendil-works/pi-agent-core';
2
2
  import type { Config } from '../../config/schema.js';
3
3
  import type { MemoryManager } from '../memory/manager.js';
4
- import type { UnderstandingCandidate } from '../memory/understanding/types.js';
4
+ import type { UnderstandingReviewResult } from '../memory/understanding/types.js';
5
5
  import type { BackgroundReviewSettings } from './settings.js';
6
6
  export interface RunBackgroundReviewParams {
7
7
  sessionKey: string;
@@ -10,5 +10,10 @@ export interface RunBackgroundReviewParams {
10
10
  memoryManager: MemoryManager;
11
11
  getConfig: () => Config | undefined;
12
12
  }
13
- export declare function parseUnderstandingCandidates(raw: string): UnderstandingCandidate[];
13
+ export interface RunTurnUnderstandingParams extends Omit<RunBackgroundReviewParams, 'settings'> {
14
+ turnId: string;
15
+ userText: string;
16
+ maxHistoryMessages?: number;
17
+ }
18
+ export declare function runTurnUnderstandingReview(params: RunTurnUnderstandingParams): Promise<UnderstandingReviewResult>;
14
19
  export declare function runBackgroundReviewTurn(params: RunBackgroundReviewParams): Promise<void>;
@@ -1,54 +1,60 @@
1
1
  import { createLogger } from "../../utils/logger/index.js";
2
2
  import { init_logger } from "../../utils/logger.js";
3
- import { UNDERSTANDING_KINDS } from "../../user-context/domain.js";
4
3
  import { finishContextExtractionRun } from "../../storage/sqlite/context-extraction-repository.js";
5
- import { createContextEvidence } from "../../storage/sqlite/user-context-repository.js";
6
- import { getSessionMetadata } from "../../storage/sqlite/session-repository.js";
4
+ import { getTurnPersonalization } from "../../storage/sqlite/user-context-repository.js";
7
5
  import { loadCompactionSourceSnapshot } from "../../storage/sqlite/transcript-repository.js";
8
6
  import "../../storage/sqlite/index.js";
7
+ import { extractProfileAgentId } from "../../config/agent-profile.js";
9
8
  import { init_sync_provider_auth, resolveProviderApiKeySync } from "../../auth/sync-provider-auth.js";
10
- import { getApiKeySync, init_providers } from "../../providers/index.js";
9
+ import { getApiKeySync, init_providers, resolveModel } from "../../providers/index.js";
11
10
  import { createExtensionAwareStreamFn } from "../../providers/extension-stream-bridge.js";
12
11
  import { extractTextContent } from "../context/workspace.js";
13
12
  import { readAgentMessageContent } from "../memory/agent-message-access.js";
14
13
  import { resolveAgentTurnTimeoutMs, runAgentTurnWithTimeout } from "../orchestration/run-agent-turn-with-timeout.js";
15
- import { claimRegisteredExtraction, extractionInputHash } from "../../user-context/extraction/registry.js";
16
- import { isDurableUnderstandingCandidate } from "../../user-context/understandingQuality.js";
14
+ import { resolveTypedModelRef } from "../../config/agent-typed-models.js";
15
+ import { claimRegisteredExtraction } from "../../user-context/extraction/registry.js";
17
16
  import { isAssistantTurnAborted, isAssistantTurnFailed } from "../orchestration/llm-turn-retry.js";
18
- import { MEMORY_REVIEW_USER_PROMPT, UNDERSTANDING_REVIEW_SYSTEM_PROMPT } from "./prompts.js";
17
+ import { emptyUnderstandingReview, executeUnderstandingInterpretation } from "../../user-context/extraction/executor.js";
18
+ import { parseSemanticUnderstanding } from "../../user-context/extraction/semantic.js";
19
+ import { UNDERSTANDING_INTERPRETER_SYSTEM_PROMPT, buildUnderstandingInterpreterPrompt } from "./prompts.js";
19
20
  import { Agent } from "@earendil-works/pi-agent-core";
20
21
  //#region src/agent/background-review/run-background-review.ts
21
22
  init_sync_provider_auth();
22
23
  init_providers();
23
24
  init_logger();
24
- const log = createLogger("BackgroundReview");
25
+ const log = createLogger("UnderstandingInterpreter");
25
26
  function isReviewMessage(value) {
26
27
  if (!value || typeof value !== "object") return false;
27
28
  const role = value.role;
28
29
  return role === "user" || role === "assistant";
29
30
  }
30
- function tagMessage(message, entryId) {
31
- const copy = JSON.parse(JSON.stringify(message));
32
- const tag = `[evidence_ref:${entryId}]\n`;
33
- const messageContent = readAgentMessageContent(copy);
34
- if (typeof messageContent === "string") return {
31
+ function messageText(message) {
32
+ const content = readAgentMessageContent(message);
33
+ if (typeof content === "string") return content;
34
+ return Array.isArray(content) ? extractTextContent(content) : "";
35
+ }
36
+ function tagMessage(entry) {
37
+ const copy = JSON.parse(JSON.stringify(entry.message));
38
+ const tag = `[evidence_ref:${entry.ref}] [role:${entry.role}]\n`;
39
+ const content = readAgentMessageContent(copy);
40
+ if (typeof content === "string") return {
35
41
  ...copy,
36
- content: `${tag}${messageContent}`
42
+ content: `${tag}${content}`
37
43
  };
38
- if (Array.isArray(messageContent)) {
39
- const content = [...messageContent];
40
- const first = content[0];
41
- if (first?.type === "text") content[0] = {
44
+ if (Array.isArray(content)) {
45
+ const parts = [...content];
46
+ const first = parts[0];
47
+ if (first?.type === "text") parts[0] = {
42
48
  ...first,
43
49
  text: `${tag}${first.text ?? ""}`
44
50
  };
45
- else content.unshift({
51
+ else parts.unshift({
46
52
  type: "text",
47
53
  text: tag
48
54
  });
49
55
  return {
50
56
  ...copy,
51
- content
57
+ content: parts
52
58
  };
53
59
  }
54
60
  return copy;
@@ -56,89 +62,75 @@ function tagMessage(message, entryId) {
56
62
  function loadEvidenceMessages(sessionKey, max) {
57
63
  const snapshot = loadCompactionSourceSnapshot(sessionKey);
58
64
  if (!snapshot) return [];
59
- return snapshot.entries.filter((entry) => isReviewMessage(entry.row)).slice(-max).map((entry) => ({
60
- entryId: entry.entryId,
61
- createdAt: entry.createdAt,
62
- message: entry.row
63
- }));
65
+ return snapshot.entries.filter((entry) => isReviewMessage(entry.row)).slice(-max).map((entry) => {
66
+ const message = entry.row;
67
+ return {
68
+ ref: entry.entryId,
69
+ role: message.role,
70
+ text: messageText(message),
71
+ createdAt: entry.createdAt,
72
+ message
73
+ };
74
+ });
64
75
  }
65
- const ALLOWED_UNDERSTANDING_KINDS = new Set(UNDERSTANDING_KINDS);
66
- const ALLOWED_SENSITIVITIES = new Set([
67
- "normal",
68
- "personal",
69
- "secret",
70
- "regulated"
71
- ]);
72
76
  function lastAssistantText(agent) {
73
- for (let i = agent.state.messages.length - 1; i >= 0; i--) {
77
+ for (let i = agent.state.messages.length - 1; i >= 0; i -= 1) {
74
78
  const message = agent.state.messages[i];
75
- if (message.role !== "assistant") continue;
76
- return Array.isArray(message.content) ? extractTextContent(message.content) : String(message.content);
79
+ if (message.role === "assistant") return messageText(message);
77
80
  }
78
81
  return "";
79
82
  }
80
- function parseBackgroundCandidates(raw) {
81
- const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(raw)?.[1];
82
- const start = raw.indexOf("{");
83
- const end = raw.lastIndexOf("}");
84
- const candidateJson = fenced ?? (start >= 0 && end > start ? raw.slice(start, end + 1) : raw);
83
+ function isLocalModel(model) {
84
+ if (["ollama", "lmstudio"].includes(model.provider)) return true;
85
85
  try {
86
- const parsed = JSON.parse(candidateJson);
87
- if (!Array.isArray(parsed.candidates)) return [];
88
- const output = [];
89
- for (const value of parsed.candidates.slice(0, 8)) {
90
- if (!value || typeof value !== "object") continue;
91
- const item = value;
92
- if (!ALLOWED_UNDERSTANDING_KINDS.has(item.kind)) continue;
93
- if (typeof item.content !== "string" || item.content.trim().length < 4) continue;
94
- const kind = item.kind;
95
- if (!isDurableUnderstandingCandidate(kind, item.content)) continue;
96
- const confidence = typeof item.confidence === "number" ? item.confidence : .65;
97
- const importance = typeof item.importance === "number" ? item.importance : .5;
98
- const durability = item.durability === "ephemeral" || item.durability === "recurring" ? item.durability : "durable";
99
- const sensitivity = ALLOWED_SENSITIVITIES.has(item.sensitivity) ? item.sensitivity : "personal";
100
- const disclosurePolicy = item.disclosurePolicy === "silent" || item.disclosurePolicy === "ask_before_reference" ? item.disclosurePolicy : "referenceable";
101
- const evidenceRefs = Array.isArray(item.evidenceRefs) ? [...new Set(item.evidenceRefs.filter((value) => typeof value === "string" && value.trim().length > 0))] : [];
102
- output.push({
103
- kind,
104
- content: item.content.trim(),
105
- confidence: Math.max(0, Math.min(1, confidence)),
106
- importance: Math.max(0, Math.min(1, importance)),
107
- explicitness: "inferred",
108
- durability,
109
- sensitivity,
110
- disclosurePolicy,
111
- evidenceRefs
112
- });
113
- }
114
- return output;
86
+ const hostname = new URL(model.baseUrl).hostname;
87
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
115
88
  } catch {
116
- return [];
89
+ return false;
117
90
  }
118
91
  }
119
- function parseUnderstandingCandidates(raw) {
120
- return parseBackgroundCandidates(raw).map(({ evidenceRefs: _evidenceRefs, ...candidate }) => candidate);
121
- }
122
- async function runUnderstandingReview(params) {
123
- const { sessionKey, mainAgent, settings, memoryManager, getConfig } = params;
124
- const evidenceMessages = loadEvidenceMessages(sessionKey, settings.maxHistoryMessages);
125
- if (!evidenceMessages.length) {
126
- log.debug({ sessionKey }, "User-understanding review skipped because no persisted evidence was available");
127
- return;
92
+ function resolveInterpreterRuntime(params) {
93
+ const config = params.getConfig();
94
+ const processingPolicy = config?.userContext.understanding.processingPolicy ?? "remote_allowed";
95
+ let model;
96
+ if (config) {
97
+ const agentId = extractProfileAgentId(params.sessionKey, config);
98
+ for (const role of ["understanding", "small"]) {
99
+ const ref = resolveTypedModelRef(config, agentId, role);
100
+ if (!ref) continue;
101
+ try {
102
+ model = resolveModel(ref);
103
+ break;
104
+ } catch (err) {
105
+ log.debug({
106
+ err,
107
+ agentId,
108
+ role,
109
+ modelRef: ref
110
+ }, "Configured understanding model could not be resolved");
111
+ }
112
+ }
128
113
  }
129
- const lastEvidence = evidenceMessages[evidenceMessages.length - 1];
130
- const extraction = claimRegisteredExtraction({
131
- extractorId: "transcript-synthesis",
132
- sourceRef: `session:${sessionKey}:window:${evidenceMessages[0].entryId}:${lastEvidence.entryId}`,
133
- contentForHash: evidenceMessages.map((entry) => entry.entryId).join("\n"),
134
- processingPolicy: "remote_allowed",
135
- destination: "remote_model"
136
- });
137
- if (!extraction.shouldExecute) return;
114
+ model ??= params.mainAgent.state.model;
115
+ if (processingPolicy === "local_only" && !isLocalModel(model)) {
116
+ log.debug({
117
+ sessionKey: params.sessionKey,
118
+ provider: model.provider,
119
+ modelId: model.id
120
+ }, "Understanding interpretation skipped because no local model is configured");
121
+ return null;
122
+ }
123
+ return {
124
+ model,
125
+ processingPolicy,
126
+ destination: isLocalModel(model) ? "local_model" : "remote_model"
127
+ };
128
+ }
129
+ async function interpret(params) {
138
130
  const reviewAgent = new Agent({
139
131
  initialState: {
140
- systemPrompt: UNDERSTANDING_REVIEW_SYSTEM_PROMPT,
141
- model: mainAgent.state.model,
132
+ systemPrompt: UNDERSTANDING_INTERPRETER_SYSTEM_PROMPT,
133
+ model: params.model,
142
134
  thinkingLevel: "off",
143
135
  tools: [],
144
136
  messages: []
@@ -146,79 +138,71 @@ async function runUnderstandingReview(params) {
146
138
  streamFn: createExtensionAwareStreamFn(),
147
139
  getApiKey: (provider) => resolveProviderApiKeySync(provider) ?? getApiKeySync(provider) ?? ""
148
140
  });
149
- reviewAgent.state.messages = evidenceMessages.map((entry) => tagMessage(entry.message, entry.entryId));
150
- const timeoutMs = Math.min(settings.maxDurationMs, resolveAgentTurnTimeoutMs(getConfig()));
141
+ reviewAgent.state.messages = params.evidence.map(tagMessage);
151
142
  try {
152
143
  await runAgentTurnWithTimeout(reviewAgent, async () => {
153
144
  await reviewAgent.prompt({
154
145
  role: "user",
155
- content: MEMORY_REVIEW_USER_PROMPT,
146
+ content: buildUnderstandingInterpreterPrompt({
147
+ mode: params.mode,
148
+ availableTargets: params.availableTargets
149
+ }),
156
150
  timestamp: Date.now()
157
151
  });
158
152
  await reviewAgent.waitForIdle();
159
- }, timeoutMs);
153
+ }, Math.min(params.timeoutMs, resolveAgentTurnTimeoutMs(params.getConfig())));
160
154
  } catch (err) {
161
155
  log.warn({
162
156
  err,
163
- sessionKey
164
- }, "User-understanding review failed or timed out");
157
+ sessionKey: params.sessionKey
158
+ }, "User-understanding interpretation failed or timed out");
165
159
  reviewAgent.abort();
166
160
  await reviewAgent.waitForIdle().catch(() => {});
167
- finishContextExtractionRun({
168
- runId: extraction.run.id,
169
- status: "failed",
170
- errorCode: "model_failed"
171
- });
172
- return;
161
+ return null;
173
162
  }
174
- if (isAssistantTurnAborted(reviewAgent) || isAssistantTurnFailed(reviewAgent)) {
163
+ if (isAssistantTurnAborted(reviewAgent) || isAssistantTurnFailed(reviewAgent)) return null;
164
+ return parseSemanticUnderstanding(lastAssistantText(reviewAgent), params.evidence, params.availableTargets.map((item) => item.id));
165
+ }
166
+ async function executeReview(params) {
167
+ const runtime = resolveInterpreterRuntime(params);
168
+ if (!runtime) return emptyUnderstandingReview();
169
+ const extraction = claimRegisteredExtraction({
170
+ extractorId: params.extractorId,
171
+ sourceRef: params.sourceRef,
172
+ contentForHash: params.contentForHash,
173
+ processingPolicy: runtime.processingPolicy,
174
+ destination: runtime.destination
175
+ });
176
+ if (!extraction.shouldExecute) return emptyUnderstandingReview();
177
+ const interpretation = await interpret({
178
+ ...params,
179
+ model: runtime.model
180
+ });
181
+ if (!interpretation) {
175
182
  finishContextExtractionRun({
176
183
  runId: extraction.run.id,
177
184
  status: "failed",
178
- errorCode: "model_failed"
185
+ errorCode: "model_or_schema_failed"
179
186
  });
180
- return;
187
+ return emptyUnderstandingReview();
181
188
  }
182
- const candidates = parseBackgroundCandidates(lastAssistantText(reviewAgent));
183
- let applied = 0;
184
189
  try {
185
- const evidenceByRef = new Map(evidenceMessages.map((entry) => [entry.entryId, entry]));
186
- const projectId = getSessionMetadata(sessionKey)?.projectId;
187
- const outputs = [];
188
- for (const { evidenceRefs, ...candidate } of candidates) {
189
- const referenced = evidenceRefs.flatMap((ref) => {
190
- const entry = evidenceByRef.get(ref);
191
- return entry ? [entry] : [];
192
- });
193
- if (!referenced.length) {
194
- outputs.push({
195
- candidateKey: `${candidate.kind}:${candidate.content}`,
196
- outcome: "rejected"
197
- });
198
- continue;
199
- }
200
- const evidenceIds = referenced.map((entry) => createContextEvidence({
201
- sourceType: "conversation",
202
- sourceRef: `session:${sessionKey}:entry:${entry.entryId}`,
203
- sourceRunId: extraction.run.id,
204
- sessionId: sessionKey,
205
- messageId: entry.entryId,
206
- contentHash: extractionInputHash(JSON.stringify(entry.message)),
207
- retentionPolicy: "derived_only",
208
- processingPolicy: "remote_allowed",
209
- extractorId: "transcript-synthesis",
210
- extractorVersion: "1",
211
- trustLevel: "owner",
212
- observedAt: entry.createdAt
213
- }).id);
214
- const result = await memoryManager.applyUnderstandingCandidates([candidate], {
215
- sessionKey,
216
- ...projectId ? { projectId } : {},
217
- evidenceIds,
218
- reviewSource: "background",
219
- extractionRunId: extraction.run.id
220
- });
221
- outputs.push(...(result.writeOutputs ?? []).map((output) => ({
190
+ const result = await executeUnderstandingInterpretation({
191
+ interpretation,
192
+ evidence: params.evidence,
193
+ extractionRunId: extraction.run.id,
194
+ extractorId: params.extractorId,
195
+ sessionKey: params.sessionKey,
196
+ ...params.turnId ? { turnId: params.turnId } : {},
197
+ memoryManager: params.memoryManager,
198
+ getConfig: params.getConfig,
199
+ reviewSource: params.mode === "turn" ? "turn" : "background",
200
+ processingPolicy: runtime.processingPolicy
201
+ });
202
+ finishContextExtractionRun({
203
+ runId: extraction.run.id,
204
+ status: "completed",
205
+ outputs: result.writeOutputs?.map((output) => ({
222
206
  candidateKey: output.candidateKey,
223
207
  ...output.objectId ? {
224
208
  objectType: "understanding",
@@ -226,30 +210,61 @@ async function runUnderstandingReview(params) {
226
210
  } : {},
227
211
  ...output.versionId ? { versionId: output.versionId } : {},
228
212
  outcome: output.outcome
229
- })));
230
- applied += 1;
231
- }
232
- finishContextExtractionRun({
233
- runId: extraction.run.id,
234
- status: "completed",
235
- outputs
213
+ }))
236
214
  });
237
- } catch (error) {
215
+ return result;
216
+ } catch (err) {
238
217
  finishContextExtractionRun({
239
218
  runId: extraction.run.id,
240
219
  status: "failed",
241
220
  errorCode: "write_failed"
242
221
  });
243
- throw error;
222
+ throw err;
244
223
  }
245
- log.debug({
246
- sessionKey,
247
- candidateCount: candidates.length,
248
- applied
249
- }, "User-understanding review completed");
224
+ }
225
+ async function runTurnUnderstandingReview(params) {
226
+ const evidence = loadEvidenceMessages(params.sessionKey, params.maxHistoryMessages ?? 12);
227
+ if (!evidence.length) return emptyUnderstandingReview();
228
+ const availableTargets = getTurnPersonalization(params.turnId)?.items.flatMap((item) => {
229
+ if (item.objectType !== "understanding" || item.decision !== "selected") return [];
230
+ return [{
231
+ id: item.objectId,
232
+ statement: item.content
233
+ }];
234
+ }) ?? [];
235
+ return executeReview({
236
+ sessionKey: params.sessionKey,
237
+ mainAgent: params.mainAgent,
238
+ memoryManager: params.memoryManager,
239
+ getConfig: params.getConfig,
240
+ evidence,
241
+ mode: "turn",
242
+ extractorId: "turn-semantics",
243
+ sourceRef: `session:${params.sessionKey}:turn:${params.turnId}`,
244
+ contentForHash: params.userText,
245
+ availableTargets,
246
+ timeoutMs: 3e4,
247
+ turnId: params.turnId
248
+ });
250
249
  }
251
250
  async function runBackgroundReviewTurn(params) {
252
- await runUnderstandingReview(params);
251
+ const evidence = loadEvidenceMessages(params.sessionKey, params.settings.maxHistoryMessages);
252
+ if (!evidence.length) return;
253
+ const first = evidence[0];
254
+ const last = evidence[evidence.length - 1];
255
+ await executeReview({
256
+ sessionKey: params.sessionKey,
257
+ mainAgent: params.mainAgent,
258
+ memoryManager: params.memoryManager,
259
+ getConfig: params.getConfig,
260
+ evidence,
261
+ mode: "transcript",
262
+ extractorId: "transcript-synthesis",
263
+ sourceRef: `session:${params.sessionKey}:window:${first.ref}:${last.ref}`,
264
+ contentForHash: evidence.map((entry) => entry.ref).join("\n"),
265
+ availableTargets: [],
266
+ timeoutMs: params.settings.maxDurationMs
267
+ });
253
268
  }
254
269
  //#endregion
255
- export { parseUnderstandingCandidates, runBackgroundReviewTurn };
270
+ export { runBackgroundReviewTurn, runTurnUnderstandingReview };
@@ -5,7 +5,7 @@ export type { UserContextPlan } from './context/types.js';
5
5
  export { createMemoryManagerFromConfig } from './create-memory-manager.js';
6
6
  export { isMemorySubsystemEnabled, shouldPlanUserContextThisTurn, } from './memory-config.js';
7
7
  export { MemoryManager } from './manager.js';
8
- export { UserUnderstandingService, extractExplicitUnderstandingCandidates } from './understanding/service.js';
8
+ export { UserUnderstandingService } from './understanding/service.js';
9
9
  export type { UnderstandingCandidate, UnderstandingReviewResult } from './understanding/types.js';
10
10
  export { discoverMemoryPlugins } from './plugin-discovery.js';
11
11
  export type { MemoryPluginMetadata } from './plugin-discovery.js';
@@ -3,9 +3,9 @@ import { buildUserContextBlock, sanitizeUserContextFenceEscapes } from "./contex
3
3
  import { UserContextPlanner } from "../../user-context/planner.js";
4
4
  import { extractAgentUserPlainText } from "./user-message-text.js";
5
5
  import { BuiltinMemoryProvider } from "./builtin-provider.js";
6
- import { UserUnderstandingService, extractExplicitUnderstandingCandidates } from "./understanding/service.js";
6
+ import { UserUnderstandingService } from "./understanding/service.js";
7
7
  import { MemoryManager } from "./manager.js";
8
8
  import { discoverMemoryPlugins } from "./plugin-discovery.js";
9
9
  import { createMemoryManagerFromConfig } from "./create-memory-manager.js";
10
10
  import { StubMemoryProvider } from "./stub-memory-provider.js";
11
- export { BuiltinMemoryProvider, MemoryManager, StubMemoryProvider, UserContextPlanner, UserUnderstandingService, buildUserContextBlock, createMemoryManagerFromConfig, discoverMemoryPlugins, extractAgentUserPlainText, extractExplicitUnderstandingCandidates, isMemorySubsystemEnabled, sanitizeUserContextFenceEscapes, shouldPlanUserContextThisTurn };
11
+ export { BuiltinMemoryProvider, MemoryManager, StubMemoryProvider, UserContextPlanner, UserUnderstandingService, buildUserContextBlock, createMemoryManagerFromConfig, discoverMemoryPlugins, extractAgentUserPlainText, isMemorySubsystemEnabled, sanitizeUserContextFenceEscapes, shouldPlanUserContextThisTurn };