@xopcai/xopc 0.0.228 → 0.0.230

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 (135) 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-Bp_wmuGW.js} +1 -1
  4. package/dist/gateway/static/root/assets/{agents-B0NI4_NI.js → agents-CKG93dlc.js} +1 -1
  5. package/dist/gateway/static/root/assets/{app-management-settings-panel--SjycrXk.js → app-management-settings-panel-CwAPK4Jm.js} +1 -1
  6. package/dist/gateway/static/root/assets/{appearance-settings-8G-TVUtg.js → appearance-settings-DsGLvqTb.js} +1 -1
  7. package/dist/gateway/static/root/assets/{apps-page-2NiqD-YP.js → apps-page-Ee9qOQEx.js} +1 -1
  8. package/dist/gateway/static/root/assets/{attachment-load-Bx44zSpz.js → attachment-load-B4qqigAQ.js} +1 -1
  9. package/dist/gateway/static/root/assets/{automations-page-CrKAHqc0.js → automations-page-B8ImehSW.js} +1 -1
  10. package/dist/gateway/static/root/assets/{automations-workspace-Q3g9cf0h.js → automations-workspace-BNFAfNwC.js} +1 -1
  11. package/dist/gateway/static/root/assets/{binary-plugins-DjDwnHAQ.js → binary-plugins-DaJbyYc2.js} +1 -1
  12. package/dist/gateway/static/root/assets/{block-editor-7aMOKoZM.js → block-editor-Kl25XWJc.js} +1 -1
  13. package/dist/gateway/static/root/assets/{browser-settings-page-DTwPkmAC.js → browser-settings-page-Cg6NgwE_.js} +1 -1
  14. package/dist/gateway/static/root/assets/{browser-workflows-page-DVLrWKz_.js → browser-workflows-page-DjMxs33B.js} +1 -1
  15. package/dist/gateway/static/root/assets/{capabilities-settings-panel-YcP4FbN7.js → capabilities-settings-panel-NvJKgF1u.js} +1 -1
  16. package/dist/gateway/static/root/assets/{capability-presets-settings-panel-AcPjHHia.js → capability-presets-settings-panel-C2uBdALe.js} +1 -1
  17. package/dist/gateway/static/root/assets/{channels-settings-Ca94Q1D-.js → channels-settings-CIcYKMEs.js} +1 -1
  18. package/dist/gateway/static/root/assets/{chat-terminal-dock-BR-_7KC0.js → chat-terminal-dock-BiU_4Rq6.js} +1 -1
  19. package/dist/gateway/static/root/assets/{connectors-page-SGxfLTd6.js → connectors-page-CEEcmUiP.js} +1 -1
  20. package/dist/gateway/static/root/assets/{cron-expression-D8-c-Tkw.js → cron-expression-Cs_5pUPT.js} +1 -1
  21. package/dist/gateway/static/root/assets/{date-picker-kV-Jyl9J.js → date-picker-y1kWrFVU.js} +1 -1
  22. package/dist/gateway/static/root/assets/{dependency-picker-CwKcrfGj.js → dependency-picker-skc62zrn.js} +1 -1
  23. package/dist/gateway/static/root/assets/{desktop-pet-settings-CTs5WGzk.js → desktop-pet-settings-BVVCBgYK.js} +1 -1
  24. package/dist/gateway/static/root/assets/{desktop-pet-D9rnchu3.js → desktop-pet-ux9DxchT.js} +1 -1
  25. package/dist/gateway/static/root/assets/{directory-picker-path-field-CCl0aaDm.js → directory-picker-path-field-V8vZP0Dy.js} +1 -1
  26. package/dist/gateway/static/root/assets/{extension-debug-page-Cau40SvC.js → extension-debug-page-Dh6DDuvQ.js} +1 -1
  27. package/dist/gateway/static/root/assets/{extension-page-BsJXdvIL.js → extension-page-8OKQDEat.js} +1 -1
  28. package/dist/gateway/static/root/assets/{extension-settings-page-qWqJyF7-.js → extension-settings-page-BgSV0Nny.js} +1 -1
  29. package/dist/gateway/static/root/assets/{gateway-config-api-BI0SELXm.js → gateway-config-api-Dlc6eaTG.js} +1 -1
  30. package/dist/gateway/static/root/assets/{gateway-settings-6ZdOIC7F.js → gateway-settings-DqQgiAUv.js} +1 -1
  31. package/dist/gateway/static/root/assets/{heartbeat-settings-KBwhXeFD.js → heartbeat-settings-Pxqk5GFH.js} +1 -1
  32. package/dist/gateway/static/root/assets/{home-page-BA2M4CLi.js → home-page-1xjo6wE4.js} +1 -1
  33. package/dist/gateway/static/root/assets/{index-BX0dz1JK.js → index-Bbd_dXui.js} +17 -17
  34. package/dist/gateway/static/root/assets/{keyboard-shortcuts-settings-kHtpnyEm.js → keyboard-shortcuts-settings-BSFNqxzY.js} +1 -1
  35. package/dist/gateway/static/root/assets/{local-app-workbench-page-D2nkn09R.js → local-app-workbench-page-heQ4-PJ7.js} +1 -1
  36. package/dist/gateway/static/root/assets/{local-apps-page-BCXa0oUa.js → local-apps-page-DzU6yZ9-.js} +1 -1
  37. package/dist/gateway/static/root/assets/{logs-page-D3sNst0K.js → logs-page-BblnS6Jy.js} +1 -1
  38. package/dist/gateway/static/root/assets/{management-settings-tHnlfOAQ.js → management-settings-B8hM56HS.js} +1 -1
  39. package/dist/gateway/static/root/assets/{markdown-split-BMLqHHr5.js → markdown-split-DRbZjxMK.js} +1 -1
  40. package/dist/gateway/static/root/assets/{media-plugins-DybwqTgv.js → media-plugins-B8vMe5VX.js} +1 -1
  41. package/dist/gateway/static/root/assets/{notes-page-C24SfF6r.js → notes-page-B-YZ7iuK.js} +1 -1
  42. package/dist/gateway/static/root/assets/{notes-workbench-CTdZc3ov.js → notes-workbench-CAM09C8b.js} +2 -2
  43. package/dist/gateway/static/root/assets/{product-open-page-DBfCVlJq.js → product-open-page-DkWcyki5.js} +1 -1
  44. package/dist/gateway/static/root/assets/{project-detail-page-COHaEpbA.js → project-detail-page-BIPIwgU2.js} +1 -1
  45. package/dist/gateway/static/root/assets/{projects-page-lMnST7D_.js → projects-page-B_kzTn1K.js} +1 -1
  46. package/dist/gateway/static/root/assets/{remote-access-hub-BIRKBvO_.js → remote-access-hub-CtD8DsD-.js} +1 -1
  47. package/dist/gateway/static/root/assets/{runtime-tools-settings-panel-BPEGTip5.js → runtime-tools-settings-panel-Bq_ETeal.js} +1 -1
  48. package/dist/gateway/static/root/assets/{schema-form-Dxlu60Td.js → schema-form-BogTlrsP.js} +1 -1
  49. package/dist/gateway/static/root/assets/{sessions-page-CATO9G3y.js → sessions-page-B8n9HI1y.js} +1 -1
  50. package/dist/gateway/static/root/assets/settings-advanced-gate-xlhdRTME.js +1 -0
  51. package/dist/gateway/static/root/assets/{settings-form-section-ChXh3Bwk.js → settings-form-section-Coy1Cbp6.js} +1 -1
  52. package/dist/gateway/static/root/assets/{settings-loading-skeleton-BCAUqIe2.js → settings-loading-skeleton-B5GU7iCG.js} +1 -1
  53. package/dist/gateway/static/root/assets/{settings-page-D25W9Okr.js → settings-page-Dd-BRu12.js} +1 -1
  54. package/dist/gateway/static/root/assets/{setup-status-panel-DsN7Z4Fl.js → setup-status-panel-CwEFAVWx.js} +1 -1
  55. package/dist/gateway/static/root/assets/{share-preview-page-CRFnUaNb.js → share-preview-page-DzXw9UQJ.js} +1 -1
  56. package/dist/gateway/static/root/assets/{shares-settings-CAX0eNaP.js → shares-settings-Bk6UQOwS.js} +1 -1
  57. package/dist/gateway/static/root/assets/{skill-reload-api-Doy1gghe.js → skill-reload-api-DrmQZ3Au.js} +1 -1
  58. package/dist/gateway/static/root/assets/{skills-page-Cl7jjTK7.js → skills-page-Brxb6QnW.js} +1 -1
  59. package/dist/gateway/static/root/assets/{skills-page.utils-BiCl4nb5.js → skills-page.utils-FB5LtEGm.js} +1 -1
  60. package/dist/gateway/static/root/assets/{system-settings-panel-BuESR7ZT.js → system-settings-panel-ChosWt8n.js} +1 -1
  61. package/dist/gateway/static/root/assets/{task-detail-page-BRiy8NL3.js → task-detail-page-CW2sJbdc.js} +1 -1
  62. package/dist/gateway/static/root/assets/{use-autosave-Dg1mgJ_l.js → use-autosave-2SqnmSKD.js} +1 -1
  63. package/dist/gateway/static/root/assets/{user-context-page-CqoADNKu.js → user-context-page-Bq9KB-Oj.js} +1 -1
  64. package/dist/gateway/static/root/assets/{voice-api-key-field-BDNexlVR.js → voice-api-key-field-DtTIF6M8.js} +1 -1
  65. package/dist/gateway/static/root/assets/{work-discovery-overlay-BHTfeaWL.js → work-discovery-overlay-CK3aZDdE.js} +1 -1
  66. package/dist/gateway/static/root/assets/{workflow-run-setup-panel-Cf_w-NZy.js → workflow-run-setup-panel-BjOuddkX.js} +1 -1
  67. package/dist/gateway/static/root/assets/{workflows-page-j0P-uECz.js → workflows-page-CcbGEQol.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/inbound/turn-dispatcher.js +1 -1
  78. package/dist/src/agent/memory/index.d.ts +1 -1
  79. package/dist/src/agent/memory/index.js +2 -2
  80. package/dist/src/agent/memory/manager.d.ts +1 -11
  81. package/dist/src/agent/memory/manager.js +0 -16
  82. package/dist/src/agent/memory/understanding/service.d.ts +0 -11
  83. package/dist/src/agent/memory/understanding/service.js +7 -173
  84. package/dist/src/agent/memory/user-context-coordinator.d.ts +1 -3
  85. package/dist/src/agent/memory/user-context-coordinator.js +3 -66
  86. package/dist/src/agent/orchestration/agent-orchestrator.js +1 -1
  87. package/dist/src/agent/service/direct-turn-helpers.js +1 -1
  88. package/dist/src/agent/service/process-direct-streaming.js +4 -1
  89. package/dist/src/agent/service/webchat-tts.d.ts +2 -0
  90. package/dist/src/agent/service/webchat-tts.js +15 -2
  91. package/dist/src/agent/tools/tts-tool.js +19 -13
  92. package/dist/src/cli/commands/doctor/checks/database-schema.js +1 -1
  93. package/dist/src/config/schema.d.ts +4 -0
  94. package/dist/src/config/schema.js +1 -0
  95. package/dist/src/connectors/connected-source-understanding.js +35 -21
  96. package/dist/src/connectors/learning-coordinator.js +1 -42
  97. package/dist/src/gateway/chat-stream/mapper.d.ts +2 -0
  98. package/dist/src/gateway/chat-stream/mapper.js +16 -0
  99. package/dist/src/gateway/hono/routes/understanding-sources.js +4 -1
  100. package/dist/src/gateway/hono/routes/voice.js +1 -1
  101. package/dist/src/gateway/hono/routes/you.js +29 -11
  102. package/dist/src/gateway/service/run-gateway-agent.js +5 -1
  103. package/dist/src/knowledge/index.d.ts +0 -1
  104. package/dist/src/knowledge/index.js +1 -2
  105. package/dist/src/notifications/planner.js +5 -1
  106. package/dist/src/storage/sqlite/index.d.ts +1 -1
  107. package/dist/src/storage/sqlite/index.js +2 -2
  108. package/dist/src/storage/sqlite/migrations/137_understanding_status_audit.sql +71 -0
  109. package/dist/src/storage/sqlite/migrations/runner.d.ts +1 -1
  110. package/dist/src/storage/sqlite/migrations/runner.js +3 -3
  111. package/dist/src/storage/sqlite/migrations/runner.ts +1 -1
  112. package/dist/src/storage/sqlite/schema.js +1 -1
  113. package/dist/src/storage/sqlite/user-context-repository.d.ts +16 -4
  114. package/dist/src/storage/sqlite/user-context-repository.js +56 -12
  115. package/dist/src/user-context/config.d.ts +8 -0
  116. package/dist/src/user-context/config.js +3 -0
  117. package/dist/src/user-context/consolidation.js +16 -4
  118. package/dist/src/user-context/extraction/executor.d.ts +22 -0
  119. package/dist/src/user-context/extraction/executor.js +142 -0
  120. package/dist/src/user-context/extraction/registry.d.ts +1 -1
  121. package/dist/src/user-context/extraction/registry.js +5 -34
  122. package/dist/src/user-context/extraction/repair.js +4 -1
  123. package/dist/src/user-context/extraction/semantic.d.ts +18 -0
  124. package/dist/src/user-context/extraction/semantic.js +148 -0
  125. package/dist/src/user-context/understandingQuality.js +4 -0
  126. package/dist/src/work-discovery/analyzer.js +9 -4
  127. package/dist/src/work-discovery/service.d.ts +1 -0
  128. package/dist/src/work-discovery/service.js +5 -4
  129. package/dist/src/work-discovery/types.d.ts +1 -0
  130. package/package.json +14 -8
  131. package/dist/gateway/static/root/assets/settings-advanced-gate-Cco_W41x.js +0 -1
  132. package/dist/src/agent/memory/understanding/correction.d.ts +0 -3
  133. package/dist/src/agent/memory/understanding/correction.js +0 -39
  134. package/dist/src/knowledge/connected-understanding-pipeline.d.ts +0 -17
  135. package/dist/src/knowledge/connected-understanding-pipeline.js +0 -278
@@ -6,7 +6,6 @@ import { upsertUserFocus } from "../user-context/sources/repository.js";
6
6
  import { claimRegisteredExtraction } from "../user-context/extraction/registry.js";
7
7
  import { allowsRemoteSourceProcessing } from "../user-context/sources/processing-policy.js";
8
8
  import { analyzeUnderstandingSources } from "../work-discovery/analyzer.js";
9
- import { createHash } from "node:crypto";
10
9
  //#region src/connectors/connected-source-understanding.ts
11
10
  const MAX_CONNECTED_ITEMS = 150;
12
11
  function normalizedValue(item) {
@@ -60,17 +59,14 @@ function connectedItemsForUnderstanding(items) {
60
59
  }];
61
60
  });
