@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
@@ -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 = "";
@@ -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 {
@@ -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;
@@ -4,6 +4,11 @@ import { retrievalQueryAuditValue } from "../../retrieval/audit.js";
4
4
  import { buildFts5SearchQuery, fts5RankToScore } from "./fts.js";
5
5
  import { createHash, randomUUID } from "node:crypto";
6
6
  //#region src/storage/sqlite/user-context-repository.ts
7
+ function insertUnderstandingStatusEvent(db, input) {
8
+ db.prepare(`INSERT INTO understanding_status_events (
9
+ event_id, understanding_id, from_status, to_status, actor_type, source, created_at
10
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)`).run(randomUUID(), input.understandingId, input.fromStatus ?? null, input.toStatus, input.actorType, input.source, input.createdAt);
11
+ }
7
12
  function evidenceFromRow(row) {
8
13
  return {
9
14
  id: row.evidence_id,
@@ -144,6 +149,13 @@ function createUnderstanding(input, principalId = USER_CONTEXT_PRINCIPAL_ID) {
144
149
  version_id, understanding_id, statement, payload_json, created_by, change_reason, created_at
145
150
  ) VALUES (?, ?, ?, ?, ?, ?, ?)`).run(versionId, id, input.statement.trim(), JSON.stringify(input.payload ?? {}), input.createdBy, input.changeReason, now);
146
151
  db.prepare("INSERT INTO user_understanding_fts (statement, understanding_id, version_id) VALUES (?, ?, ?)").run(input.statement.trim(), id, versionId);
152
+ insertUnderstandingStatusEvent(db, {
153
+ understandingId: id,
154
+ toStatus: input.status,
155
+ actorType: input.createdBy === "user" ? "user" : "runtime",
156
+ source: `create:${input.changeReason}`,
157
+ createdAt: now
158
+ });
147
159
  });
148
160
  return getUnderstanding(id);
149
161
  }
@@ -197,17 +209,29 @@ function reviseUnderstanding(id, statement, options) {
197
209
  });
198
210
  return getUnderstanding(id);
199
211
  }
200
- function setUnderstandingStatus(id, status, confirmation) {
212
+ function setUnderstandingStatus(id, status, options) {
213
+ const current = getUnderstanding(id);
214
+ if (!current) throw new Error(`User understanding not found: ${id}`);
201
215
  const now = Date.now();
202
- getSqliteDatabase().prepare(`UPDATE user_understandings
203
- SET status = ?,
204
- explicitness = COALESCE(?, explicitness),
205
- confidence = COALESCE(?, confidence),
206
- updated_at = ?
207
- WHERE understanding_id = ?`).run(status, confirmation?.explicitness ?? null, confirmation?.confidence ?? null, now, id);
208
- const assertionStatus = status === "active" ? "active" : status === "archived" ? "closed" : status === "rejected" ? "rejected" : "candidate";
209
- getSqliteDatabase().prepare(`UPDATE context_temporal_assertions
210
- SET status = ?, updated_at = ? WHERE object_type = 'understanding' AND object_id = ?`).run(assertionStatus, now, id);
216
+ runSqliteWriteTransaction((db) => {
217
+ db.prepare(`UPDATE user_understandings
218
+ SET status = ?,
219
+ explicitness = COALESCE(?, explicitness),
220
+ confidence = COALESCE(?, confidence),
221
+ updated_at = ?
222
+ WHERE understanding_id = ?`).run(status, options?.explicitness ?? null, options?.confidence ?? null, now, id);
223
+ const assertionStatus = status === "active" ? "active" : status === "archived" ? "closed" : status === "rejected" ? "rejected" : "candidate";
224
+ db.prepare(`UPDATE context_temporal_assertions
225
+ SET status = ?, updated_at = ? WHERE object_type = 'understanding' AND object_id = ?`).run(assertionStatus, now, id);
226
+ if (current.status !== status) insertUnderstandingStatusEvent(db, {
227
+ understandingId: id,
228
+ fromStatus: current.status,
229
+ toStatus: status,
230
+ actorType: options?.actorType ?? "runtime",
231
+ source: options?.source ?? "repository-status-change",
232
+ createdAt: now
233
+ });
234
+ });
211
235
  const result = getUnderstanding(id);
212
236
  if (!result) throw new Error(`User understanding not found: ${id}`);
213
237
  return result;
@@ -219,12 +243,20 @@ function closeUnderstandingValidity(id, validTo = Date.now()) {
219
243
  if (!result) throw new Error(`User understanding not found: ${id}`);
220
244
  return result;
221
245
  }
222
- function rejectUnderstanding(id, reason) {
246
+ function rejectUnderstanding(id, reason, actorType = "runtime") {
223
247
  const current = getUnderstanding(id);
224
248
  if (!current) throw new Error(`User understanding not found: ${id}`);
225
249
  const now = Date.now();
226
250
  runSqliteWriteTransaction((db) => {
227
251
  db.prepare("UPDATE user_understandings SET status = 'rejected', updated_at = ? WHERE understanding_id = ?").run(now, id);
252
+ if (current.status !== "rejected") insertUnderstandingStatusEvent(db, {
253
+ understandingId: id,
254
+ fromStatus: current.status,
255
+ toStatus: "rejected",
256
+ actorType,
257
+ source: reason,
258
+ createdAt: now
259
+ });
228
260
  db.prepare(`INSERT INTO context_suppressions (
229
261
  suppression_id, principal_id, canonical_key, scope_type, scope_id, reason, expires_at, created_at
230
262
  ) VALUES (?, ?, ?, ?, ?, ?, NULL, ?)
@@ -232,6 +264,18 @@ function rejectUnderstanding(id, reason) {
232
264
  });
233
265
  return getUnderstanding(id);
234
266
  }
267
+ function listUnderstandingStatusEvents(id) {
268
+ return getSqliteDatabase().prepare(`SELECT * FROM understanding_status_events
269
+ WHERE understanding_id = ? ORDER BY created_at DESC, rowid DESC`).all(id).map((row) => ({
270
+ id: row.event_id,
271
+ understandingId: row.understanding_id,
272
+ ...row.from_status ? { fromStatus: row.from_status } : {},
273
+ toStatus: row.to_status,
274
+ actorType: row.actor_type,
275
+ source: row.source,
276
+ createdAt: row.created_at
277
+ }));
278
+ }
235
279
  function deleteUnderstanding(id) {
236
280
  return runSqliteWriteTransaction((db) => {
237
281
  db.prepare("DELETE FROM user_understanding_fts WHERE understanding_id = ?").run(id);
@@ -442,4 +486,4 @@ function decideContextConsent(id, decision) {
442
486
  return Number(result.changes) > 0;
443
487
  }
444
488
  //#endregion
445
- export { 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 };
489
+ export { 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 };
@@ -96,6 +96,10 @@ export declare const UserMemoryConfigSchema: z.ZodDefault<z.ZodObject<{
96
96
  }, z.core.$strict>>;
97
97
  export declare const UserUnderstandingConfigSchema: z.ZodDefault<z.ZodObject<{
98
98
  enabled: z.ZodDefault<z.ZodBoolean>;
99
+ processingPolicy: z.ZodDefault<z.ZodEnum<{
100
+ local_only: "local_only";
101
+ remote_allowed: "remote_allowed";
102
+ }>>;
99
103
  adaptiveCadence: z.ZodDefault<z.ZodBoolean>;
100
104
  reviewIntervalTurns: z.ZodDefault<z.ZodNumber>;
101
105
  maxHistoryMessages: z.ZodDefault<z.ZodNumber>;
@@ -204,6 +208,10 @@ export declare const UserContextConfigSchema: z.ZodDefault<z.ZodObject<{
204
208
  }, z.core.$strict>>;
205
209
  understanding: z.ZodDefault<z.ZodObject<{
206
210
  enabled: z.ZodDefault<z.ZodBoolean>;
211
+ processingPolicy: z.ZodDefault<z.ZodEnum<{
212
+ local_only: "local_only";
213
+ remote_allowed: "remote_allowed";
214
+ }>>;
207
215
  adaptiveCadence: z.ZodDefault<z.ZodBoolean>;
208
216
  reviewIntervalTurns: z.ZodDefault<z.ZodNumber>;
209
217
  maxHistoryMessages: z.ZodDefault<z.ZodNumber>;
@@ -91,12 +91,14 @@ var init_config = __esmMin((() => {
91
91
  });
92
92
  UserUnderstandingConfigSchema = z.object({
93
93
  enabled: z.boolean().default(true),
94
+ processingPolicy: z.enum(["local_only", "remote_allowed"]).default("remote_allowed"),
94
95
  adaptiveCadence: z.boolean().default(true),
95
96
  reviewIntervalTurns: z.number().int().min(1).max(1e3).default(10),
96
97
  maxHistoryMessages: z.number().int().min(1).max(200).default(80),
97
98
  maxDurationMs: z.number().int().min(1e3).max(6e5).default(12e4)
98
99
  }).strict().default({
99
100
  enabled: true,
101
+ processingPolicy: "remote_allowed",
100
102
  adaptiveCadence: true,
101
103
  reviewIntervalTurns: 10,
102
104
  maxHistoryMessages: 80,
@@ -161,6 +163,7 @@ var init_config = __esmMin((() => {
161
163
  },
162
164
  understanding: {
163
165
  enabled: true,
166
+ processingPolicy: "remote_allowed",
164
167
  adaptiveCadence: true,
165
168
  reviewIntervalTurns: 10,
166
169
  maxHistoryMessages: 80,
@@ -97,7 +97,10 @@ async function runContextConsolidation(input) {
97
97
  const evidenceCount = distinctEvidenceCount(understanding.id, "supports");
98
98
  const contradictionCount = distinctEvidenceCount(understanding.id, "contradicts");
99
99
  if (understanding.validTo != null && understanding.validTo <= now || understanding.expiresAt != null && understanding.expiresAt <= now) {
100
- setUnderstandingStatus(understanding.id, "stale");
100
+ setUnderstandingStatus(understanding.id, "stale", {
101
+ actorType: "runtime",
102
+ source: "consolidation-expired"
103
+ });
101
104
  recordContextConsolidationDecision({
102
105
  runId: run.runId,
103
106
  understandingId: understanding.id,
@@ -110,7 +113,10 @@ async function runContextConsolidation(input) {
110
113
  continue;
111
114
  }
112
115
  if (contradictionCount > 0) {
113
- setUnderstandingStatus(understanding.id, "needs_review");
116
+ setUnderstandingStatus(understanding.id, "needs_review", {
117
+ actorType: "runtime",
118
+ source: "consolidation-contradiction"
119
+ });
114
120
  recordContextConsolidationDecision({
115
121
  runId: run.runId,
116
122
  understandingId: understanding.id,
@@ -123,7 +129,10 @@ async function runContextConsolidation(input) {
123
129
  continue;
124
130
  }
125
131
  if (understanding.status === "active" && understanding.reviewAt != null && understanding.reviewAt <= now) {
126
- setUnderstandingStatus(understanding.id, "needs_review");
132
+ setUnderstandingStatus(understanding.id, "needs_review", {
133
+ actorType: "runtime",
134
+ source: "consolidation-review-due"
135
+ });
127
136
  recordContextConsolidationDecision({
128
137
  runId: run.runId,
129
138
  understandingId: understanding.id,
@@ -136,7 +145,10 @@ async function runContextConsolidation(input) {
136
145
  continue;
137
146
  }
138
147
  if (understanding.status === "candidate" && evidenceCount >= resolved.minEvidenceSources) {
139
- setUnderstandingStatus(understanding.id, "needs_review");
148
+ setUnderstandingStatus(understanding.id, "needs_review", {
149
+ actorType: "runtime",
150
+ source: "consolidation-evidence-threshold"
151
+ });
140
152
  recordContextConsolidationDecision({
141
153
  runId: run.runId,
142
154
  understandingId: understanding.id,
@@ -0,0 +1,22 @@
1
+ import type { Config } from '../../config/schema.js';
2
+ import type { MemoryManager } from '../../agent/memory/manager.js';
3
+ import type { UnderstandingReviewResult } from '../../agent/memory/understanding/types.js';
4
+ import { type ExtractorId } from './registry.js';
5
+ import type { SemanticEvidence, SemanticUnderstandingInterpretation } from './semantic.js';
6
+ export type UnderstandingEvidenceMessage = SemanticEvidence & {
7
+ createdAt: number;
8
+ message: unknown;
9
+ };
10
+ export declare function emptyUnderstandingReview(): UnderstandingReviewResult;
11
+ export declare function executeUnderstandingInterpretation(params: {
12
+ interpretation: SemanticUnderstandingInterpretation;
13
+ evidence: UnderstandingEvidenceMessage[];
14
+ extractionRunId: string;
15
+ extractorId: ExtractorId;
16
+ sessionKey: string;
17
+ turnId?: string;
18
+ memoryManager: MemoryManager;
19
+ getConfig: () => Config | undefined;
20
+ reviewSource: 'turn' | 'background';
21
+ processingPolicy: 'local_only' | 'remote_allowed';
22
+ }): Promise<UnderstandingReviewResult>;