62
61
  }
63
- function understandingKind(category) {
64
- if (category === "preference") return "preference";
65
- if (category === "routine") return "routine";
66
- return "project_context";
62
+ function isConnectedPortraitCandidate(candidate) {
63
+ return candidate.category === "preference" || candidate.category === "routine";
67
64
  }
68
65
  function understandingCandidate(candidate) {
69
- const normalized = candidate.statement.toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();
70
66
  return {
71
- kind: understandingKind(candidate.category),
67
+ kind: candidate.category,
72
68
  content: candidate.statement,
73
- canonicalKey: `connected-semantic:${candidate.category}:${createHash("sha256").update(normalized).digest("hex").slice(0, 20)}`,
69
+ canonicalKey: `understanding:${candidate.category}:${candidate.factKey}`,
74
70
  confidence: candidate.confidence === "high" ? .9 : candidate.confidence === "medium" ? .72 : .55,
75
71
  importance: .68,
76
72
  explicitness: "inferred",
@@ -84,6 +80,18 @@ function hasLongVerbatimOverlap(value, sourceTexts, minimumLength = 32) {
84
80
  if (normalized.length < minimumLength) return false;
85
81
  return sourceTexts.some((source) => source.replace(/\s+/g, " ").includes(normalized));
86
82
  }
83
+ function evidenceDate(item) {
84
+ const timestamp = item.occurredAt ?? item.modifiedAt;
85
+ return timestamp == null ? void 0 : new Date(timestamp).toISOString().slice(0, 10);
86
+ }
87
+ function durableConnectedEvidence(candidate, itemsByRef) {
88
+ if (candidate.confidence !== "high") return [];
89
+ const items = [...new Set(candidate.evidenceRefs ?? [])].flatMap((ref) => itemsByRef.get(ref) ?? []);
90
+ if (items.some((item) => item.ownerAttribution !== "user")) return [];
91
+ const required = candidate.category === "routine" ? 3 : 2;
92
+ const dates = new Set(items.map(evidenceDate).filter((value) => Boolean(value)));
93
+ return items.length >= required && dates.size >= required ? items : [];
94
+ }
87
95
  async function deriveConnectedSourceUnderstanding(input) {
88
96
  const knowledgeItems = listKnowledgeSourceItems({
89
97
  agentId: input.agentId,
@@ -115,22 +123,28 @@ async function deriveConnectedSourceUnderstanding(input) {
115
123
  items
116
124
  });
117
125
  const rawTexts = items.flatMap((item) => item.text ? [item.text] : []);
118
- const profileCandidates = analysis.profileCandidates.filter((candidate) => !hasLongVerbatimOverlap(candidate.statement, rawTexts));
119
- const sourceItemIds = [...new Set([...profileCandidates.flatMap((candidate) => candidate.evidenceRefs ?? []), ...analysis.workThreadCandidates.flatMap((candidate) => candidate.evidenceRefs)].map((ref) => ref.startsWith("knowledge-source://") ? ref.slice(19) : ""))].filter(Boolean).slice(0, 20);
120
- const reviewed = profileCandidates.length ? await input.memoryManager.applyUnderstandingCandidates(profileCandidates.map(understandingCandidate), {
121
- agentId: input.agentId,
122
- sourceItemIds,
123
- sourceText: "Bounded semantic synthesis from explicitly connected work sources.",
124
- source: {
125
- provider: "connected-sources",
126
- sourceInstanceId: input.sourceInstanceId
127
- },
128
- reviewSource: "background",
129
- extractionRunId: extraction.run.id
130
- }) : {
126
+ const itemsByRef = new Map(items.map((item) => [item.evidenceRef, item]));
127
+ const profileCandidates = analysis.profileCandidates.filter(isConnectedPortraitCandidate).filter((candidate) => !hasLongVerbatimOverlap(candidate.statement, rawTexts) && durableConnectedEvidence(candidate, itemsByRef).length > 0);
128
+ const reviewed = {
131
129
  created: 0,
132
130
  writeOutputs: []
133
131
  };
132
+ for (const candidate of profileCandidates) {
133
+ const evidenceItems = durableConnectedEvidence(candidate, itemsByRef);
134
+ const applied = await input.memoryManager.applyUnderstandingCandidates([understandingCandidate(candidate)], {
135
+ agentId: input.agentId,
136
+ sourceItemIds: evidenceItems.map((item) => item.id).slice(0, 20),
137
+ sourceText: "Bounded semantic synthesis from explicitly connected work sources.",
138
+ source: {
139
+ provider: "connected-sources",
140
+ sourceInstanceId: input.sourceInstanceId
141
+ },
142
+ reviewSource: "background",
143
+ extractionRunId: extraction.run.id
144
+ });
145
+ reviewed.created += applied.created;
146
+ reviewed.writeOutputs.push(...applied.writeOutputs ?? []);
147
+ }
134
148
  const focuses = analysis.workThreadCandidates.filter((candidate) => !hasLongVerbatimOverlap(candidate.title, rawTexts) && !hasLongVerbatimOverlap(candidate.summary, rawTexts)).map((candidate) => upsertUserFocus({
135
149
  canonicalKey: `connected-focus:${candidate.topicKey}`,
136
150
  title: candidate.title,
@@ -1,6 +1,5 @@
1
1
  import { createLogger } from "../utils/logger/index.js";
2
2
  import { init_logger } from "../utils/logger.js";
3
- import { finishContextExtractionRun } from "../storage/sqlite/context-extraction-repository.js";
4
3
  import { claimNextConnectorLearningJob, enqueueConnectorLearningJob, listConnectorLearningJobs, recoverStaleConnectorLearningJobs, setConnectorLearningPaused, updateConnectorLearningJob } from "../storage/sqlite/connector-learning-repository.js";
5
4
  import { getConnectorInstallation, listConnectorConnections, upsertConnectorConnection } from "../storage/sqlite/connector-repository.js";
6
5
  import { getConnectorAccount, reconcileConnectorAccount } from "../storage/sqlite/connector-account-repository.js";
@@ -11,10 +10,8 @@ import { ComposioSessionsAdapter } from "./composio-sessions.js";
11
10
  import { buildConnectorLearningArguments, getConnectorLearningPlan } from "./learning-recipes.js";
12
11
  import { getConnectorDefinition } from "./catalog.js";
13
12
  import { createUnderstandingSourceRun, getUnderstandingSourceGrant, listUnderstandingSourceRuns, updateUnderstandingSourceGrantCheckpoint, updateUnderstandingSourceRun, upsertUnderstandingSourceGrant } from "../user-context/sources/repository.js";
14
- import { claimRegisteredExtraction } from "../user-context/extraction/registry.js";
15
13
  import { getWorkspacePath } from "../config/workspace-path-helpers.js";
16
14
  import { ConnectedKnowledgePipeline } from "../knowledge/connected-knowledge-pipeline.js";
17
- import { ConnectedUnderstandingPipeline } from "../knowledge/connected-understanding-pipeline.js";
18
15
  import "../knowledge/index.js";
19
16
  import { ingestComposioConnectedSource } from "./connected-source-ingestion.js";
20
17
  import { deriveConnectedSourceUnderstanding } from "./connected-source-understanding.js";
@@ -210,44 +207,6 @@ function startConnectorLearningCoordinator(options) {
210
207
  itemsIndexed
211
208
  }));
212
209
  publish(updateConnectorLearningJob(job.id, { phase: "deriving" }));
213
- const structuralExtraction = claimRegisteredExtraction({
214
- extractorId: "connector-structural",
215
- sourceRef: `understanding-source-run:${sourceRun.id}`,
216
- contentForHash: `${job.sourceInstanceId}:${itemsSeen}:${itemsIndexed}`,
217
- processingPolicy: "local_only",
218
- destination: "deterministic"
219
- });
220
- let understanding = {
221
- proposed: 0,
222
- created: 0,
223
- deduplicated: 0,
224
- rejected: 0,
225
- createdRecords: [],
226
- writeOutputs: []
227
- };
228
- if (structuralExtraction.shouldExecute) try {
229
- understanding = await new ConnectedUnderstandingPipeline(options.getMemoryManager()).process(job.agentId, structuralExtraction.run.id);
230
- finishContextExtractionRun({
231
- runId: structuralExtraction.run.id,
232
- status: "completed",
233
- outputs: (understanding.writeOutputs ?? []).map((output) => ({
234
- candidateKey: output.candidateKey,
235
- ...output.objectId ? {
236
- objectType: "understanding",
237
- objectId: output.objectId
238
- } : {},
239
- ...output.versionId ? { versionId: output.versionId } : {},
240
- outcome: output.outcome
241
- }))
242
- });
243
- } catch (error) {
244
- finishContextExtractionRun({
245
- runId: structuralExtraction.run.id,
246
- status: "failed",
247
- errorCode: "extractor_failed"
248
- });
249
- throw error;
250
- }
251
210
  let semantic = {
252
211
  created: 0,
253
212
  focusCount: 0,
@@ -276,7 +235,7 @@ function startConnectorLearningCoordinator(options) {
276
235
  connectorId: job.connectorId
277
236
  }, `Connected source semantic analysis failed: ${errorMessage}`);
278
237
  }
279
- const candidatesCreated = understanding.created + semantic.created + semantic.focusCount;
238
+ const candidatesCreated = semantic.created + semantic.focusCount;
280
239
  const incomplete = enrichmentErrors.length > 0 || semantic.status !== "completed";
281
240
  const completed = updateConnectorLearningJob(job.id, {
282
241
  status: "completed",
@@ -15,6 +15,7 @@ export declare class ChatStreamMapper {
15
15
  private currentAssistantMessageId;
16
16
  private lastAssistantMessageId;
17
17
  private currentAssistantText;
18
+ private lastAssistantText;
18
19
  private currentAssistantReviewEmitted;
19
20
  private toolCallToMessageId;
20
21
  private turnDiffs;
@@ -28,6 +29,7 @@ export declare class ChatStreamMapper {
28
29
  start(): ChatStreamEvent[];
29
30
  end(status: ChatStreamStatus, summary?: string): ChatStreamEvent[];
30
31
  error(message: string, code?: string): ChatStreamEvent[];
32
+ getLastAssistantText(): string;
31
33
  private mapMessageStart;
32
34
  private mapMessageUpdate;
33
35
  private mapAssistantSnapshot;
@@ -14,6 +14,7 @@ var ChatStreamMapper = class {
14
14
  currentAssistantMessageId;
15
15
  lastAssistantMessageId;
16
16
  currentAssistantText = "";
17
+ lastAssistantText = "";
17
18
  currentAssistantReviewEmitted = false;
18
19
  toolCallToMessageId = /* @__PURE__ */ new Map();
19
20
  turnDiffs = [];
@@ -154,6 +155,9 @@ var ChatStreamMapper = class {
154
155
  petFeedback: createPetFeedback("error", { recoverable: false })
155
156
  })];
156
157
  }
158
+ getLastAssistantText() {
159
+ return this.currentAssistantText || this.lastAssistantText;
160
+ }
157
161
  mapMessageStart(raw) {
158
162
  if (raw?.role !== "assistant") return [];
159
163
  const messageId = this.nextAssistantMessageId();
@@ -260,6 +264,7 @@ var ChatStreamMapper = class {
260
264
  presentation: hasToolCall(message) ? "narration" : "answer",
261
265
  usage: extractUsage(message)
262
266
  }));
267
+ if (this.currentAssistantText) this.lastAssistantText = this.currentAssistantText;
263
268
  this.lastAssistantMessageId = messageId;
264
269
  this.currentAssistantMessageId = void 0;
265
270
  this.currentAssistantText = "";
@@ -337,6 +342,17 @@ var ChatStreamMapper = class {
337
342
  errorMessage: event.isError ? result?.text ?? extractText(result?.content) : void 0
338
343
  })];
339
344
  const details = asRecord(fullResult?.details);
345
+ if (toolName === "text_to_speech" && !event.isError && details) {
346
+ const audio = (Array.isArray(details.media) ? details.media : []).map(asRecord).find((item) => item?.type === "voice" || String(item?.mimeType ?? "").startsWith("audio/"));
347
+ const uri = typeof audio?.uri === "string" ? audio.uri.trim() : "";
348
+ if (uri) events.push(this.make("tts_audio", {
349
+ uri,
350
+ mimeType: typeof audio?.mimeType === "string" ? audio.mimeType : "audio/mpeg",
351
+ name: typeof audio?.name === "string" ? audio.name : "voice.mp3",
352
+ attachTo: "last_assistant",
353
+ messageId
354
+ }));
355
+ }
340
356
  if (toolName === "exec_command" && details) events.push(this.make("command_completed", {
341
357
  messageId,
342
358
  toolCallId,
@@ -67,7 +67,10 @@ function applySourceRevocationChoices(impact, options) {
67
67
  } else updateUserFocus(id, { status: "paused" });
68
68
  for (const id of impact.understandingIds) if (options.derived === "delete") {
69
69
  if (deleteUnderstanding(id)) derivedDeleted += 1;
70
- } else setUnderstandingStatus(id, "needs_review");
70
+ } else setUnderstandingStatus(id, "needs_review", {
71
+ actorType: "runtime",
72
+ source: "understanding-source-revoked"
73
+ });
71
74
  if (options.derived === "delete" && impact.sourceInstanceId) derivedDeleted += deleteMemoryRecordsBySourceInstanceId(impact.sourceInstanceId);
72
75
  const rawDeleted = options.raw === "delete" && impact.sourceInstanceId ? deleteKnowledgeSourceItems(impact.sourceInstanceId) : 0;
73
76
  return {
@@ -14,8 +14,8 @@ import "../../../voice/stt/index.js";
14
14
  import { listSttProvidersForApi } from "../../../voice/stt/list-providers.js";
15
15
  import "../../../voice/tts/index.js";
16
16
  import { createGatewayRouteLogger } from "../lib/route-logger.js";
17
- import { listLocalVoiceModelStatuses, removeLocalVoiceModel, startLocalVoiceModelInstall } from "../../../voice/local/model-manager.js";
18
17
  import { listTtsProvidersForApi } from "../../../voice/tts/list-providers.js";
18
+ import { listLocalVoiceModelStatuses, removeLocalVoiceModel, startLocalVoiceModelInstall } from "../../../voice/local/model-manager.js";
19
19
  //#region src/gateway/hono/routes/voice.ts
20
20
  init_providers();
21
21
  const log = createGatewayRouteLogger("Voice");
@@ -1,7 +1,7 @@
1
1
  import { UNDERSTANDING_KINDS } from "../../../user-context/domain.js";
2
2
  import { listContextExtractionRuns } from "../../../storage/sqlite/context-extraction-repository.js";
3
3
  import { listContextConsolidationRuns } from "../../../storage/sqlite/context-consolidation-repository.js";
4
- import { createCollaborationRule, createUnderstanding, decideContextConsent, deleteCollaborationRule, deleteUnderstanding, getCollaborationRule, getTurnPersonalization, getUnderstanding, getUserProfile, listCollaborationRules, listUnderstandingEvidence, listUnderstandings, recordContextFeedback, rejectUnderstanding, reviseCollaborationRule, reviseUnderstanding, setCollaborationRuleStatus, setUnderstandingStatus, updateUserProfile } from "../../../storage/sqlite/user-context-repository.js";
4
+ import { createCollaborationRule, createUnderstanding, decideContextConsent, deleteCollaborationRule, deleteUnderstanding, getCollaborationRule, getTurnPersonalization, getUnderstanding, getUserProfile, listCollaborationRules, listUnderstandingEvidence, listUnderstandingStatusEvents, listUnderstandings, recordContextFeedback, rejectUnderstanding, reviseCollaborationRule, reviseUnderstanding, setCollaborationRuleStatus, setUnderstandingStatus, updateUserProfile } from "../../../storage/sqlite/user-context-repository.js";
5
5
  import "../../../storage/sqlite/index.js";
6
6
  import { listUserFocuses, updateUserFocus } from "../../../user-context/sources/repository.js";
7
7
  import { canonicalUnderstandingKey, findDuplicateUnderstanding } from "../../../user-context/understanding.js";
@@ -199,8 +199,13 @@ function registerYouRoutes(authenticated, deps) {
199
199
  const objects = normalized.map(({ objectType, objectId, action }) => {
200
200
  if (objectType === "understanding") return action === "accept" ? setUnderstandingStatus(objectId, "active", {
201
201
  explicitness: "explicit",
202
- confidence: 1
203
- }) : action === "reject" ? rejectUnderstanding(objectId, "Rejected during context review") : setUnderstandingStatus(objectId, "needs_review");
202
+ confidence: 1,
203
+ actorType: "user",
204
+ source: "context-review"
205
+ }) : action === "reject" ? rejectUnderstanding(objectId, "Rejected during context review", "user") : setUnderstandingStatus(objectId, "needs_review", {
206
+ actorType: "user",
207
+ source: "context-review-later"
208
+ });
204
209
  return updateUserFocus(objectId, { status: action === "accept" ? "active" : action === "reject" ? "rejected" : "paused" });
205
210
  });
206
211
  return c.json({ objects });
@@ -271,7 +276,10 @@ function registerYouRoutes(authenticated, deps) {
271
276
  authenticated.get("/api/you/understandings/:id/evidence", (c) => {
272
277
  const understanding = getUnderstanding(c.req.param("id"));
273
278
  if (!understanding) return c.json({ error: "Understanding not found" }, 404);
274
- return c.json({ evidence: listUnderstandingEvidence(understanding.id) });
279
+ return c.json({
280
+ evidence: listUnderstandingEvidence(understanding.id),
281
+ statusEvents: listUnderstandingStatusEvents(understanding.id)
282
+ });
275
283
  });
276
284
  authenticated.patch("/api/you/understandings/:id", write, async (c) => {
277
285
  const id = c.req.param("id");
@@ -299,10 +307,14 @@ function registerYouRoutes(authenticated, deps) {
299
307
  }
300
308
  if (body.status !== void 0) {
301
309
  if (!UNDERSTANDING_STATUSES.has(body.status)) return c.json({ error: "Invalid status" }, 400);
302
- understanding = body.status === "rejected" ? rejectUnderstanding(id, nonEmptyString(body.reason, 500) ?? "Rejected by user") : setUnderstandingStatus(id, body.status, body.status === "active" ? {
303
- explicitness: "explicit",
304
- confidence: 1
305
- } : void 0);
310
+ understanding = body.status === "rejected" ? rejectUnderstanding(id, nonEmptyString(body.reason, 500) ?? "Rejected by user", "user") : setUnderstandingStatus(id, body.status, {
311
+ ...body.status === "active" ? {
312
+ explicitness: "explicit",
313
+ confidence: 1
314
+ } : {},
315
+ actorType: "user",
316
+ source: "understanding-edit"
317
+ });
306
318
  }
307
319
  return c.json({ understanding });
308
320
  });
@@ -374,9 +386,15 @@ function registerYouRoutes(authenticated, deps) {
374
386
  ...typeof body.reason === "string" ? { reason: body.reason.slice(0, 500) } : {}
375
387
  });
376
388
  if (objectType === "understanding" && typeof objectId === "string") {
377
- if (rating === "wrong") rejectUnderstanding(objectId, "Marked wrong from turn feedback");
378
- if (rating === "stale") setUnderstandingStatus(objectId, "stale");
379
- if (rating === "sensitive") setUnderstandingStatus(objectId, "needs_review");
389
+ if (rating === "wrong") rejectUnderstanding(objectId, "Marked wrong from turn feedback", "user");
390
+ if (rating === "stale") setUnderstandingStatus(objectId, "stale", {
391
+ actorType: "user",
392
+ source: "turn-feedback-stale"
393
+ });
394
+ if (rating === "sensitive") setUnderstandingStatus(objectId, "needs_review", {
395
+ actorType: "user",
396
+ source: "turn-feedback-sensitive"
397
+ });
380
398
  }
381
399
  if (objectType === "focus" && typeof objectId === "string") {
382
400
  if (rating === "wrong") updateUserFocus(objectId, { status: "rejected" });
@@ -331,6 +331,9 @@ async function* runGatewayAgent(deps, message, channel, chatId, origin, attachme
331
331
  }
332
332
  if (webchatSessionKey) {
333
333
  const metaAfter = await sessionIndex.getSessionMetadata(webchatSessionKey).catch(() => void 0);
334
+ const normalizedResponse = terminalStatus === "success" ? mapper.getLastAssistantText().replace(/\s+/g, " ").trim() : "";
335
+ const responseCharacters = Array.from(normalizedResponse);
336
+ const responsePreview = responseCharacters.length > 180 ? `${responseCharacters.slice(0, 179).join("")}…` : normalizedResponse;
334
337
  if (metaAfter?.name) emit("session.updated", {
335
338
  key: webchatSessionKey,
336
339
  name: metaAfter.name
@@ -346,7 +349,8 @@ async function* runGatewayAgent(deps, message, channel, chatId, origin, attachme
346
349
  sessionKey: webchatSessionKey
347
350
  },
348
351
  source: "webchat",
349
- ...metaAfter?.name?.trim() ? { sessionTitle: metaAfter.name.trim().slice(0, 100) } : {}
352
+ ...metaAfter?.name?.trim() ? { sessionTitle: metaAfter.name.trim().slice(0, 100) } : {},
353
+ ...responsePreview ? { responsePreview } : {}
350
354
  });
351
355
  }
352
356
  }
@@ -1,6 +1,5 @@
1
1
  export * from './types.js';
2
2
  export * from './ingestion-service.js';
3
3
  export * from './connected-knowledge-pipeline.js';
4
- export * from './connected-understanding-pipeline.js';
5
4
  export * from './coordinator.js';
6
5
  export * from './local-folder-adapter.js';
@@ -1,6 +1,5 @@
1
1
  import { KnowledgeIngestionService, SqliteKnowledgeSourceStateStore } from "./ingestion-service.js";
2
2
  import { ConnectedKnowledgePipeline } from "./connected-knowledge-pipeline.js";
3
- import { ConnectedUnderstandingPipeline, deriveConnectedClaimObservations, renderConnectedObservation } from "./connected-understanding-pipeline.js";
4
3
  import { startConnectedKnowledgeCoordinator } from "./coordinator.js";
5
4
  import { LocalFolderKnowledgeSourceAdapter } from "./local-folder-adapter.js";
6
- export { ConnectedKnowledgePipeline, ConnectedUnderstandingPipeline, KnowledgeIngestionService, LocalFolderKnowledgeSourceAdapter, SqliteKnowledgeSourceStateStore, deriveConnectedClaimObservations, renderConnectedObservation, startConnectedKnowledgeCoordinator };
5
+ export { ConnectedKnowledgePipeline, KnowledgeIngestionService, LocalFolderKnowledgeSourceAdapter, SqliteKnowledgeSourceStateStore, startConnectedKnowledgeCoordinator };
@@ -14,6 +14,7 @@ function chatPlan(payload) {
14
14
  zh: "打开对话查看结果。"
15
15
  };
16
16
  const sessionTitle = typeof event.sessionTitle === "string" ? event.sessionTitle.trim().slice(0, 120) : "";
17
+ const responsePreview = completed && typeof event.responsePreview === "string" ? Array.from(event.responsePreview.trim()).slice(0, 180).join("") : "";
17
18
  return {
18
19
  dedupeKey: `${type}:${event.runId}`,
19
20
  notification: {
@@ -27,7 +28,10 @@ function chatPlan(payload) {
27
28
  en: "Response needs attention",
28
29
  zh: "回答需要处理"
29
30
  },
30
- body: sessionTitle ? {
31
+ body: responsePreview ? {
32
+ en: responsePreview,
33
+ zh: responsePreview
34
+ } : sessionTitle ? {
31
35
  en: sessionTitle,
32
36
  zh: sessionTitle
33
37
  } : fallback,
@@ -9,7 +9,7 @@ export { claimContextExtractionRun, finishContextExtractionRun, getContextExtrac
9
9
  export { closeTemporalAssertions, createTemporalAssertion, linkContextObjects, listContextObjectRelations, listTemporalAssertions, type ContextObjectRelation, type ContextTemporalAssertion, } from './context-relation-repository.js';
10
10
  export { finishContextConsolidationRun, getContextConsolidationRun, listContextConsolidationDecisions, listContextConsolidationRuns, recordContextConsolidationDecision, startContextConsolidationRun, type ContextConsolidationDecision, type ContextConsolidationRun, } from './context-consolidation-repository.js';
11
11
  export { summarizeUnderstandingFeedback, summarizeUserUnderstandingQuality, type UnderstandingFeedbackSummary, type UserUnderstandingQualityMetrics, } from './user-context-quality-repository.js';
12
- export { createCollaborationRule, createContextEvidence, createUnderstanding, closeUnderstandingValidity, consumeContextConsent, deleteCollaborationRule, deleteUnderstanding, decideContextConsent, ensureContextConsent, getCollaborationRule, getTurnPersonalization, getUnderstanding, getUserProfile, hasContextConsent, isUnderstandingSuppressed, listCollaborationRules, listUnderstandingEvidence, listUnderstandings, linkUnderstandingEvidence, recordContextFeedback, recordContextRun, rejectUnderstanding, reviseCollaborationRule, reviseUnderstanding, searchActiveUnderstandings, setCollaborationRuleStatus, setUnderstandingStatus, updateUserProfile, type CreateUnderstandingInput, } from './user-context-repository.js';
12
+ export { createCollaborationRule, createContextEvidence, createUnderstanding, closeUnderstandingValidity, consumeContextConsent, deleteCollaborationRule, deleteUnderstanding, decideContextConsent, ensureContextConsent, getCollaborationRule, getTurnPersonalization, getUnderstanding, getUserProfile, hasContextConsent, isUnderstandingSuppressed, listCollaborationRules, listUnderstandingEvidence, listUnderstandingStatusEvents, listUnderstandings, linkUnderstandingEvidence, recordContextFeedback, recordContextRun, rejectUnderstanding, reviseCollaborationRule, reviseUnderstanding, searchActiveUnderstandings, setCollaborationRuleStatus, setUnderstandingStatus, updateUserProfile, type CreateUnderstandingInput, type UnderstandingStatusEvent, } from './user-context-repository.js';
13
13
  export { getUserPerson, getUserPeopleIndexState, listUserPeople, mergeUserPeople, replaceUserPeopleIndex, summarizeUserPeople, updateUserPerson, } from './user-people-repository.js';
14
14
  export { cancelQueuedSessionInput, claimNextSessionInput, findSessionInput, finishSessionInputRun, getSessionInputState, getSessionInputById, insertSessionInput, listActiveSessionInputRuns, mutateQueuedSessionInput, recoverSessionInputState, setSessionInputStatus, type SessionInput, type SessionInputDelivery, type SessionInputState, type SessionInputStatus, } from './session-input-repository.js';
15
15
  export { replaceLatestSessionTurnAndQueueInput, validateLatestSessionTurnTarget, type ReplaceLatestSessionTurnInput, type ReplaceLatestSessionTurnResult, } from './session-turn-replace-repository.js';
@@ -10,7 +10,7 @@ import { claimContextExtractionRun, finishContextExtractionRun, getContextExtrac
10
10
  import { closeTemporalAssertions, createTemporalAssertion, linkContextObjects, listContextObjectRelations, listTemporalAssertions } from "./context-relation-repository.js";
11
11
  import { finishContextConsolidationRun, getContextConsolidationRun, listContextConsolidationDecisions, listContextConsolidationRuns, recordContextConsolidationDecision, startContextConsolidationRun } from "./context-consolidation-repository.js";
12
12
  import { summarizeUnderstandingFeedback, summarizeUserUnderstandingQuality } from "./user-context-quality-repository.js";
13
- import { closeUnderstandingValidity, consumeContextConsent, createCollaborationRule, createContextEvidence, createUnderstanding, decideContextConsent, deleteCollaborationRule, deleteUnderstanding, ensureContextConsent, getCollaborationRule, getTurnPersonalization, getUnderstanding, getUserProfile, hasContextConsent, isUnderstandingSuppressed, linkUnderstandingEvidence, listCollaborationRules, listUnderstandingEvidence, listUnderstandings, recordContextFeedback, recordContextRun, rejectUnderstanding, reviseCollaborationRule, reviseUnderstanding, searchActiveUnderstandings, setCollaborationRuleStatus, setUnderstandingStatus, updateUserProfile } from "./user-context-repository.js";
13
+ import { closeUnderstandingValidity, consumeContextConsent, createCollaborationRule, createContextEvidence, createUnderstanding, decideContextConsent, deleteCollaborationRule, deleteUnderstanding, ensureContextConsent, getCollaborationRule, getTurnPersonalization, getUnderstanding, getUserProfile, hasContextConsent, isUnderstandingSuppressed, linkUnderstandingEvidence, listCollaborationRules, listUnderstandingEvidence, listUnderstandingStatusEvents, listUnderstandings, recordContextFeedback, recordContextRun, rejectUnderstanding, reviseCollaborationRule, reviseUnderstanding, searchActiveUnderstandings, setCollaborationRuleStatus, setUnderstandingStatus, updateUserProfile } from "./user-context-repository.js";
14
14
  import { getUserPeopleIndexState, getUserPerson, listUserPeople, mergeUserPeople, replaceUserPeopleIndex, summarizeUserPeople, updateUserPerson } from "./user-people-repository.js";
15
15
  import { cancelQueuedSessionInput, claimNextSessionInput, findSessionInput, finishSessionInputRun, getSessionInputById, getSessionInputState, insertSessionInput, listActiveSessionInputRuns, mutateQueuedSessionInput, recoverSessionInputState, setSessionInputStatus } from "./session-input-repository.js";
16
16
  import { buildDefaultSessionMetadata } from "./session-metadata.js";
@@ -36,4 +36,4 @@ import { appendConnectorExecutionAudit, claimConnectorWebhookDelivery, completeC
36
36
  import { getConnectorAccount, listConnectorAccounts, reconcileConnectorAccount, refreshConnectorAccountCurrent } from "./connector-account-repository.js";
37
37
  import { getConnectorSyncPolicy, getConnectorSyncPolicyForConnection, listConnectorSyncPolicies, upsertConnectorSyncPolicy } from "./connector-sync-policy-repository.js";
38
38
  import { getUserTrustPolicy, setUserTrustPolicy } from "./user-trust-repository.js";
39
- export { COMPOSER_INPUT_HISTORY_LIMIT, DatabaseSchemaMigrationGapError, DatabaseSchemaTooNewError, SCHEMA_META_SCHEMA_VERSION_KEY, XOPC_DB_BASELINE_SCHEMA_VERSION, XOPC_DB_FILENAME, XOPC_DB_SCHEMA_VERSION, acknowledgeHomeAttention, appendCompactionBoundaryIfUnchanged, appendComposerInputHistory, appendConnectorExecutionAudit, appendMemorySignal, appendMemoryTraceEvent, appendTranscriptEntry, applyPendingMigrations, attachMemoryEvidence, bindEndpointPrincipal, buildDefaultSessionMetadata, buildGlobalSessionStats, buildRelationshipPrompt, cancelQueuedSessionInput, claimConnectorWebhookDelivery, claimContextExtractionRun, claimKnowledgeSourceItems, claimNextConnectorLearningJob, claimNextSessionInput, classifyStoredRow, clearComposerInputHistory, closeTemporalAssertions, closeUnderstandingValidity, closeXopcDatabase, completeConnectorWebhookDelivery, completeKnowledgeSourceItemSynthesis, consumeConnectorApproval, consumeContextConsent, countKnowledgeSourceItems, countMemoryRecordsBySourceInstanceId, createCollaborationRule, createConnectorApproval, createContextEvidence, createEndpointPrincipal, createObjectLinkRecord, createTemporalAssertion, createUnderstanding, decideConnectorApproval, decideContextConsent, deleteCollaborationRule, deleteConnectorConnection, deleteConnectorInstallation, deleteKnowledgeSourceItems, deleteMemoryEvidenceForRecord, deleteMemoryRecord, deleteMemoryRecordsBySourceInstanceId, deleteNoteAgentContextRecord, deleteNoteRecord, deleteObjectLinkRecord, deleteSessionConfig, deleteSessionRecord, deleteUnderstanding, discoverSqlMigrations, enqueueConnectorLearningJob, ensureContextConsent, ensureSessionRecord, ensureXopcDatabaseSchema, estimateTokensFromMessages, extractFtsContent, findSessionInput, findSessionKeyBySessionId, finishContextConsolidationRun, finishContextExtractionRun, finishEndpointToolInvocationAudit, finishKnowledgeSyncRun, finishSessionInputRun, getActivityEventRecord, getCachedConnectorCatalogEntry, getCollaborationRule, getConnectorAccount, getConnectorApproval, getConnectorConnection, getConnectorInstallation, getConnectorSyncPolicy, getConnectorSyncPolicyForConnection, getContextConsolidationRun, getContextExtractionRun, getCurrentSessionId, getEndpointPrincipal, getGlobalSessionStats, getInteractionState, getKnowledgeConsumerWatermark, getKnowledgeSourceCursor, getKnowledgeSourceItem, getMemoryProviderState, getMemoryRecord, getMemoryTurnFeedback, getNoteAgentContextRecord, getNoteRecord, getRelationshipSettings, getSessionConfig, getSessionInputById, getSessionInputState, getSessionMetadata, getSessionPersistedLevels, getSessionTaskPlan, getSqliteDatabase, getTurnPersonalization, getUnderstanding, getUserPeopleIndexState, getUserPerson, getUserProfile, getUserTrustPolicy, getXopcDatabase, hasContextConsent, hasIndependentExtractionOutput, hasSessionConfig, hasUnresolvedMemoryConflict, incrementSessionStatsOnAppend, insertSessionInput, inspectSchemaMigrationStatus, isHomeAttentionAcknowledged, isProactiveSupportAllowed, isUnderstandingSuppressed, isXopcDatabaseOpen, linkContextObjects, linkUnderstandingEvidence, listActiveSessionInputRuns, listActivityRecords, listCachedConnectorCatalogEntries, listCollaborationRules, listCompactionBoundaries, listComposerInputHistory, listConnectorAccounts, listConnectorActionMetadata, listConnectorApprovals, listConnectorConnections, listConnectorExecutionAudit, listConnectorInstallations, listConnectorLearningJobs, listConnectorSyncPolicies, listContextConsolidationDecisions, listContextConsolidationRuns, listContextExtractionOutputs, listContextExtractionRuns, listContextObjectRelations, listEndpointPrincipals, listEndpointToolInvocationAudits, listKnowledgeSourceChanges, listKnowledgeSourceItems, listKnowledgeSyncRuns, listMemoryEvidence, listMemoryRecords, listMemorySignals, listMemoryTraceEvents, listNoteRecords, listObjectActivityRecords, listObjectLinkRecords, listProjectActivityRecords, listRegisteredMigrationTargets, listSessionMetadata, listSessionsByAgent, listTemporalAssertions, listUnderstandingEvidence, listUnderstandings, listUserPeople, loadCompactionSourceSnapshot, loadLlmMessagesForSession, loadTranscriptHistoryRowsForSession, loadTranscriptRows, loadTranscriptRowsForSession, markMemoryRecordsConflicted, mergeUserPeople, metadataToSessionInsert, mutateQueuedSessionInput, openXopcDatabase, paginateTranscriptMessages, patchSessionMetadata, pruneBoundedKnowledgeSourceItems, readSchemaVersion, readSchemaVersionForTest, reconcileConnectorAccount, recordActivityEvent, recordContextConsolidationDecision, recordContextFeedback, recordContextRun, recoverSessionInputState, recoverStaleConnectorLearningJobs, refreshConnectorAccountCurrent, rejectUnderstanding, releaseConnectorWebhookDelivery, replaceConnectorCatalogEntries, replaceLatestSessionTurnAndQueueInput, replaceTranscriptRows, replaceUserPeopleIndex, requireXopcDatabase, resetSessionRecord, resetXopcDatabaseSingletonForTest, resolveMigrationsDir, resolveSessionAgentId, resolveXopcDatabasePath, restoreBeforeCompactionBoundary, reviseCollaborationRule, reviseUnderstanding, revokeEndpointPrincipal, runSqliteWriteTransaction, searchActiveUnderstandings, searchMemoryRecords, searchSessionTranscript, sessionConfigRowToConfig, sessionRowToMetadata, setCollaborationRuleStatus, setConnectorLearningPaused, setInteractionState, setKnowledgeConsumerWatermark, setKnowledgeSourceCursor, setKnowledgeSourceItemSynthesisStatus, setMemoryProviderState, setMemoryRecordStatus, setMemoryTurnFeedback, setSessionConfig, setSessionInputStatus, setSessionTaskPlan, setUnderstandingStatus, setUserTrustPolicy, startContextConsolidationRun, startEndpointToolInvocationAudit, startKnowledgeSyncRun, summarizeMemoryRecallFeedback, summarizeUnderstandingFeedback, summarizeUserPeople, summarizeUserUnderstandingQuality, touchEndpointPrincipal, transcriptEntryRowToStoredRow, updateConnectorLearningJob, updateInteractionStateFromMessage, updateRelationshipSettings, updateSessionConfig, updateSessionStats, updateUserPerson, updateUserProfile, upsertConnectorActionMetadata, upsertConnectorCatalogEntry, upsertConnectorConnection, upsertConnectorInstallation, upsertConnectorSyncPolicy, upsertKnowledgeSourceItems, upsertMemoryRecord, upsertNoteAgentContextRecord, upsertNoteRecord, validateLatestSessionTurnTarget };
39
+ export { COMPOSER_INPUT_HISTORY_LIMIT, DatabaseSchemaMigrationGapError, DatabaseSchemaTooNewError, SCHEMA_META_SCHEMA_VERSION_KEY, XOPC_DB_BASELINE_SCHEMA_VERSION, XOPC_DB_FILENAME, XOPC_DB_SCHEMA_VERSION, acknowledgeHomeAttention, appendCompactionBoundaryIfUnchanged, appendComposerInputHistory, appendConnectorExecutionAudit, appendMemorySignal, appendMemoryTraceEvent, appendTranscriptEntry, applyPendingMigrations, attachMemoryEvidence, bindEndpointPrincipal, buildDefaultSessionMetadata, buildGlobalSessionStats, buildRelationshipPrompt, cancelQueuedSessionInput, claimConnectorWebhookDelivery, claimContextExtractionRun, claimKnowledgeSourceItems, claimNextConnectorLearningJob, claimNextSessionInput, classifyStoredRow, clearComposerInputHistory, closeTemporalAssertions, closeUnderstandingValidity, closeXopcDatabase, completeConnectorWebhookDelivery, completeKnowledgeSourceItemSynthesis, consumeConnectorApproval, consumeContextConsent, countKnowledgeSourceItems, countMemoryRecordsBySourceInstanceId, createCollaborationRule, createConnectorApproval, createContextEvidence, createEndpointPrincipal, createObjectLinkRecord, createTemporalAssertion, createUnderstanding, decideConnectorApproval, decideContextConsent, deleteCollaborationRule, deleteConnectorConnection, deleteConnectorInstallation, deleteKnowledgeSourceItems, deleteMemoryEvidenceForRecord, deleteMemoryRecord, deleteMemoryRecordsBySourceInstanceId, deleteNoteAgentContextRecord, deleteNoteRecord, deleteObjectLinkRecord, deleteSessionConfig, deleteSessionRecord, deleteUnderstanding, discoverSqlMigrations, enqueueConnectorLearningJob, ensureContextConsent, ensureSessionRecord, ensureXopcDatabaseSchema, estimateTokensFromMessages, extractFtsContent, findSessionInput, findSessionKeyBySessionId, finishContextConsolidationRun, finishContextExtractionRun, finishEndpointToolInvocationAudit, finishKnowledgeSyncRun, finishSessionInputRun, getActivityEventRecord, getCachedConnectorCatalogEntry, getCollaborationRule, getConnectorAccount, getConnectorApproval, getConnectorConnection, getConnectorInstallation, getConnectorSyncPolicy, getConnectorSyncPolicyForConnection, getContextConsolidationRun, getContextExtractionRun, getCurrentSessionId, getEndpointPrincipal, getGlobalSessionStats, getInteractionState, getKnowledgeConsumerWatermark, getKnowledgeSourceCursor, getKnowledgeSourceItem, getMemoryProviderState, getMemoryRecord, getMemoryTurnFeedback, getNoteAgentContextRecord, getNoteRecord, getRelationshipSettings, getSessionConfig, getSessionInputById, getSessionInputState, getSessionMetadata, getSessionPersistedLevels, getSessionTaskPlan, getSqliteDatabase, getTurnPersonalization, getUnderstanding, getUserPeopleIndexState, getUserPerson, getUserProfile, getUserTrustPolicy, getXopcDatabase, hasContextConsent, hasIndependentExtractionOutput, hasSessionConfig, hasUnresolvedMemoryConflict, incrementSessionStatsOnAppend, insertSessionInput, inspectSchemaMigrationStatus, isHomeAttentionAcknowledged, isProactiveSupportAllowed, isUnderstandingSuppressed, isXopcDatabaseOpen, linkContextObjects, linkUnderstandingEvidence, listActiveSessionInputRuns, listActivityRecords, listCachedConnectorCatalogEntries, listCollaborationRules, listCompactionBoundaries, listComposerInputHistory, listConnectorAccounts, listConnectorActionMetadata, listConnectorApprovals, listConnectorConnections, listConnectorExecutionAudit, listConnectorInstallations, listConnectorLearningJobs, listConnectorSyncPolicies, listContextConsolidationDecisions, listContextConsolidationRuns, listContextExtractionOutputs, listContextExtractionRuns, listContextObjectRelations, listEndpointPrincipals, listEndpointToolInvocationAudits, listKnowledgeSourceChanges, listKnowledgeSourceItems, listKnowledgeSyncRuns, listMemoryEvidence, listMemoryRecords, listMemorySignals, listMemoryTraceEvents, listNoteRecords, listObjectActivityRecords, listObjectLinkRecords, listProjectActivityRecords, listRegisteredMigrationTargets, listSessionMetadata, listSessionsByAgent, listTemporalAssertions, listUnderstandingEvidence, listUnderstandingStatusEvents, listUnderstandings, listUserPeople, loadCompactionSourceSnapshot, loadLlmMessagesForSession, loadTranscriptHistoryRowsForSession, loadTranscriptRows, loadTranscriptRowsForSession, markMemoryRecordsConflicted, mergeUserPeople, metadataToSessionInsert, mutateQueuedSessionInput, openXopcDatabase, paginateTranscriptMessages, patchSessionMetadata, pruneBoundedKnowledgeSourceItems, readSchemaVersion, readSchemaVersionForTest, reconcileConnectorAccount, recordActivityEvent, recordContextConsolidationDecision, recordContextFeedback, recordContextRun, recoverSessionInputState, recoverStaleConnectorLearningJobs, refreshConnectorAccountCurrent, rejectUnderstanding, releaseConnectorWebhookDelivery, replaceConnectorCatalogEntries, replaceLatestSessionTurnAndQueueInput, replaceTranscriptRows, replaceUserPeopleIndex, requireXopcDatabase, resetSessionRecord, resetXopcDatabaseSingletonForTest, resolveMigrationsDir, resolveSessionAgentId, resolveXopcDatabasePath, restoreBeforeCompactionBoundary, reviseCollaborationRule, reviseUnderstanding, revokeEndpointPrincipal, runSqliteWriteTransaction, searchActiveUnderstandings, searchMemoryRecords, searchSessionTranscript, sessionConfigRowToConfig, sessionRowToMetadata, setCollaborationRuleStatus, setConnectorLearningPaused, setInteractionState, setKnowledgeConsumerWatermark, setKnowledgeSourceCursor, setKnowledgeSourceItemSynthesisStatus, setMemoryProviderState, setMemoryRecordStatus, setMemoryTurnFeedback, setSessionConfig, setSessionInputStatus, setSessionTaskPlan, setUnderstandingStatus, setUserTrustPolicy, startContextConsolidationRun, startEndpointToolInvocationAudit, startKnowledgeSyncRun, summarizeMemoryRecallFeedback, summarizeUnderstandingFeedback, summarizeUserPeople, summarizeUserUnderstandingQuality, touchEndpointPrincipal, transcriptEntryRowToStoredRow, updateConnectorLearningJob, updateInteractionStateFromMessage, updateRelationshipSettings, updateSessionConfig, updateSessionStats, updateUserPerson, updateUserProfile, upsertConnectorActionMetadata, upsertConnectorCatalogEntry, upsertConnectorConnection, upsertConnectorInstallation, upsertConnectorSyncPolicy, upsertKnowledgeSourceItems, upsertMemoryRecord, upsertNoteAgentContextRecord, upsertNoteRecord, validateLatestSessionTurnTarget };
@@ -0,0 +1,71 @@
1
+ CREATE TABLE understanding_status_events (
2
+ event_id TEXT PRIMARY KEY,
3
+ understanding_id TEXT NOT NULL REFERENCES user_understandings(understanding_id) ON DELETE CASCADE,
4
+ from_status TEXT CHECK (from_status IS NULL OR from_status IN (
5
+ 'candidate', 'active', 'needs_review', 'stale', 'archived', 'rejected'
6
+ )),
7
+ to_status TEXT NOT NULL CHECK (to_status IN (
8
+ 'candidate', 'active', 'needs_review', 'stale', 'archived', 'rejected'
9
+ )),
10
+ actor_type TEXT NOT NULL CHECK (actor_type IN ('user', 'runtime', 'migration')),
11
+ source TEXT NOT NULL,
12
+ created_at INTEGER NOT NULL
13
+ );
14
+
15
+ CREATE INDEX idx_understanding_status_events_item
16
+ ON understanding_status_events(understanding_id, created_at DESC);
17
+
18
+ INSERT INTO understanding_status_events (
19
+ event_id, understanding_id, from_status, to_status, actor_type, source, created_at
20
+ )
21
+ SELECT
22
+ lower(hex(randomblob(16))), understanding_id, NULL, status, 'migration', 'status-audit-baseline', updated_at
23
+ FROM user_understandings;
24
+
25
+ INSERT INTO understanding_status_events (
26
+ event_id, understanding_id, from_status, to_status, actor_type, source, created_at
27
+ )
28
+ SELECT
29
+ lower(hex(randomblob(16))), u.understanding_id, u.status, 'needs_review', 'migration',
30
+ 'repair-untrusted-portrait-v1', CAST(strftime('%s', 'now') AS INTEGER) * 1000
31
+ FROM user_understandings u
32
+ JOIN user_understanding_versions v ON v.version_id = u.current_version_id
33
+ WHERE u.status = 'active'
34
+ AND (
35
+ u.canonical_key LIKE 'connected:%'
36
+ OR u.canonical_key LIKE 'connected-semantic:%'
37
+ OR (u.canonical_key LIKE 'work-discovery:%' AND v.created_by <> 'user')
38
+ OR EXISTS (
39
+ SELECT 1
40
+ FROM understanding_evidence_links l
41
+ JOIN context_evidence e ON e.evidence_id = l.evidence_id
42
+ WHERE l.version_id = u.current_version_id
43
+ AND e.extractor_id IN ('connector-structural', 'connector-semantic', 'explicit-command')
44
+ )
45
+ OR (u.kind = 'task_lesson' AND length(v.statement) > 240)
46
+ OR (u.kind = 'boundary' AND (
47
+ v.statement LIKE '%不要再问%'
48
+ OR v.statement LIKE '%直接执行%'
49
+ OR lower(v.statement) LIKE '%do not ask%'
50
+ OR lower(v.statement) LIKE '%just do it%'
51
+ ))
52
+ );
53
+
54
+ UPDATE user_understandings
55
+ SET status = 'needs_review',
56
+ updated_at = CAST(strftime('%s', 'now') AS INTEGER) * 1000
57
+ WHERE understanding_id IN (
58
+ SELECT understanding_id
59
+ FROM understanding_status_events
60
+ WHERE source = 'repair-untrusted-portrait-v1'
61
+ );
62
+
63
+ UPDATE context_temporal_assertions
64
+ SET status = 'candidate',
65
+ updated_at = CAST(strftime('%s', 'now') AS INTEGER) * 1000
66
+ WHERE object_type = 'understanding'
67
+ AND object_id IN (
68
+ SELECT understanding_id
69
+ FROM understanding_status_events
70
+ WHERE source = 'repair-untrusted-portrait-v1'
71
+ );
@@ -3,7 +3,7 @@ import type { ApplyMigrationsOptions } from './types.js';
3
3
  /** Baseline schema version applied from schema.sql on first open. */
4
4
  export declare const XOPC_DB_BASELINE_SCHEMA_VERSION = 11;
5
5
  /** Latest schema version this release supports (increment when adding migrations). */
6
- export declare const XOPC_DB_SCHEMA_VERSION = 136;
6
+ export declare const XOPC_DB_SCHEMA_VERSION = 137;
7
7
  export declare function resolveMigrationsDir(override?: string): string;
8
8
  /**
9
9
  * Apply sequential SQL migrations from (currentVersion + 1) through targetVersion.
@@ -12,7 +12,7 @@ const log = createLogger("Sqlite:Migrations");
12
12
  /** Baseline schema version applied from schema.sql on first open. */
13
13
  const XOPC_DB_BASELINE_SCHEMA_VERSION = 11;
14
14
  /** Latest schema version this release supports (increment when adding migrations). */
15
- const XOPC_DB_SCHEMA_VERSION = 136;
15
+ const XOPC_DB_SCHEMA_VERSION = 137;
16
16
  const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
17
17
  function backupBeforeTaskCutover(db, databasePath) {
18
18
  db.exec("PRAGMA wal_checkpoint(FULL)");
@@ -57,7 +57,7 @@ function applySingleMigration(db, migration) {
57
57
  * Each step runs in its own transaction and updates schema_meta on success.
58
58
  */
59
59
  function applyPendingMigrations(db, options = {}) {
60
- const targetVersion = options.targetVersion ?? 136;
60
+ const targetVersion = options.targetVersion ?? 137;
61
61
  let currentVersion = readSchemaVersion(db);
62
62
  if (currentVersion > targetVersion) throw new DatabaseSchemaTooNewError(currentVersion, targetVersion);
63
63
  if (currentVersion >= targetVersion) return currentVersion;
@@ -94,7 +94,7 @@ function applyPendingMigrations(db, options = {}) {
94
94
  }
95
95
  /** Inspect schema version without mutating the database. */
96
96
  function inspectSchemaMigrationStatus(db, options = {}) {
97
- const appVersion = options.targetVersion ?? 136;
97
+ const appVersion = options.targetVersion ?? 137;
98
98
  const dbVersion = readSchemaVersion(db);
99
99
  if (dbVersion > appVersion) return {
100
100
  dbVersion,
@@ -19,7 +19,7 @@ const log = createLogger('Sqlite:Migrations');
19
19
  export const XOPC_DB_BASELINE_SCHEMA_VERSION = 11;
20
20
 
21
21
  /** Latest schema version this release supports (increment when adding migrations). */
22
- export const XOPC_DB_SCHEMA_VERSION = 136;
22
+ export const XOPC_DB_SCHEMA_VERSION = 137;
23
23
 
24
24
  const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
25
25
 
@@ -32,7 +32,7 @@ function ensureXopcDatabaseSchema(db, options = {}) {
32
32
  currentVersion = 11;
33
33
  }
34
34
  applyPendingMigrations(db, {
35
- targetVersion: 136,
35
+ targetVersion: 137,
36
36
  databasePath: options.databasePath
37
37
  });
38
38
  }
@@ -1,4 +1,13 @@
1
1
  import { type CollaborationRule, type ContextEvidence, type PersonalizationItem, type UnderstandingStatus, type UserContextScope, type UserProfile, type UserUnderstanding } from '../../user-context/domain.js';
2
+ export type UnderstandingStatusEvent = {
3
+ id: string;
4
+ understandingId: string;
5
+ fromStatus?: UnderstandingStatus;
6
+ toStatus: UnderstandingStatus;
7
+ actorType: 'user' | 'runtime' | 'migration';
8
+ source: string;
9
+ createdAt: number;
10
+ };
2
11
  export declare function getUserProfile(principalId?: string): UserProfile;
3
12
  export declare function updateUserProfile(patch: Partial<Pick<UserProfile, 'callName' | 'role' | 'primaryGoal' | 'pronouns' | 'timezone' | 'locale' | 'accessibility'>>, principalId?: string): UserProfile;
4
13
  export type CreateUnderstandingInput = Omit<UserUnderstanding, 'id' | 'versionId' | 'createdAt' | 'updatedAt' | 'statement' | 'payload'> & {
@@ -21,12 +30,15 @@ export declare function reviseUnderstanding(id: string, statement: string, optio
21
30
  confidence?: number;
22
31
  changeReason: string;
23
32
  }): UserUnderstanding;
24
- export declare function setUnderstandingStatus(id: string, status: UnderstandingStatus, confirmation?: {
25
- explicitness: UserUnderstanding['explicitness'];
26
- confidence: number;
33
+ export declare function setUnderstandingStatus(id: string, status: UnderstandingStatus, options?: {
34
+ explicitness?: UserUnderstanding['explicitness'];
35
+ confidence?: number;
36
+ actorType?: UnderstandingStatusEvent['actorType'];
37
+ source?: string;
27
38
  }): UserUnderstanding;
28
39
  export declare function closeUnderstandingValidity(id: string, validTo?: number): UserUnderstanding;
29
- export declare function rejectUnderstanding(id: string, reason: string): UserUnderstanding;
40
+ export declare function rejectUnderstanding(id: string, reason: string, actorType?: UnderstandingStatusEvent['actorType']): UserUnderstanding;
41
+ export declare function listUnderstandingStatusEvents(id: string): UnderstandingStatusEvent[];
30
42
  export declare function deleteUnderstanding(id: string): boolean;
31
43
  export declare function isUnderstandingSuppressed(canonicalKey: string, scope: UserContextScope, principalId?: string): boolean;
32
44
  export declare function createCollaborationRule(input: Pick<CollaborationRule, 'category' | 'priority' | 'scope' | 'conditions' | 'statement'>, principalId?: string): CollaborationRule;