fuli-context 0.20.1 → 0.21.0-beta.2

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 (262) hide show
  1. package/dist/web/assets/{AboutPage-CjDenGS_.js → AboutPage-D0dTwKq8.js} +1 -1
  2. package/dist/web/assets/{AgentName-DdlJlpT3.js → AgentName-n4oqQUwE.js} +1 -1
  3. package/dist/web/assets/{AgentProfilePage-Cx_Uf5Vf.js → AgentProfilePage-DH54S93r.js} +1 -1
  4. package/dist/web/assets/{AgentsDirectoryPage-DylT-GSW.js → AgentsDirectoryPage-xwIRrNb8.js} +1 -1
  5. package/dist/web/assets/{BackLink-D7oAvDG5.js → BackLink-nM3e40IT.js} +1 -1
  6. package/dist/web/assets/{BoardMoveMenu-B0pA7LLx.js → BoardMoveMenu-Cxgkbwkl.js} +1 -1
  7. package/dist/web/assets/{CaptureChangePage-DEuqPb14.js → CaptureChangePage-DWdz9dEk.js} +1 -1
  8. package/dist/web/assets/{Card-BZFLZ_2I.js → Card-89NKHANE.js} +1 -1
  9. package/dist/web/assets/{CardHeader-C_c0keQn.js → CardHeader-9MwjWRxl.js} +1 -1
  10. package/dist/web/assets/{CardTitle-yXOhV577.js → CardTitle-BAhmXjAK.js} +1 -1
  11. package/dist/web/assets/{ConnectionsPage-DlnHdtwn.js → ConnectionsPage-Yf4UvjDT.js} +1 -1
  12. package/dist/web/assets/{CreateProjectDialog-BVJqWdlT.js → CreateProjectDialog-crpLTyDf.js} +1 -1
  13. package/dist/web/assets/{DataFormatPage-BdcjcyhZ.js → DataFormatPage-BPuUH0PG.js} +1 -1
  14. package/dist/web/assets/{DialogFooter-DYawfDCD.js → DialogFooter-D9A9hRP4.js} +1 -1
  15. package/dist/web/assets/{EmployeeRecruitDialog-CB4ARFkM.js → EmployeeRecruitDialog-DeB0XHeM.js} +1 -1
  16. package/dist/web/assets/EmployeeWorkbenchPage-0oK2RfIh.js +3 -0
  17. package/dist/web/assets/{EmployeeWorkbenchPage-BenZP7De.css → EmployeeWorkbenchPage-CMutwFBC.css} +1 -1
  18. package/dist/web/assets/{GrowthLoading-smW3-Gfp.js → GrowthLoading-Cs9brXcN.js} +1 -1
  19. package/dist/web/assets/{InboxPage-Crn1UU7s.js → InboxPage-CTQ425Ez.js} +1 -1
  20. package/dist/web/assets/{Input-F1oftPWh.js → Input-DGf4juEs.js} +1 -1
  21. package/dist/web/assets/{KnowledgeEditDialog-VdQwbX4E.js → KnowledgeEditDialog-Ccgj30Wu.js} +1 -1
  22. package/dist/web/assets/{KnowledgeHardDeleteSection-CXRmNnZF.js → KnowledgeHardDeleteSection-CSnqisUv.js} +1 -1
  23. package/dist/web/assets/{KnowledgeItemEditPage-CQo3TbCJ.js → KnowledgeItemEditPage-C0Y2DsHz.js} +1 -1
  24. package/dist/web/assets/{KnowledgeItemSummaryCard-Dd2McM-d.js → KnowledgeItemSummaryCard-BRvaf4Fw.js} +1 -1
  25. package/dist/web/assets/{KnowledgeOrganizerPage-BVgAyu6U.js → KnowledgeOrganizerPage-CRC3mk0j.js} +1 -1
  26. package/dist/web/assets/KnowledgePage-NsKFUWth.js +1 -0
  27. package/dist/web/assets/{KnowledgePeek-BNBkh1ey.js → KnowledgePeek-Bc0bqyZp.js} +1 -1
  28. package/dist/web/assets/{KnowledgeTurnReceiptPage-Ckw_olrt.js → KnowledgeTurnReceiptPage-Dl0KeFDe.js} +1 -1
  29. package/dist/web/assets/{KnowledgeWorkspace-pH2tAFld.js → KnowledgeWorkspace-BGlODG7G.js} +1 -1
  30. package/dist/web/assets/{Label-yDCtlpkb.js → Label-CafdTnDF.js} +1 -1
  31. package/dist/web/assets/ModelSettingsPage-Bz1tMXtW.js +1 -0
  32. package/dist/web/assets/ModelSettingsPage-DJuEaw6p.css +1 -0
  33. package/dist/web/assets/{NotFoundPage-8gVVukRR.js → NotFoundPage-TfZ2eoA2.js} +1 -1
  34. package/dist/web/assets/{OccupationsPage-PNoqE21Y.js → OccupationsPage-CnSp6362.js} +1 -1
  35. package/dist/web/assets/{OverviewPage-DiwYSnhh.js → OverviewPage-D5W-DhOz.js} +2 -2
  36. package/dist/web/assets/{PersonalProfilePage-C_v2BFee.js → PersonalProfilePage-CndOcRQ6.js} +1 -1
  37. package/dist/web/assets/{PersonalProjectsPage-DGRV8cM5.js → PersonalProjectsPage-CXBOwEqC.js} +1 -1
  38. package/dist/web/assets/{PopperContent-5zqbtnYr.js → PopperContent-BXbztFFi.js} +1 -1
  39. package/dist/web/assets/{Presence-BYfYJNMD.js → Presence-BLar6FCs.js} +1 -1
  40. package/dist/web/assets/{ProjectAgentDetailPage-BQ9ffaCX.js → ProjectAgentDetailPage-SmZ2NYTw.js} +1 -1
  41. package/dist/web/assets/{ProjectAgentDialog-BGckQDTq.js → ProjectAgentDialog-Bg0V3Zr2.js} +1 -1
  42. package/dist/web/assets/{ProjectAgentFirstTask-DrSd3nR-.js → ProjectAgentFirstTask-CbOWaP7Q.js} +1 -1
  43. package/dist/web/assets/{ProjectAgentsPage-U4Om3EPu.js → ProjectAgentsPage-Y6qCYRZj.js} +1 -1
  44. package/dist/web/assets/{ProjectScopePicker-D0oxbwOd.js → ProjectScopePicker-ClDUoUHW.js} +1 -1
  45. package/dist/web/assets/{PublicProjectsPage-CvkQ3E8I.js → PublicProjectsPage-C63vW9UZ.js} +1 -1
  46. package/dist/web/assets/{RadioGroupItem-CBpbQlHx.js → RadioGroupItem-tL_2upmD.js} +1 -1
  47. package/dist/web/assets/{RoundtablesPage-BEUaKOjI.js → RoundtablesPage-2Akxagrm.js} +1 -1
  48. package/dist/web/assets/{RovingFocusGroup-X9U-ufYr.js → RovingFocusGroup-D5mf9s6I.js} +1 -1
  49. package/dist/web/assets/{RovingFocusItem-_uA_OCLT.js → RovingFocusItem-DAumq9xD.js} +1 -1
  50. package/dist/web/assets/{SessionMigrationPage-WVFSDcUO.js → SessionMigrationPage-B5r2PWCF.js} +1 -1
  51. package/dist/web/assets/{SessionRecordsPage-Bs2eLXEi.js → SessionRecordsPage-DIc2GoCQ.js} +1 -1
  52. package/dist/web/assets/{SettingsPage-DlIwICIz.js → SettingsPage-BAxKpnBx.js} +1 -1
  53. package/dist/web/assets/{SharedJefaReportPage-B_rreEep.js → SharedJefaReportPage-B54qEdIV.js} +1 -1
  54. package/dist/web/assets/{TabsContent-8pXwYJPz.js → TabsContent-DZQE2Iq8.js} +1 -1
  55. package/dist/web/assets/{TabsTrigger-Cd6SI2yI.js → TabsTrigger-CHnq6mkI.js} +1 -1
  56. package/dist/web/assets/{TagVocabularyPage-BQiuKG-4.js → TagVocabularyPage-BIsHYk2i.js} +1 -1
  57. package/dist/web/assets/{TaskExecutionPlan-CupxJeyo.js → TaskExecutionPlan-IYG_JeuT.js} +1 -1
  58. package/dist/web/assets/{TaskSchedulesPage-zYQs7s6T.js → TaskSchedulesPage-Cxjqc8XQ.js} +1 -1
  59. package/dist/web/assets/{Teleport-BZX1Eb7R.js → Teleport-BKN3dSMk.js} +1 -1
  60. package/dist/web/assets/{TextField-CielK4l3.js → TextField-DoKtn--E.js} +1 -1
  61. package/dist/web/assets/{UiDialog-BSDblUpR.js → UiDialog-7pnZ-eQA.js} +1 -1
  62. package/dist/web/assets/{UiDisclosure-DLmVwmy1.js → UiDisclosure-COV4NwHI.js} +1 -1
  63. package/dist/web/assets/{UiIcon-B8eZeuGI.js → UiIcon-BADOYtHM.js} +1 -1
  64. package/dist/web/assets/{UiIconButton-e754Tmnq.js → UiIconButton-CkBP6pnX.js} +1 -1
  65. package/dist/web/assets/{UiSegmented-D1HD-qin.js → UiSegmented-FwOnE2IZ.js} +1 -1
  66. package/dist/web/assets/{UiSelect-CbkTsi2e.js → UiSelect-BIhr03Gk.js} +1 -1
  67. package/dist/web/assets/{UiToggle-Dz93aXFK.js → UiToggle-bpyawyIe.js} +1 -1
  68. package/dist/web/assets/{UiWeight-CUvyApSB.js → UiWeight-TyBehy3K.js} +1 -1
  69. package/dist/web/assets/{UnassignedConversationsPanel-xY7gsFot.js → UnassignedConversationsPanel-B4PqImRi.js} +1 -1
  70. package/dist/web/assets/{VirtualDirectoryList-Dv6PwLjU.js → VirtualDirectoryList-DNQP6X8j.js} +1 -1
  71. package/dist/web/assets/{Workbench3D--4N_uKzp.js → Workbench3D-DNwgymIE.js} +1 -1
  72. package/dist/web/assets/{WritingTastePage-B7KojA4r.js → WritingTastePage-D-ELo7mh.js} +1 -1
  73. package/dist/web/assets/{_plugin-vue_export-helper-BmfQlfI8.js → _plugin-vue_export-helper-RegzAV-H.js} +1 -1
  74. package/dist/web/assets/{accordion-gXElbGP_.js → accordion-DpqAdXTB.js} +1 -1
  75. package/dist/web/assets/{agent-occupation-ChN-1QjC.js → agent-occupation-Ba5Fl0ys.js} +1 -1
  76. package/dist/web/assets/{agent-pins-Chh_rdBi.js → agent-pins-Bb7-1Uoz.js} +1 -1
  77. package/dist/web/assets/{agent-profile.css_vue_type_style_index_0_src_true_lang-DWlz7UoN.js → agent-profile.css_vue_type_style_index_0_src_true_lang-wT8gjVyZ.js} +1 -1
  78. package/dist/web/assets/{agent-work-summary-C9yMf019.js → agent-work-summary-D0a836ik.js} +1 -1
  79. package/dist/web/assets/{attention-store-CG9cF6DX.js → attention-store-g2-_vAhV.js} +1 -1
  80. package/dist/web/assets/{badge-DvvDq2Wb.js → badge-BIoC0hjn.js} +1 -1
  81. package/dist/web/assets/{button-CFEnxtio.js → button-A2esxd6G.js} +1 -1
  82. package/dist/web/assets/{checkbox-DovdRz8u.js → checkbox-DxBVlC6t.js} +1 -1
  83. package/dist/web/assets/{client-lh80ewvs.js → client-DAoXcTUz.js} +1 -1
  84. package/dist/web/assets/{console-CQMgYkk9.js → console-DiNe1hFP.js} +1 -1
  85. package/dist/web/assets/{conversation-launcher-settings-B1QM-wZB.js → conversation-launcher-settings-CtOlr9uP.js} +1 -1
  86. package/dist/web/assets/{design-lab-BDKwIbI8.js → design-lab-UWXx2ZtA.js} +1 -1
  87. package/dist/web/assets/{dialog-D2mO6m3B.js → dialog-DTVE8tN1.js} +1 -1
  88. package/dist/web/assets/{dist-PmK0PfVA.js → dist-D-8b3yGa.js} +1 -1
  89. package/dist/web/assets/{dropdown-menu-YzCnvjAb.js → dropdown-menu-NcUrhhmG.js} +1 -1
  90. package/dist/web/assets/{field-BMEFEyVC.js → field-6mg5DSC8.js} +1 -1
  91. package/dist/web/assets/{identity-bK-fJdnj.js → identity-FG3YqHVj.js} +1 -1
  92. package/dist/web/assets/index-BpQe3IT5.js +2 -0
  93. package/dist/web/assets/{judgment-types-DJnAr9c0.js → judgment-types-rLsl2Cis.js} +1 -1
  94. package/dist/web/assets/{model-Cengn9fg.js → model-BCnsjEuP.js} +1 -1
  95. package/dist/web/assets/{model-rumuELTi.js → model-BcMr6R8m.js} +1 -1
  96. package/dist/web/assets/{model-DpVrfbnj.js → model-CYJ_LZ47.js} +1 -1
  97. package/dist/web/assets/{model-BwNZZZNP.js → model-CeF2BATq.js} +1 -1
  98. package/dist/web/assets/{model-CuY1vtEy.js → model-CtmCtjml.js} +1 -1
  99. package/dist/web/assets/{model-CPMYnu3S.js → model-t2ZvD7wL.js} +1 -1
  100. package/dist/web/assets/{motion-preference-A1AMssSH.js → motion-preference-DeZURhN7.js} +1 -1
  101. package/dist/web/assets/{occupation-catalog-DxwlYD1L.js → occupation-catalog-q0ZjGx2o.js} +1 -1
  102. package/dist/web/assets/{orchestration-filters-DZpJ0FN3.js → orchestration-filters-CKf_Gzdl.js} +1 -1
  103. package/dist/web/assets/{page-title-Bg-mVyrS.js → page-title-BLHrexaP.js} +1 -1
  104. package/dist/web/assets/{personal-profile-graph-tMneNj_m.js → personal-profile-graph-IYovB9sV.js} +1 -1
  105. package/dist/web/assets/{project-capture-QgMw6qvo.js → project-capture-BvIPecIS.js} +1 -1
  106. package/dist/web/assets/{project-origin-ppsYHpYL.js → project-origin-JnGPwlfA.js} +1 -1
  107. package/dist/web/assets/project-team-api-Cfn41MCR.js +1 -0
  108. package/dist/web/assets/{quick-edit-api-BiyK3ih-.js → quick-edit-api-DzpRAPsr.js} +1 -1
  109. package/dist/web/assets/{shared-report-D3Hem1t5.js → shared-report-BLmBg2FG.js} +3 -3
  110. package/dist/web/assets/{task-labels-7KyNw9id.js → task-labels-BArOYZEW.js} +1 -1
  111. package/dist/web/assets/{ui-Ck58paqr.js → ui-CtW0tAA1.js} +1 -1
  112. package/dist/web/assets/{useAgentRecords-C6RrZwwv.js → useAgentRecords-BoOqLQcf.js} +1 -1
  113. package/dist/web/assets/{useApi-CROJJdhE-BujjnKN_.js → useApi-CROJJdhE-CH5wlWTU.js} +1 -1
  114. package/dist/web/assets/{useFocusReturn-D9IOIg17.js → useFocusReturn-DX2zmPSK.js} +1 -1
  115. package/dist/web/assets/{useKnowledgeItemPeek-C6nAzvDL.js → useKnowledgeItemPeek-Cfvr5H1q.js} +1 -1
  116. package/dist/web/assets/{useMinimumLoadingDisplay-HnxkDut6.js → useMinimumLoadingDisplay-GhG1ICNJ.js} +1 -1
  117. package/dist/web/assets/{useRoutePeek-BvYFc1BA.js → useRoutePeek-DydCbUhy.js} +1 -1
  118. package/dist/web/assets/{vue-router-Bl55c88B.js → vue-router-Dad-4p7O.js} +1 -1
  119. package/dist/web/index.html +32 -32
  120. package/docs/agent-conversations-and-collaboration.md +10 -0
  121. package/docs/employee-agents.md +3 -1
  122. package/docs/judgment-and-autonomy.md +30 -1
  123. package/graph-provider/fuli_graph/agent_conversation_models.py +7 -0
  124. package/graph-provider/fuli_graph/agent_conversation_routes.py +5 -1
  125. package/graph-provider/fuli_graph/default_project_lead.py +7 -3
  126. package/graph-provider/fuli_graph/store_agent_conversations.py +66 -34
  127. package/graph-provider/pyproject.toml +1 -1
  128. package/native/win32/fuli-win-helper.exe +0 -0
  129. package/npm-shrinkwrap.json +2 -2
  130. package/package.json +1 -1
  131. package/packages/roundtable/src/host.js +5 -0
  132. package/packages/roundtable/src/peer/coordinator-service.js +20 -3
  133. package/packages/roundtable/src/roundtable/service.js +31 -5
  134. package/skills/capturing-session-knowledge/references/retrieval.md +10 -2
  135. package/skills/operating-fuli/references/workflow-recipes.md +2 -0
  136. package/src/agent-apps/host-tools/catalog.js +1 -0
  137. package/src/agent-tools/executor-routing-definitions.js +194 -0
  138. package/src/agent-tools/graph-definitions.js +20 -1279
  139. package/src/agent-tools/graph-handlers.js +6 -2
  140. package/src/agent-tools/graph-tool-fields.js +43 -0
  141. package/src/agent-tools/interface-catalog.js +5 -1
  142. package/src/agent-tools/knowledge-curation-definitions.js +167 -0
  143. package/src/agent-tools/knowledge-definitions.js +431 -0
  144. package/src/agent-tools/project-agent-tool-definitions.js +271 -0
  145. package/src/agent-tools/project-space-definitions.js +155 -0
  146. package/src/agent-tools/session-fuli-gate.js +33 -31
  147. package/src/agent-tools/standing-assignment-definitions.js +32 -0
  148. package/src/agent-tools/task-entry-definitions.js +105 -0
  149. package/src/agent-tools.js +5 -4
  150. package/src/agents/claude-code/lifecycle-hook.js +16 -2
  151. package/src/agents/claude-code/preference-evidence.js +11 -1
  152. package/src/app/application-error.js +21 -3
  153. package/src/conversations/capture-window.js +8 -3
  154. package/src/conversations/entry-budget.js +2 -10
  155. package/src/conversations/entry-inline-budget.js +144 -0
  156. package/src/conversations/entry-rules.js +1 -1
  157. package/src/conversations/entry-time.js +15 -0
  158. package/src/conversations/preference-evidence.js +19 -0
  159. package/src/conversations/preference-lifecycle.js +28 -7
  160. package/src/conversations/preference-session.js +26 -10
  161. package/src/conversations/preference-snapshot.js +12 -1
  162. package/src/conversations/sync-transcript.js +10 -6
  163. package/src/conversations/transcript-guard.js +4 -3
  164. package/src/conversations/transcript-lifecycle.js +6 -3
  165. package/src/data-format/local-stores.js +3 -0
  166. package/src/desktop/windows-installation.js +2 -1
  167. package/src/external-knowledge/connectors/feishu.js +3 -1
  168. package/src/graphiti/active-personal-space.js +5 -0
  169. package/src/graphiti/agent-conversations.js +23 -28
  170. package/src/graphiti/agent-knowledge-workflows.js +12 -1299
  171. package/src/graphiti/agent-project-resolution.js +11 -0
  172. package/src/graphiti/agent-view-records.js +19 -0
  173. package/src/graphiti/capture-notice.js +20 -6
  174. package/src/graphiti/collaboration-preference-entry.js +89 -0
  175. package/src/graphiti/collaboration-preference-workflow.js +1 -1
  176. package/src/graphiti/common-knowledge-candidates.js +222 -0
  177. package/src/graphiti/cross-project-knowledge-similarity.js +59 -0
  178. package/src/graphiti/current-project-knowledge-search.js +86 -0
  179. package/src/graphiti/decision-trace.js +136 -0
  180. package/src/graphiti/federated-application.js +158 -795
  181. package/src/graphiti/human-knowledge-changes.js +45 -0
  182. package/src/graphiti/knowledge-credential-guard.js +43 -0
  183. package/src/graphiti/knowledge-curation.js +178 -0
  184. package/src/graphiti/knowledge-feedback.js +25 -0
  185. package/src/graphiti/knowledge-graph-reads.js +62 -0
  186. package/src/graphiti/local-runtimes.js +78 -0
  187. package/src/graphiti/personal-global-preference-candidates.js +431 -0
  188. package/src/graphiti/personal-projects.js +33 -0
  189. package/src/graphiti/preference-conflict-requests.js +57 -0
  190. package/src/graphiti/preference-project-resolution.js +39 -0
  191. package/src/graphiti/preference-task-scope.js +18 -0
  192. package/src/graphiti/project-agent-control-plane.js +6 -1
  193. package/src/graphiti/project-agent-task-entry.js +18 -1
  194. package/src/graphiti/project-path-context.js +28 -9
  195. package/src/graphiti/provider-client.js +1 -1
  196. package/src/graphiti/public-project-relations.js +28 -0
  197. package/src/graphiti/public-projects.js +125 -0
  198. package/src/graphiti/publication-review-queues.js +50 -0
  199. package/src/graphiti/roundtable-host.js +35 -3
  200. package/src/graphiti/session-capture-pause-request.js +3 -2
  201. package/src/graphiti/session-fuli-switch.js +4 -3
  202. package/src/graphiti/session-knowledge-capture.js +59 -0
  203. package/src/graphiti/session-records.js +4 -3
  204. package/src/graphiti/source-marker.js +13 -3
  205. package/src/graphiti/standing-assignment-confirmation.js +66 -0
  206. package/src/graphiti/standing-assignment-correction.js +148 -0
  207. package/src/graphiti/standing-assignment-entry.js +223 -0
  208. package/src/graphiti/task-context-entry.js +114 -0
  209. package/src/graphiti/task-entry-preferences.js +4 -1
  210. package/src/graphiti/task-entry-project-mention.js +13 -2
  211. package/src/graphiti/task-entry-project-scope.js +12 -3
  212. package/src/graphiti/task-entry-standing-owner.js +141 -0
  213. package/src/graphiti/task-knowledge-checkpoint.js +212 -0
  214. package/src/graphiti/task-knowledge-guidance.js +13 -0
  215. package/src/graphiti/task-knowledge-recall.js +113 -2
  216. package/src/graphiti/task-preference-reader.js +1 -1
  217. package/src/graphiti/workflow-learning.js +38 -0
  218. package/src/graphiti/workspace-provider-client.js +10 -0
  219. package/src/http/api-router.js +13 -3
  220. package/src/http/standing-assignment-api-router.js +35 -0
  221. package/src/judgment/agent-view.js +29 -7
  222. package/src/judgment/conversation.js +8 -2
  223. package/src/judgment/engine.js +16 -4
  224. package/src/judgment/http.js +37 -5
  225. package/src/judgment/review-injection-precheck.js +97 -0
  226. package/src/judgment/review-suggestions.js +46 -0
  227. package/src/judgment/store.js +8 -0
  228. package/src/knowledge-hard-delete/delete-ledger.js +12 -3
  229. package/src/knowledge-hard-delete/recovery-gate.js +4 -4
  230. package/src/knowledge-owner-reads/console-port.js +8 -0
  231. package/src/knowledge-owner-reads/owner-proof.js +35 -0
  232. package/src/local-runtime/lifecycle.js +2 -1
  233. package/src/local-runtime/provider-readiness.js +35 -11
  234. package/src/mcp/instructions.js +3 -3
  235. package/src/mcp/preference-delivery.js +13 -3
  236. package/src/mcp/session-id.js +2 -0
  237. package/src/mcp/tool-annotations.js +3 -2
  238. package/src/model-backends/http.js +45 -8
  239. package/src/model-backends/role-settings.js +25 -3
  240. package/src/model-backends/role-trust.js +39 -6
  241. package/src/model-backends/runtime.js +10 -3
  242. package/src/model-backends/settings-history-list.js +132 -0
  243. package/src/model-backends/settings-history.js +175 -0
  244. package/src/native-runtime/java-runtime.js +4 -4
  245. package/src/presence/windows-helper-pin.js +1 -1
  246. package/src/semantic-version.js +5 -1
  247. package/src/server.js +3 -2
  248. package/src/setup/claude-code-config.js +1 -1
  249. package/src/setup/graph-runtime.js +42 -15
  250. package/src/setup/paths.js +2 -0
  251. package/src/standing-assignments/port.js +189 -44
  252. package/src/standing-assignments/store.js +12 -1
  253. package/src/standing-assignments/term-match.js +7 -0
  254. package/src/system/file-identity.js +11 -0
  255. package/src/system/platform-path.js +38 -0
  256. package/src/validation/values.js +22 -6
  257. package/dist/web/assets/EmployeeWorkbenchPage-BUMfMBc8.js +0 -3
  258. package/dist/web/assets/KnowledgePage-Bfbfz_Z8.js +0 -1
  259. package/dist/web/assets/ModelSettingsPage-C3eBDWRL.js +0 -1
  260. package/dist/web/assets/ModelSettingsPage-DZkrJw7R.css +0 -1
  261. package/dist/web/assets/index-r-WFOs21.js +0 -2
  262. package/dist/web/assets/project-team-api-DwP0O3rn.js +0 -1
@@ -1,1299 +1,12 @@
1
- import { taskAgentAssignment } from './task-agent-assignment.js';
2
- import { beginConversation, checkpointConversation } from './agent-conversations.js';
3
- import { recordTriage, validateTriage } from './conversation-triage.js';
4
- import { REMEMBER_GUIDANCE, compactTaskCapture, rememberRequested } from './task-remember.js';
5
- import { withRecoveredSource } from './task-knowledge-recall.js';
6
- import { taskTeam } from './task-collaboration-attribution.js';
7
- import { captureSettingsUrl, taskAgentReceipt } from '../agents/identity-receipt.js';
8
- import { checkpointTurnReceipt, entryAgentReceipt } from './turn-receipt-delivery.js';
9
- import { ensureSessionTemporaryProject } from './temporary-project-scope.js';
10
- import { createHash } from 'node:crypto';
11
- import { taskPreferenceScope } from '../mcp/provider-task-context-registry.js';
12
-
13
- import { ApplicationError, ApplicationErrorCode } from '../app/application-error.js';
14
- import { agentMemoryRecord, prepareProjectAgentMemory } from './project-agent-memory.js';
15
- import { internalCaptureSkip, legacyCaptureReceipts, normalizeTaskCaptures, taskCaptureInput, taskCaptureReceipt, taskCaptureReviewPaths, taskCaptureStatus } from './task-knowledge-routing.js';
16
- import { captureDisabled, taskCaptureScope } from './capture-decision.js';
17
- import { checkpointCaptureDecision, storedCheckpoint } from './checkpoint-capture.js';
18
- import { receiptNotices } from './capture-notice.js';
19
- import { receiptFormatNotices } from '../data-format/format-notices.js';
20
- import { activeSealedWorkerRequest } from '../app/agent-request-context.js';
21
- import { taskPreferenceMetadata, withPreferenceScope } from '../conversations/preference-snapshot.js';
22
- import { checkpointHumanInteraction } from './checkpoint-human-interaction.js';
23
- import { budgetKnowledgeSearch } from './knowledge-result-budget.js';
24
-
25
- import { onlineSourceUri } from './source-uri.js';
26
- import {
27
- relatedProjectGuidance,
28
- relatedProjectSuggestions
29
- } from './related-project-suggestions.js';
30
-
31
- export async function beginTaskContext(application, {
32
- sessionId,
33
- turnId = null,
34
- projectPath,
35
- personalProjectId = null,
36
- taskPrompt = null,
37
- sourceApplication = 'other',
38
- sourceSessionId = null,
39
- projectAgentId = null,
40
- workKind,
41
- workflow,
42
- requiredCapabilities = []
43
- }) {
44
- const continuationToken = /^FULI_CHECKPOINT_REQUIRED: (fuli-task-[a-zA-Z0-9-]{8,128})\b/.exec(taskPrompt ?? '')?.[1];
45
- const current = !continuationToken && turnId && application.taskContextRegistry.current
46
- ? await application.taskContextRegistry.current(sessionId, sourceApplication) : null;
47
- const resumed = continuationToken
48
- ? await application.taskContextRegistry.context(continuationToken, sourceApplication) : null;
49
- const scopeRetry = current?.turnId === turnId
50
- ? current : null;
51
- if (resumed && resumed.sessionId !== sessionId) {
52
- throw validationError('Checkpoint continuation belongs to another host session');
53
- }
54
- const existingTask = resumed ?? scopeRetry;
55
- if (existingTask && personalProjectId && existingTask.personalProjectId !== personalProjectId) {
56
- throw validationError('Task context belongs to another project');
57
- }
58
- const preferenceScope = existingTask ? taskPreferenceScope(existingTask.preferenceScope)
59
- : taskPreferenceScope({ version: 1, work_kind: workKind ?? null, workflow: workflow ?? null });
60
- if (!preferenceScope) throw validationError('Task preference scope is unknown; legacy recovery cannot guess preference dimensions');
61
- if (existingTask && ((workKind !== undefined && workKind !== preferenceScope.work_kind) ||
62
- (workflow !== undefined && workflow !== preferenceScope.workflow))) {
63
- throw Object.assign(validationError('Task preference scope is immutable; begin a new task for different dimensions'), { status: 409 });
64
- }
65
- const preferences = await application.getCollaborationPreferences({
66
- personalProjectId: resumed?.personalProjectId ?? scopeRetry?.personalProjectId ?? personalProjectId,
67
- projectPath,
68
- sessionId,
69
- turnId: existingTask?.turnId ?? turnId,
70
- taskPrompt,
71
- projectAgentId: resumed?.projectAgentId ?? scopeRetry?.projectAgentId ?? projectAgentId,
72
- sourceApplication,
73
- sourceSessionId,
74
- workKind: preferenceScope.work_kind,
75
- workflow: preferenceScope.workflow,
76
- requiredCapabilities,
77
- agentInvocation: true,
78
- agentToolName: 'begin_task_context'
79
- });
80
- if (resumed && resumed.personalProjectId !== preferences.context.personal_project_id) {
81
- throw validationError('Checkpoint continuation belongs to another project');
82
- }
83
- return beginTaskFromPreferences(application, preferences, {
84
- sessionId, turnId: existingTask?.turnId ?? turnId, sourceApplication, sourceSessionId, taskPrompt,
85
- workKind: preferenceScope.work_kind, workflow: preferenceScope.workflow
86
- }, { existingTask: resumed ?? (scopeRetry?.projectScope?.type === 'temporary' ? scopeRetry : null), resumed: Boolean(resumed),
87
- entryVia: 'hook' });
88
- }
89
-
90
- export const STOP_HOOK_CHECKPOINT_GUIDANCE = 'Call checkpoint_task_knowledge for capture candidates, experiences, agentMemory changes, knowledgeUsage, collaborators or a meaningful workLog, including failures and blockers. Otherwise the Stop hook closes the task as retain_nothing/reported; without a Stop hook a routine fallback closes at the next entry in the same native session. Copy the current entry receipt when skipping checkpoint; never claim unsaved memory was saved.';
91
-
92
- // Hook and model fallback share the same durable lifecycle. A stored pending
93
- // task is not evidence that its context reached this model turn.
94
- export async function beginTaskFromPreferences(application, preferences, {
95
- sessionId, turnId = null, sourceApplication = 'other', sourceSessionId = null,
96
- workKind = null, workflow = null, taskPrompt = null
97
- }, { existingTask = null, resumed = false, entryVia = 'tool' } = {}) {
98
- const task = existingTask ?? await application.taskContextRegistry.begin({
99
- sessionId,
100
- turnId,
101
- personalProjectId: preferences.context.personal_project_id,
102
- projectAgentId: preferences.context.project_agent_id,
103
- sourceApplication,
104
- sourceSessionId,
105
- delegationToken: application.roundtable?.taskEntryDelegation?.({ sessionId })?.token,
106
- preferenceScope: taskPreferenceScope({ version: 1, work_kind: workKind, workflow }),
107
- agentAssignment: taskAgentAssignment(preferences.project_agent_context),
108
- memoryRevision: preferences.project_agent_context?.memory?.revision ?? null,
109
- workLogRequired: Boolean(preferences.project_agent_context?.memory),
110
- entryVia
111
- });
112
- // Only the Provider can establish that a fallback has no claim or worker /
113
- // coordination associations. Missing metadata keeps the legacy requirement.
114
- // A request to keep something is never a routine auto-closed task.
115
- const remembering = rememberRequested(taskPrompt);
116
- const autoClosed = !remembering && ((entryVia === 'hook' && task.entryVia === 'hook') || task.routineAutoCloseEligible === true);
117
- const conversation = await beginConversation(application, task);
118
- const receipt = preferences.agent_receipt ? await entryAgentReceipt(application, task, preferences.agent_receipt) : null;
119
- return withPreferenceScope({
120
- conversation,
121
- taskContextToken: task.token,
122
- task_context_token: task.token,
123
- checkpoint_required: !autoClosed && task.checkpoint?.phase !== 'complete',
124
- ...(autoClosed ? { checkpoint_guidance: STOP_HOOK_CHECKPOINT_GUIDANCE } : {}),
125
- ...(remembering ? { remember_guidance: REMEMBER_GUIDANCE } : {}),
126
- resumed_checkpoint: Boolean(resumed),
127
- previous_checkpoint_missing: task.previousCheckpointMissing,
128
- ...preferences, ...(receipt ? { agent_receipt: receipt } : {}),
129
- ...(preferences.task_knowledge_recall ? { task_knowledge_recall: withRecoveredSource(preferences.task_knowledge_recall, conversation, {
130
- consoleUrl: application.consoleUrl, spaceId: preferences.context?.personal_space_id, agentId: preferences.context?.project_agent_id }) } : {}),
131
- ...(task.projectScope ? { project_scope: task.projectScope } : {}),
132
- task_guidance: taskKnowledgeGuidance()
133
- }, taskPreferenceMetadata(task, application.config?.personal?.spaceId));
134
- }
135
-
136
- export function taskKnowledgeGuidance() {
137
- return {
138
- execution_plan: 'For an explicit durable project execution plan, publish public steps via record_project_agent_task_activity.executionPlan and update step statuses as work progresses. Reuse step IDs and send the full current plan; steps: [] withdraws it. Optional: never invent plans, infer progress percentages or expose private reasoning. Completed steps do not replace verification or human acceptance.',
139
- collaboration: 'Before implementation, call plan_agent_collaboration with taskSize and all known implementationAgentIds; follow divisionPlan. Standard work: main FLA + different FLA for independent acceptance. Complex work: add at most one explicitly bounded independentWork. Small low-impact edits, coupled changes and command-only checks need no artificial split. Keep coupled implementation together; separate meaningful acceptance once artifacts are stable. The stable project lead decomposes, integrates and delivers. Reuse qualified specialists; gaps use approved loans or existing HR flow. Workers get bounded briefs and necessary artifact references, not the full conversation. Start with at most 3 results/query; expand only for a specific gap. Use only authorized clients/models and assess_agent_action under existing user policies. Publish assigned scopes/dependencies via the optional execution plan; report real worker/model/usage and leave unknown tokens unknown. Verify artifacts via record_agent_verification with evidence; escalate capability after two failures. Recommendations, command runs and configured peers alone are not independent worker execution.',
140
- profile_capture: 'Separately evaluate durable artifact taste (including writing voice, wording, structure, formatting), stable collaboration personality and decision preferences; do not default all to judgment_preference. Writing evidence uses tasteDomain: writing; a scene-limited item uses attributes.tasteDomain (frontend, ui, ux, design, visual, architecture, code, testing, chat) or workKind, and only explicit user words set attributes.constraint: hard (every scene, chat included) or soft (small talk may omit it); remember takes the same fields. Retain exact session/turn/time provenance. Agent-inferred personality stays pending. Report missing evidence; do not promise automatic progress from use alone.',
141
- knowledge_routing: 'Finish with retain_nothing+reason or one capture+captureRouting using explicit personal_global/current_project scopes. Partition each entity/relationship key exactly once; keep relationships with endpoints. Project-limited preferences stay current_project; global scope requires explicit sourceExcerpt evidence, never inferred from profileAspect. Global capture uses standalone preference entities (e.g. PersonalPreference/profileAspect taste), never relabelled Person/Project anchors. Every routed AI proposal remains pending; excerpts do not verify global applicability. Routine review goes to Tonborg under saved policy and must not block independent work. For human decisions use human_interaction: ask native choices with custom input in this conversation, without requiring a review page. review_paths are optional inspection links. Private employee working context belongs in agentMemory, not shared knowledge.',
142
- human_attention: 'When the person is in this conversation, ask there with native choices (human_interaction). Use request_agent_attention when they are away or the answer must outlive this session: the FULI 待决策 page is their inbox. Pass the exact current space/project/Agent IDs, a stable idempotency key and a specific requestedAction; for a step they must do by hand (log in, trust hooks) say so, and they can answer Done. Never raise a hand for ordinary running, queueing or automatic retries. Answers reach you as attention_replies at task entry, in read_agent_messages, or at once in an agent_chat wait; cancel obsolete requests with cancel_agent_attention. A response does not grant permission or accept task completion.',
143
- retrieval: 'Inspect task_knowledge_recall before asking for a stable project fact or method again. On a miss, use search_current_project_knowledge with focused action, artifact, target-system, or identifier queries; never use the full conversational request as the only query.',
144
- checkpoint: 'The owner checkpoints after integration when there are capture candidates, experiences, memory changes, explicit knowledge usage, collaborators or a meaningful workLog. For routine finishes follow checkpoint_guidance; checkpoint_required remains true when automatic closure is unavailable. Coordinated workers return evidence and must not begin or checkpoint an inherited parent context. Explicit checkpoints use capture_candidates or retain_nothing; assigned employees include a concise truthful workLog, even without knowledge capture. Memory changes include agentMemory with the loaded revision and bounded merged notes. Do not overwrite truncated context or store raw transcripts.'
145
- };
146
- }
147
-
148
- export async function checkpointTaskKnowledge(application, {
149
- taskContextToken,
150
- disposition,
151
- reason,
152
- capture = null,
153
- captureRouting = null,
154
- agentMemory = null,
155
- workLog = null,
156
- knowledgeUsage = null,
157
- sourceApplication = 'other',
158
- personalProjectId = null,
159
- remoteSessionId = null,
160
- collaborators = [],
161
- triage = null,
162
- experiences = null,
163
- remember = null
164
- }) {
165
- if (!['capture_candidates', 'retain_nothing'].includes(disposition)) {
166
- throw validationError('Unknown task knowledge checkpoint disposition');
167
- }
168
- const triageLabel = validateTriage(triage);
169
- const task = await application.taskContextRegistry.context(taskContextToken, sourceApplication);
170
- if (personalProjectId && task.personalProjectId !== personalProjectId) {
171
- throw validationError('Task checkpoint belongs to another project');
172
- }
173
- if (remoteSessionId && task.sessionId !== remoteSessionId) {
174
- throw validationError('Task checkpoint belongs to another remote session');
175
- }
176
- // One decision for every write of this checkpoint, kept across its retries.
177
- // Its writes are decided by the task's project, including a global
178
- // preference learned there.
179
- const captureScope = taskCaptureScope(task);
180
- const captureCheck = await checkpointCaptureDecision(application, task);
181
- const captureKnowledge = async input => captureCheck.allowed ? application.captureSessionKnowledge(input, { captureScope })
182
- : { route: 'disabled', ...captureDisabled(captureCheck) };
183
- // experiences and remember are compact forms of one routed capture.
184
- if (experiences !== null || remember !== null) {
185
- if (capture || captureRouting !== null) throw validationError('Send experiences or remember, or a capture, not both');
186
- if (disposition !== 'capture_candidates') throw validationError('experiences and remember require disposition capture_candidates');
187
- ({ capture, captureRouting } = compactTaskCapture(task, { experiences, remember }, { sourceApplication }));
188
- }
189
- // A Provider-admitted sealed worker call still checkpoints, but never writes
190
- // preference or project knowledge candidates. Only the worker MCP composition
191
- // marks the call; roundtable wakes and unknown origins keep ordinary capture.
192
- const internalActivity = disposition === 'capture_candidates' && capture && activeSealedWorkerRequest()
193
- ? 'sealed_worker' : null;
194
- const scopedCaptures = captureRouting === null || internalActivity
195
- ? null : normalizeTaskCaptures(task, capture, captureRouting);
196
- if (disposition === 'capture_candidates') {
197
- if (!capture && !scopedCaptures) {
198
- throw validationError('capture_candidates requires a bounded capture payload');
199
- }
200
- } else if (capture || scopedCaptures) {
201
- throw validationError('retain_nothing cannot include a capture payload');
202
- }
203
- if (task.workLogRequired && !workLog && !agentMemory) {
204
- throw validationError('This employee needs a workLog summary and status before finishing; retain_nothing only skips knowledge capture.');
205
- }
206
- const fingerprint = createHash('sha256').update(JSON.stringify(
207
- canonicalCheckpoint({ disposition, reason, capture: scopedCaptures ? null : capture,
208
- ...(scopedCaptures ? { captures: scopedCaptures } : {}),
209
- ...(internalActivity && captureRouting !== null ? { captureRouting } : {}), agentMemory, ...(workLog ? { workLog } : {}),
210
- ...(knowledgeUsage ? { knowledgeUsage } : {}) })
211
- )).digest('hex');
212
- if (task.checkpoint && task.checkpoint.fingerprint !== fingerprint) {
213
- throw validationError(
214
- 'Task checkpoint already has different input; resume the original review or begin a new task context'
215
- );
216
- }
217
- const finish = async (result, checkpointTask = task, memory = null) => {
218
- const team = await taskTeam(application, checkpointTask, collaborators);
219
- const effectiveLog = workLog ?? { status: 'reported', summary: reason };
220
- const conversation = captureCheck.allowed ? await checkpointConversation(application, task, effectiveLog, team)
221
- : captureDisabled(captureCheck);
222
- const triaged = await recordTriage(application, task, conversation, triageLabel);
223
- const interaction = activeSealedWorkerRequest() ? {} : await checkpointHumanInteraction(application, task);
224
- return { ...interaction, ...result, conversation, ...(triaged ? { triage: triaged } : {}),
225
- agent_receipt: taskAgentReceipt(application, { projectId: task.personalProjectId,
226
- agentId: task.projectAgentId ?? null, name: team.name, role: team.role, sourceApplication: task.sourceApplication,
227
- workStatus: effectiveLog.status, conversationId: conversation?.conversation_id ?? null,
228
- persistence: conversation?.status ?? null, collaborators: team.collaborators,
229
- notices: [...receiptNotices(captureCheck, [], { settingsUrl: captureSettingsUrl(application) }), ...await receiptFormatNotices(application)],
230
- turnReceipt: await checkpointTurnReceipt(application, checkpointTask, { memory, agentName: team.name }) }),
231
- ...(team.ignored.length ? { ignored_collaborators: team.ignored } : {}) };
232
- };
233
- if (task.checkpoint?.phase === 'complete') {
234
- return finish({ status: 'checkpointed', disposition, reason,
235
- personal_project_id: task.personalProjectId, project_agent_id: task.projectAgentId,
236
- replayed: true, capture_status: task.checkpoint.captureStatus,
237
- ...(task.checkpoint.knowledgeUsageResult ? { knowledge_usage: task.checkpoint.knowledgeUsageResult } : {}),
238
- ...(task.checkpoint.captureResults ? { capture_results: taskCaptureReviewPaths(application.config.personal.spaceId, task.checkpoint.captureResults) } : {}) });
239
- }
240
- const captureInput = capture && !scopedCaptures && !internalActivity ? {
241
- ...capture,
242
- targetKind: 'personal',
243
- spaceId: application.config.personal.spaceId,
244
- personalProjectId: task.personalProjectId,
245
- projectAgentId: task.agentMemoryScope === 'task_only' ? null : task.projectAgentId ?? null,
246
- sessionId: task.sessionId,
247
- sourceApplication,
248
- idempotencyKey: `${task.token}:knowledge`
249
- } : null;
250
- // Local validation has no side effects. Reject correctable input before
251
- // binding an immutable checkpoint or advancing the Agent's memory revision.
252
- if (captureInput) await application.validateCaptureSessionKnowledge(captureInput, { captureScope });
253
- const temporaryProjectId = captureCheck.allowed && scopedCaptures?.some(batch => batch.scope === 'session_temporary')
254
- ? await ensureSessionTemporaryProject(application, task) : null;
255
- const scopedInputs = scopedCaptures?.map(batch => ({ scope: batch.scope,
256
- input: taskCaptureInput(application.config.personal.spaceId, task, batch, temporaryProjectId) }));
257
- for (const batch of scopedInputs ?? []) await application.validateCaptureSessionKnowledge(batch.input, { captureScope });
258
- // The Provider owns the full commit model and scope authorization. Validate
259
- // every scoped batch before claiming the checkpoint or advancing memory.
260
- if (scopedInputs && captureCheck.allowed) await application.preflightPersonalKnowledgeCaptures(scopedInputs.map(batch => batch.input));
261
- let memoryResult = null;
262
- let memoryRequest = null;
263
- if (agentMemory) {
264
- if (!task.projectAgentId) {
265
- throw validationError('Task has no durable project Agent; do not guess a memory target');
266
- }
267
- const prepared = await prepareProjectAgentMemory(application, {
268
- personalSpaceId: application.config.personal.spaceId,
269
- personalProjectId: task.personalProjectId,
270
- agentId: task.projectAgentId,
271
- expectedRevision: agentMemory.expectedRevision,
272
- idempotencyKey: `${task.token}:memory`,
273
- memory: agentMemory.memory, sourceApplication,
274
- // The logical client session survives independent lifecycle-hook MCP
275
- // processes; their host session ids do not. The Provider persists this
276
- // stable task session as the memory checkpoint provenance.
277
- sourceSessionId: task.sessionId
278
- });
279
- if (prepared.status === 'capture_disabled') memoryResult = prepared;
280
- else if (!captureCheck.allowed) memoryResult = captureDisabled(captureCheck);
281
- else memoryRequest = { expected_revision: prepared.request.expected_revision,
282
- memory: prepared.request.memory };
283
- }
284
- const recorded = { disposition, reason, fingerprint, captureStatus: null,
285
- ...(knowledgeUsage ? { knowledgeUsage } : {}),
286
- ...(task.projectAgentId ? { workLog: workLog ?? {
287
- status: agentMemory ? 'reported' : 'unreported', summary: reason
288
- } } : {}) };
289
- const checkpoint = storedCheckpoint(task, recorded, captureCheck);
290
- const preparedTask = await application.taskContextRegistry.prepare(
291
- taskContextToken, checkpoint, sourceApplication, memoryRequest
292
- );
293
- if (memoryRequest) {
294
- if (!preparedTask.agentMemory) {
295
- throw new TypeError('Provider did not confirm atomic Agent memory preparation');
296
- }
297
- memoryResult = { status: 'checkpointed', ...agentMemoryRecord(preparedTask.agentMemory) };
298
- }
299
- const captureResult = internalActivity ? internalCaptureSkip(internalActivity) : captureInput
300
- ? await captureKnowledge(captureInput) : null;
301
- const captureResults = scopedInputs ? [] : null;
302
- for (const batch of scopedInputs ?? []) {
303
- const result = await captureKnowledge(batch.input);
304
- captureResults.push(taskCaptureReceipt(batch.scope, batch.input, result));
305
- }
306
- const captureStatus = captureResults
307
- ? taskCaptureStatus(captureResults)
308
- : captureResult?.status ?? checkpoint.captureStatus;
309
- // Both capture paths keep what they saved, so the turn's receipt can read it back.
310
- const savedResults = captureResults ?? legacyCaptureReceipts(captureInput, captureResult);
311
- const completedTask = await application.taskContextRegistry.checkpoint(taskContextToken, {
312
- ...checkpoint, captureStatus, ...(savedResults ? { captureResults: savedResults } : {})
313
- }, sourceApplication);
314
- return finish({
315
- status: 'checkpointed',
316
- disposition,
317
- reason,
318
- personal_project_id: task.personalProjectId,
319
- project_agent_id: task.projectAgentId ?? null,
320
- capture: captureResult ?? (captureCheck.allowed ? null : { route: 'disabled', ...captureDisabled(captureCheck) }),
321
- ...(preparedTask.checkpoint?.knowledgeUsageResult ? { knowledge_usage: preparedTask.checkpoint.knowledgeUsageResult } : {}),
322
- ...(captureResults ? { capture_status: captureStatus, capture_results: taskCaptureReviewPaths(application.config.personal.spaceId, captureResults) } : {}),
323
- ...(internalActivity ? { capture_status: captureStatus } : {}),
324
- agent_memory: memoryResult ? {
325
- status: memoryResult.status, agentId: memoryResult.agentId,
326
- checkpointId: memoryResult.checkpointId, revision: memoryResult.revision,
327
- sourceApplication: memoryResult.sourceApplication,
328
- sourceSessionId: memoryResult.sourceSessionId, createdAt: memoryResult.createdAt
329
- } : null
330
- }, completedTask, memoryResult?.status === 'checkpointed' && memoryResult.revision > agentMemory.expectedRevision ? memoryResult : null);
331
- }
332
-
333
- function canonicalCheckpoint(value) {
334
- if (Array.isArray(value)) return value.map(canonicalCheckpoint);
335
- if (!value || typeof value !== 'object') return value;
336
- return Object.fromEntries(Object.keys(value).sort().map((key) => [
337
- key, canonicalCheckpoint(value[key])
338
- ]));
339
- }
340
-
341
- function validationError(message) {
342
- return new ApplicationError(ApplicationErrorCode.VALIDATION, message);
343
- }
344
-
345
- export async function recordDecisionTrace(application, input) {
346
- const trace = decisionTraceKnowledge(input);
347
- return application.captureSessionKnowledge({
348
- targetKind: 'personal',
349
- spaceId: input.personalSpaceId,
350
- personalProjectId: input.personalProjectId ?? null,
351
- sessionId: input.sessionId,
352
- idempotencyKey: input.idempotencyKey,
353
- name: `Decision · ${input.title}`,
354
- sourceKind: input.sourceKind,
355
- sourceDescription: input.sourceDescription,
356
- sourceUri: input.sourceUri ?? null,
357
- sourceApplication: input.sourceApplication ?? null,
358
- sourceTurnId: input.sourceTurnId ?? null,
359
- referenceTime: input.referenceTime,
360
- summary: `${input.question}\nSelected: ${input.selectedOption.label}`,
361
- sensitivity: input.sensitivity ?? 'normal',
362
- ...trace
363
- });
364
- }
365
-
366
- export async function searchCurrentProjectKnowledge(
367
- application,
368
- resolution,
369
- {
370
- queries,
371
- limitPerQuery = 12,
372
- includeHistorical = false,
373
- includePending = false,
374
- cursor = null, sourceApplication = null
375
- }
376
- ) {
377
- const projectResolution = agentProjectResolution(resolution);
378
- if (!resolution.personalProjectId) {
379
- return {
380
- status: 'project_unresolved',
381
- personal_space_id: application.config.personal.spaceId,
382
- personal_project_id: null,
383
- project_resolution: projectResolution,
384
- results: [],
385
- required_action: resolution.status === 'ambiguous'
386
- ? 'Run from the exact project directory or explicitly choose one project; Fuli will not guess among workspace children.'
387
- : 'Register this repository or directory as one local personal project before project-scoped search.'
388
- };
389
- }
390
-
391
- const [results, relatedProjects] = await Promise.all([
392
- Promise.all(queries.map((query) =>
393
- application.searchKnowledge({
394
- personalSpaceId: application.config.personal.spaceId,
395
- personalProjectId: resolution.personalProjectId,
396
- query,
397
- limit: limitPerQuery,
398
- includeHistorical,
399
- includePending, sourceApplication,
400
- agentInvocation: true,
401
- agentToolName: 'search_current_project_knowledge'
402
- })
403
- )),
404
- loadRelatedProjectSuggestions(application, resolution.personalProjectId)
405
- ]);
406
- return budgetKnowledgeSearch({
407
- status: 'searched',
408
- personal_space_id: application.config.personal.spaceId,
409
- personal_project_id: resolution.personalProjectId,
410
- project_resolution: projectResolution,
411
- scope_policy: {
412
- local_project_first: true,
413
- inherited_relation_types: ['PART_OF', 'USES_KNOWLEDGE_FROM'],
414
- max_inheritance_hops: 2,
415
- local_same_key_overrides_parent: true,
416
- unrelated_relations_expand_scope: false,
417
- related_project_expansion_requires_confirmation: true
418
- },
419
- results,
420
- related_project_suggestions: relatedProjects.suggestions,
421
- related_project_suggestions_status: relatedProjects.status,
422
- related_project_guidance: relatedProjectGuidance(relatedProjects.suggestions)
423
- }, { cursor, consoleUrl: application.consoleUrl, toolName: 'search_current_project_knowledge',
424
- context: { personalSpaceId: application.config.personal.spaceId,
425
- personalProjectId: resolution.personalProjectId, queries, limitPerQuery, includeHistorical, includePending } });
426
- }
427
-
428
- async function loadRelatedProjectSuggestions(application, personalProjectId) {
429
- try {
430
- const graph = await application.personal.graph(
431
- application.config.personal.spaceId,
432
- 2000,
433
- personalProjectId
434
- );
435
- return {
436
- status: graph?.truncated ? 'partial' : 'available',
437
- suggestions: relatedProjectSuggestions(graph, personalProjectId)
438
- };
439
- } catch {
440
- return { status: 'unavailable', suggestions: [] };
441
- }
442
- }
443
-
444
- export async function discoverCommonKnowledgeCandidates(application, {
445
- personalSpaceId,
446
- parentProjectId,
447
- query,
448
- minChildProjects = 2,
449
- similarityThreshold = 0.72,
450
- limitPerProject = 12
451
- }) {
452
- if (!Number.isInteger(minChildProjects) || minChildProjects < 2) {
453
- throw new TypeError('Common knowledge needs evidence from at least two child projects');
454
- }
455
- if (
456
- typeof similarityThreshold !== 'number'
457
- || similarityThreshold < 0
458
- || similarityThreshold > 1
459
- ) {
460
- throw new TypeError('Similarity threshold must be between 0 and 1');
461
- }
462
-
463
- const graph = await application.personal.graph(personalSpaceId, 2000);
464
- const projectIdByNodeId = new Map(
465
- (graph.nodes ?? [])
466
- .filter(({ type }) => type === 'PersonalProject')
467
- .map((node) => [node.id, node.attributes?.projectId])
468
- .filter(([, projectId]) => typeof projectId === 'string' && projectId)
469
- );
470
- if (![...projectIdByNodeId.values()].includes(parentProjectId)) {
471
- throw new TypeError('Parent project is not present in the active personal graph');
472
- }
473
- const childProjectIds = [...new Set(
474
- (graph.edges ?? [])
475
- .filter(({ type, source, target, attributes = {} }) =>
476
- type === 'PART_OF'
477
- && attributes.status === 'active'
478
- && (
479
- attributes.confirmationAuthority
480
- ?? attributes.confirmation_authority
481
- ) === 'human_review'
482
- && projectIdByNodeId.get(target) === parentProjectId
483
- && projectIdByNodeId.has(source)
484
- )
485
- .map(({ source }) => projectIdByNodeId.get(source))
486
- )].sort();
487
-
488
- if (childProjectIds.length < minChildProjects) {
489
- return commonCandidateResult({
490
- status: childProjectIds.length === 0 ? 'no_children' : 'insufficient_children',
491
- personalSpaceId,
492
- parentProjectId,
493
- childProjectIds,
494
- query,
495
- candidates: [],
496
- graph
497
- });
498
- }
499
-
500
- const childResults = await Promise.all(childProjectIds.map(async (projectId) => ({
501
- projectId,
502
- result: await application.personal.search({
503
- space_ids: [personalSpaceId],
504
- query,
505
- limit: limitPerProject,
506
- include_historical: false,
507
- include_exploratory: true,
508
- personal_project_ids: [projectId],
509
- active_personal_project_id: projectId,
510
- inherit_project_knowledge: false,
511
- include_personal_global: false
512
- })
513
- })));
514
- const items = childResults.flatMap(({ projectId, result }) => [
515
- ...(result.entities ?? []).map((item) =>
516
- commonKnowledgeItem(item, 'entity', projectId)
517
- ),
518
- ...(result.facts ?? []).map((item) =>
519
- commonKnowledgeItem(item, 'relationship', projectId)
520
- )
521
- ]).filter((item) => !item.profile_aspect);
522
- const candidates = clusterCommonKnowledgeItems(
523
- items,
524
- minChildProjects,
525
- similarityThreshold,
526
- parentProjectId,
527
- query
528
- );
529
- return commonCandidateResult({
530
- status: candidates.length > 0 ? 'candidates_found' : 'no_candidates',
531
- personalSpaceId,
532
- parentProjectId,
533
- childProjectIds,
534
- query,
535
- candidates,
536
- graph
537
- });
538
- }
539
-
540
- export async function discoverPersonalGlobalPreferenceCandidates(application, {
541
- personalSpaceId,
542
- personalProjectIds,
543
- query,
544
- minProjects = 2,
545
- similarityThreshold = 0.72,
546
- limitPerProject = 12
547
- }) {
548
- if (!Array.isArray(personalProjectIds) || personalProjectIds.length < 2) {
549
- throw new TypeError('Personal-global candidates need at least two explicit projects');
550
- }
551
- if (!Number.isInteger(minProjects) || minProjects < 2) {
552
- throw new TypeError('Personal-global candidates need evidence from at least two projects');
553
- }
554
- if (
555
- typeof similarityThreshold !== 'number'
556
- || similarityThreshold < 0
557
- || similarityThreshold > 1
558
- ) {
559
- throw new TypeError('Similarity threshold must be between 0 and 1');
560
- }
561
- const projectIds = [...new Set(personalProjectIds)].sort();
562
- if (projectIds.length < 2 || minProjects > projectIds.length) {
563
- throw new TypeError('The selected project set cannot satisfy minProjects');
564
- }
565
- const knownProjectIds = new Set(
566
- (await application.personal.listPersonalProjects(personalSpaceId))
567
- .map(({ project_id: projectId }) => projectId)
568
- );
569
- if (projectIds.some((projectId) => !knownProjectIds.has(projectId))) {
570
- throw new TypeError('Every selected project must exist in the active personal space');
571
- }
572
-
573
- const projectResults = await Promise.all(projectIds.map(async (projectId) => ({
574
- projectId,
575
- result: await application.personal.search({
576
- space_ids: [personalSpaceId],
577
- query,
578
- limit: limitPerProject,
579
- include_historical: false,
580
- include_exploratory: false,
581
- personal_project_ids: [projectId],
582
- active_personal_project_id: projectId,
583
- inherit_project_knowledge: false,
584
- include_personal_global: false
585
- })
586
- })));
587
- const items = projectResults.flatMap(({ projectId, result }) => [
588
- ...(result.entities ?? []).map((item) =>
589
- commonKnowledgeItem(item, 'entity', projectId)
590
- ),
591
- ...(result.facts ?? []).map((item) =>
592
- commonKnowledgeItem(item, 'relationship', projectId)
593
- )
594
- ]).filter((item) =>
595
- item.profile_aspect
596
- && item.preference_scope === 'project'
597
- && item.preference_project_id === item.defined_project_id
598
- && ['confirmed', 'agent_confirmed'].includes(item.confirmation_status)
599
- && item.requires_attention !== true
600
- );
601
- const clusteredCandidates = clusterPersonalGlobalPreferenceItems(
602
- items,
603
- minProjects,
604
- similarityThreshold,
605
- query,
606
- projectIds.length
607
- );
608
- const candidates = await Promise.all(clusteredCandidates.map(async (candidate) => {
609
- const options = await application.personal.personalGlobalPreferenceScopeOptions(
610
- candidate.candidate_id,
611
- {
612
- personal_space_id: personalSpaceId,
613
- source_items: candidate.source_items.map((item) => ({
614
- item_id: item.id,
615
- item_kind: item.item_kind,
616
- project_id: item.defined_project_id
617
- })),
618
- preference_key: candidate.preference_key
619
- }
620
- );
621
- return {
622
- ...candidate,
623
- candidate_version: options.candidate_version,
624
- target_scope: 'human_selected',
625
- eligible_target_scopes: options.eligible_target_scopes,
626
- source_snapshots: options.source_snapshots
627
- };
628
- }));
629
- const decisionState = await personalGlobalCandidateDecisionState(
630
- application,
631
- personalSpaceId,
632
- candidates
633
- );
634
- const visibleCandidates = candidates
635
- .filter(({ candidate_id: id, candidate_version: version }) =>
636
- !decisionState.decisions.has(`${id}:${version}`)
637
- )
638
- .map((candidate) => personalGlobalCandidateWithDecisionState(
639
- candidate,
640
- decisionState.revisions.get(candidate.candidate_id)
641
- ));
642
- const suppressedCandidates = candidates
643
- .filter(({ candidate_id: id, candidate_version: version }) =>
644
- decisionState.decisions.has(`${id}:${version}`)
645
- )
646
- .map(({ candidate_id: candidateId, candidate_version: version }) => ({
647
- candidate_id: candidateId,
648
- candidate_version: version,
649
- ...decisionState.decisions.get(`${candidateId}:${version}`)
650
- }));
651
- return {
652
- status: visibleCandidates.length > 0
653
- ? 'candidates_found'
654
- : suppressedCandidates.length > 0
655
- ? 'candidates_suppressed'
656
- : 'no_candidates',
657
- personal_space_id: personalSpaceId,
658
- target_scope: 'human_selected',
659
- selected_project_ids: projectIds,
660
- query,
661
- candidates: visibleCandidates,
662
- suppressed_candidates: suppressedCandidates,
663
- policy: personalGlobalCandidatePolicy()
664
- };
665
- }
666
-
667
- export async function previewPersonalGlobalPreferenceDecision(application, input) {
668
- return application.personal.inspectPersonalGlobalPreferenceDecision(
669
- input.candidateId,
670
- providerPersonalGlobalPreferenceDecision(input)
671
- );
672
- }
673
-
674
- export async function applyPersonalGlobalPreferenceDecision(application, input) {
675
- return application.personal.applyPersonalGlobalPreferenceDecision(
676
- input.candidateId,
677
- providerPersonalGlobalPreferenceDecision(input, {
678
- approvalToken: input.previewToken
679
- })
680
- );
681
- }
682
-
683
- export async function recordKnowledgeFeedback(application, {
684
- personalSpaceId,
685
- taskId,
686
- sessionId = null,
687
- toolName = null,
688
- items
689
- }) {
690
- return application.personal.recordKnowledgeFeedback({
691
- personal_space_id: personalSpaceId,
692
- task_id: taskId,
693
- session_id: sessionId,
694
- tool_name: toolName,
695
- items: items.map((item) => ({
696
- item_id: item.itemId,
697
- item_kind: item.itemKind,
698
- feedback_kind: item.feedbackKind,
699
- reason: item.reason,
700
- evidence_summary: item.evidenceSummary,
701
- reported_by_kind: item.reportedByKind,
702
- source_uri: onlineSourceUri(item.sourceUri)
703
- }))
704
- });
705
- }
706
-
707
- export function providerCommonKnowledgePromotion(input) {
708
- return {
709
- personal_space_id: input.personalSpaceId,
710
- parent_project_id: input.parentProjectId,
711
- item_kind: input.itemKind,
712
- canonical_item_id: input.canonicalItemId,
713
- duplicate_item_ids: input.duplicateItemIds,
714
- reason: input.reason,
715
- human_confirmation_reason: input.humanConfirmationReason
716
- };
717
- }
718
-
719
- export function agentProjectResolution(resolution) {
720
- const result = {
721
- status: resolution.status,
722
- basis: resolution.basis,
723
- personal_project_id: resolution.personalProjectId
724
- };
725
- if (resolution.candidateCount !== undefined) {
726
- result.candidate_count = resolution.candidateCount;
727
- }
728
- return result;
729
- }
730
-
731
- function commonCandidateResult({
732
- status,
733
- personalSpaceId,
734
- parentProjectId,
735
- childProjectIds,
736
- query,
737
- candidates,
738
- graph
739
- }) {
740
- return {
741
- status,
742
- personal_space_id: personalSpaceId,
743
- parent_project_id: parentProjectId,
744
- child_project_ids: childProjectIds,
745
- query,
746
- candidates,
747
- graph_truncated: graph.truncated === true,
748
- policy: commonKnowledgeCandidatePolicy()
749
- };
750
- }
751
-
752
- function commonKnowledgeItem(item, itemKind, projectId) {
753
- return {
754
- ...item,
755
- item_kind: itemKind,
756
- defined_project_id: projectId
757
- };
758
- }
759
-
760
- function clusterCommonKnowledgeItems(
761
- items,
762
- minChildProjects,
763
- similarityThreshold,
764
- parentProjectId,
765
- query
766
- ) {
767
- const groups = [];
768
- for (const item of items) {
769
- const matching = groups
770
- .map((group) => ({
771
- group,
772
- similarity: Math.max(
773
- ...group.items.map((member) => commonKnowledgeSimilarity(item, member))
774
- )
775
- }))
776
- .filter(({ group, similarity }) =>
777
- group.itemKind === item.item_kind
778
- && similarity >= similarityThreshold
779
- && !group.projectIds.has(item.defined_project_id)
780
- )
781
- .sort((left, right) => right.similarity - left.similarity)[0];
782
- if (matching) {
783
- matching.group.items.push(item);
784
- matching.group.projectIds.add(item.defined_project_id);
785
- continue;
786
- }
787
- groups.push({
788
- itemKind: item.item_kind,
789
- projectIds: new Set([item.defined_project_id]),
790
- items: [item]
791
- });
792
- }
793
-
794
- return groups
795
- .filter(({ projectIds }) => projectIds.size >= minChildProjects)
796
- .map((group) => {
797
- const orderedItems = [...group.items].sort((left, right) =>
798
- left.defined_project_id.localeCompare(right.defined_project_id)
799
- );
800
- const pairScores = [];
801
- for (let left = 0; left < orderedItems.length; left += 1) {
802
- for (let right = left + 1; right < orderedItems.length; right += 1) {
803
- pairScores.push(commonKnowledgeSimilarity(
804
- orderedItems[left],
805
- orderedItems[right]
806
- ));
807
- }
808
- }
809
- const averageSimilarity = pairScores.length === 0
810
- ? 1
811
- : pairScores.reduce((sum, score) => sum + score, 0) / pairScores.length;
812
- const itemIds = orderedItems.map(({ id }) => id).sort();
813
- return {
814
- candidate_id: `common-${createHash('sha256')
815
- .update(itemIds.join('\n'))
816
- .digest('hex')
817
- .slice(0, 20)}`,
818
- parent_project_id: parentProjectId,
819
- child_project_ids: [...group.projectIds].sort(),
820
- item_kind: group.itemKind,
821
- query,
822
- similarity_score: Number(averageSimilarity.toFixed(4)),
823
- similarity_basis: 'lexical_overlap_across_direct_child_projects',
824
- items: orderedItems,
825
- requires_human_confirmation: true,
826
- promotion_performed: false
827
- };
828
- })
829
- .sort((left, right) =>
830
- right.child_project_ids.length - left.child_project_ids.length
831
- || right.similarity_score - left.similarity_score
832
- || left.candidate_id.localeCompare(right.candidate_id)
833
- );
834
- }
835
-
836
- function clusterPersonalGlobalPreferenceItems(
837
- items,
838
- minProjects,
839
- similarityThreshold,
840
- query,
841
- selectedProjectCount
842
- ) {
843
- const groups = [];
844
- for (const item of items) {
845
- const preferenceKey = personalGlobalItemPreferenceKey(item);
846
- const matching = groups
847
- .map((group) => ({
848
- group,
849
- similarity: Math.min(
850
- ...group.items.map((member) => commonKnowledgeSimilarity(item, member))
851
- )
852
- }))
853
- .filter(({ group, similarity }) =>
854
- group.itemKind === item.item_kind
855
- && group.preferenceKey === preferenceKey
856
- && similarity >= similarityThreshold
857
- && !group.projectIds.has(item.defined_project_id)
858
- )
859
- .sort((left, right) => right.similarity - left.similarity)[0];
860
- if (matching) {
861
- matching.group.items.push(item);
862
- matching.group.projectIds.add(item.defined_project_id);
863
- continue;
864
- }
865
- groups.push({
866
- itemKind: item.item_kind,
867
- preferenceKey,
868
- projectIds: new Set([item.defined_project_id]),
869
- items: [item]
870
- });
871
- }
872
-
873
- return groups
874
- .filter(({ projectIds }) => projectIds.size >= minProjects)
875
- .map((group) => {
876
- const sourceItems = [...group.items].sort((left, right) =>
877
- left.defined_project_id.localeCompare(right.defined_project_id)
878
- );
879
- const itemIds = sourceItems.map(({ id }) => id).sort();
880
- const commonTerms = sharedPreferenceTerms(sourceItems);
881
- const pairScores = [];
882
- for (let left = 0; left < sourceItems.length; left += 1) {
883
- for (let right = left + 1; right < sourceItems.length; right += 1) {
884
- pairScores.push(commonKnowledgeSimilarity(
885
- sourceItems[left],
886
- sourceItems[right]
887
- ));
888
- }
889
- }
890
- const averageSimilarity = pairScores.length === 0
891
- ? 1
892
- : pairScores.reduce((sum, score) => sum + score, 0) / pairScores.length;
893
- const ranking = personalGlobalCandidateRanking({
894
- sourceItems,
895
- projectCount: group.projectIds.size,
896
- selectedProjectCount,
897
- lexicalSimilarity: averageSimilarity
898
- });
899
- return {
900
- candidate_id: personalGlobalPreferenceCandidateId(itemIds),
901
- candidate_version: null,
902
- target_scope: 'human_selected',
903
- source_project_ids: [...group.projectIds].sort(),
904
- item_kind: group.itemKind,
905
- preference_key: group.preferenceKey,
906
- query,
907
- similarity_score: Number(averageSimilarity.toFixed(4)),
908
- similarity_basis: 'lexical_overlap_across_explicit_personal_projects',
909
- candidate_score: ranking.score,
910
- ranking,
911
- source_items: sourceItems,
912
- derived_common_core: {
913
- terms: commonTerms,
914
- basis: 'lexical_intersection_of_preserved_source_text',
915
- authoritative: false,
916
- source_item_ids: itemIds
917
- },
918
- source_specific_terms: sourceItems.map((item) => ({
919
- item_id: item.id,
920
- project_id: item.defined_project_id,
921
- terms: [...preferenceContentTokens(item)]
922
- .filter((term) => !commonTerms.includes(term))
923
- .sort()
924
- })),
925
- requires_human_scope_judgment: true,
926
- scope_apply_performed: false
927
- };
928
- })
929
- .sort((left, right) =>
930
- right.candidate_score - left.candidate_score
931
- || right.source_project_ids.length - left.source_project_ids.length
932
- || right.similarity_score - left.similarity_score
933
- || left.candidate_id.localeCompare(right.candidate_id)
934
- );
935
- }
936
-
937
- function personalGlobalItemPreferenceKey(item) {
938
- return item.preference_key
939
- ?? item.attributes?.preferenceKey
940
- ?? item.attributes?.preference_key
941
- ?? item.key
942
- ?? item.id;
943
- }
944
-
945
- const PERSONAL_GLOBAL_RANKING_WEIGHTS = Object.freeze({
946
- distinct_projects: 0.25,
947
- lexical_similarity: 0.35,
948
- confirmation_authority: 0.2,
949
- recency: 0.1,
950
- negative_evidence: 0.1
951
- });
952
-
953
- function personalGlobalCandidateRanking({
954
- sourceItems,
955
- projectCount,
956
- selectedProjectCount,
957
- lexicalSimilarity
958
- }) {
959
- const signals = {
960
- distinct_projects: boundedScore(
961
- projectCount / Math.max(selectedProjectCount, 1)
962
- ),
963
- lexical_similarity: boundedScore(lexicalSimilarity),
964
- confirmation_authority: averageScore(sourceItems.map((item) =>
965
- item.confirmation_status === 'confirmed' ? 1 : 0.65
966
- )),
967
- recency: averageScore(sourceItems.map(personalGlobalItemRecency)),
968
- negative_evidence: averageScore(sourceItems.map((item) =>
969
- item.requires_attention === true
970
- ? 0
971
- : 1 / (1 + Math.max(0, Number(item.negative_evidence_count ?? 0)))
972
- ))
973
- };
974
- const details = Object.fromEntries(
975
- Object.entries(signals).map(([key, value]) => {
976
- const weight = PERSONAL_GLOBAL_RANKING_WEIGHTS[key];
977
- return [key, {
978
- value: Number(value.toFixed(4)),
979
- weight,
980
- contribution: Number((value * weight).toFixed(4))
981
- }];
982
- })
983
- );
984
- const score = Object.values(details)
985
- .reduce((sum, signal) => sum + signal.contribution, 0);
986
- return {
987
- score: Number(score.toFixed(4)),
988
- signals: details,
989
- source_project_count: projectCount,
990
- selected_project_count: selectedProjectCount,
991
- policy: 'ranking_only_never_changes_scope_or_confirmation_authority'
992
- };
993
- }
994
-
995
- function personalGlobalItemRecency(item) {
996
- const timestamp = [
997
- item.last_used_at,
998
- item.last_human_changed_at,
999
- item.created_at
1000
- ].map((value) => Date.parse(value ?? ''))
1001
- .find(Number.isFinite);
1002
- if (!Number.isFinite(timestamp)) return 0.5;
1003
- const ageDays = Math.max(0, (Date.now() - timestamp) / 86_400_000);
1004
- return Math.exp(-ageDays / 180);
1005
- }
1006
-
1007
- function averageScore(values) {
1008
- if (values.length === 0) return 0;
1009
- return boundedScore(
1010
- values.reduce((sum, value) => sum + value, 0) / values.length
1011
- );
1012
- }
1013
-
1014
- function boundedScore(value) {
1015
- return Math.max(0, Math.min(1, Number(value) || 0));
1016
- }
1017
-
1018
- function commonKnowledgeSimilarity(left, right) {
1019
- if (left.key && right.key && left.key === right.key) return 1;
1020
- const leftTokens = commonKnowledgeTokens(left);
1021
- const rightTokens = commonKnowledgeTokens(right);
1022
- if (leftTokens.size === 0 || rightTokens.size === 0) return 0;
1023
- let intersection = 0;
1024
- for (const token of leftTokens) {
1025
- if (rightTokens.has(token)) intersection += 1;
1026
- }
1027
- return intersection / new Set([...leftTokens, ...rightTokens]).size;
1028
- }
1029
-
1030
- function commonKnowledgeTokens(item) {
1031
- const text = [
1032
- item.name,
1033
- item.summary,
1034
- item.fact,
1035
- item.type
1036
- ].filter(Boolean).join(' ').toLowerCase();
1037
- return lexicalTokens(text);
1038
- }
1039
-
1040
- function preferenceContentTokens(item) {
1041
- const text = [
1042
- item.instruction,
1043
- item.summary,
1044
- item.fact
1045
- ].filter(Boolean).join(' ').toLowerCase();
1046
- return lexicalTokens(text || String(item.name ?? '').toLowerCase());
1047
- }
1048
-
1049
- function sharedPreferenceTerms(items) {
1050
- const tokenSets = items.map(preferenceContentTokens);
1051
- if (tokenSets.length === 0) return [];
1052
- return [...tokenSets[0]]
1053
- .filter((term) => tokenSets.slice(1).every((tokens) => tokens.has(term)))
1054
- .sort();
1055
- }
1056
-
1057
- function lexicalTokens(text) {
1058
- const tokens = new Set(
1059
- text.match(/[a-z0-9]+(?:[._-][a-z0-9]+)*/g) ?? []
1060
- );
1061
- for (const sequence of text.match(/[\u3400-\u9fff]+/g) ?? []) {
1062
- if (sequence.length === 1) tokens.add(sequence);
1063
- for (let index = 0; index < sequence.length - 1; index += 1) {
1064
- tokens.add(sequence.slice(index, index + 2));
1065
- }
1066
- }
1067
- return tokens;
1068
- }
1069
-
1070
- function commonKnowledgeCandidatePolicy() {
1071
- return {
1072
- read_only: true,
1073
- direct_part_of_children_only: true,
1074
- active_human_authorized_relations_only: true,
1075
- personal_preferences_excluded: true,
1076
- inherited_knowledge_excluded: true,
1077
- personal_global_excluded: true,
1078
- automatic_promotion: false,
1079
- human_confirmation_required: true,
1080
- similarity_is_inferred_not_authoritative: true
1081
- };
1082
- }
1083
-
1084
- function personalGlobalCandidatePolicy() {
1085
- return {
1086
- read_only: true,
1087
- exact_projects_only: true,
1088
- inherited_knowledge_excluded: true,
1089
- personal_global_excluded: true,
1090
- original_text_and_sources_preserved: true,
1091
- derived_core_is_non_authoritative: true,
1092
- human_scope_judgment_required: true,
1093
- automatic_scope_apply: false,
1094
- ranking_scores_are_non_authoritative: true,
1095
- stale_decisions_do_not_suppress_changed_candidates: true
1096
- };
1097
- }
1098
-
1099
- async function personalGlobalCandidateDecisionState(
1100
- application,
1101
- personalSpaceId,
1102
- candidates
1103
- ) {
1104
- if (candidates.length === 0) {
1105
- return { decisions: new Map(), revisions: new Map() };
1106
- }
1107
- const result = await application.personal
1108
- .personalGlobalPreferenceDecisionStatus({
1109
- personal_space_id: personalSpaceId,
1110
- candidates: candidates.map((candidate) => ({
1111
- candidate_id: candidate.candidate_id,
1112
- candidate_version: candidate.candidate_version
1113
- }))
1114
- });
1115
- return {
1116
- decisions: new Map((result.decisions ?? []).map((decision) => [
1117
- `${decision.candidate_id}:${decision.candidate_version}`,
1118
- {
1119
- decision: decision.decision,
1120
- decision_event_id: decision.decision_event_id,
1121
- decision_revision: decision.decision_revision,
1122
- target_scope: decision.target_scope,
1123
- target_project_id: decision.target_project_id ?? null,
1124
- global_assertion_id: decision.global_assertion_id,
1125
- global_assertion_active: decision.global_assertion_active
1126
- }
1127
- ])),
1128
- revisions: new Map((result.revisions ?? []).map((revision) => [
1129
- revision.candidate_id,
1130
- revision
1131
- ]))
1132
- };
1133
- }
1134
-
1135
- function personalGlobalCandidateWithDecisionState(candidate, revision) {
1136
- const decisionRevision = revision?.decision_revision ?? 0;
1137
- const previousVersion = revision?.current_candidate_version ?? null;
1138
- const sourceDrift = Boolean(
1139
- previousVersion && previousVersion !== candidate.candidate_version
1140
- );
1141
- return {
1142
- ...candidate,
1143
- decision_revision: decisionRevision,
1144
- prior_decision_source_drift: sourceDrift,
1145
- prior_decision_candidate_version: sourceDrift ? previousVersion : null,
1146
- fresh_human_review_required: true
1147
- };
1148
- }
1149
-
1150
- function providerPersonalGlobalPreferenceDecision(input, {
1151
- approvalToken = null
1152
- } = {}) {
1153
- const result = {
1154
- personal_space_id: input.personalSpaceId,
1155
- candidate_version: input.candidateVersion,
1156
- decision_revision: input.decisionRevision,
1157
- source_items: input.sourceItems.map((item) => ({
1158
- item_id: item.itemId,
1159
- item_kind: item.itemKind,
1160
- project_id: item.projectId
1161
- })),
1162
- preference_key: input.preferenceKey,
1163
- target_scope: input.targetScope,
1164
- target_project_id: input.targetProjectId ?? null,
1165
- decision: input.decision,
1166
- global_title: input.globalTitle ?? null,
1167
- global_instruction: input.globalInstruction ?? null,
1168
- profile_aspect: input.profileAspect ?? null,
1169
- human_confirmation_reason: input.humanConfirmationReason,
1170
- confirmed_at: input.confirmedAt,
1171
- session_id: input.sessionId,
1172
- idempotency_key: input.idempotencyKey
1173
- };
1174
- if (approvalToken) result.approval_token = approvalToken;
1175
- return result;
1176
- }
1177
-
1178
- function personalGlobalPreferenceCandidateId(itemIds) {
1179
- return `personal-global-${createHash('sha256')
1180
- .update([...itemIds].sort().join('\n'))
1181
- .digest('hex')
1182
- .slice(0, 20)}`;
1183
- }
1184
-
1185
- function decisionTraceKnowledge(input) {
1186
- const decisionKey = `decision:${input.decisionKey}`;
1187
- const selectedKey = `${decisionKey}:option:${input.selectedOption.key}`;
1188
- const rationaleKey = `${decisionKey}:rationale`;
1189
- const rejected = input.rejectedOptions ?? [];
1190
- const validations = input.validationResults ?? [];
1191
- const confirmed = ['user', 'authoritative_source'].includes(
1192
- input.decidedBy.kind
1193
- );
1194
- const confirmationStatus = confirmed ? 'confirmed' : 'pending';
1195
- const epistemicStatus = confirmed ? 'confirmed' : 'observed';
1196
- const confirmationBasis = {
1197
- existenceReason: input.sourceDescription,
1198
- quadrantReason: input.reason,
1199
- proposedBy: input.decidedBy,
1200
- confirmedBy: confirmed ? input.decidedBy : null,
1201
- confirmedAt: confirmed ? input.referenceTime : null,
1202
- agentPolicyVersion: null
1203
- };
1204
- const epistemic = {
1205
- originQuadrant: 'known_known',
1206
- currentQuadrant: 'known_known',
1207
- epistemicStatus,
1208
- confirmationStatus,
1209
- confirmationBasis,
1210
- reasoningSummary: input.reason,
1211
- inheritanceMode: 'local_only',
1212
- inheritedProjectIds: []
1213
- };
1214
- const entities = [
1215
- {
1216
- key: decisionKey,
1217
- name: input.title,
1218
- type: 'Decision',
1219
- summary: `${input.question}\nSelected: ${input.selectedOption.label}`,
1220
- attributes: {
1221
- decisionKey: input.decisionKey,
1222
- selectedOptionKey: input.selectedOption.key,
1223
- decidedByKind: input.decidedBy.kind
1224
- },
1225
- ...epistemic
1226
- },
1227
- {
1228
- key: selectedKey,
1229
- name: input.selectedOption.label,
1230
- type: 'DecisionOption',
1231
- summary: input.selectedOption.summary ?? '',
1232
- attributes: { disposition: 'selected' },
1233
- ...epistemic
1234
- },
1235
- ...rejected.map((option) => ({
1236
- key: `${decisionKey}:option:${option.key}`,
1237
- name: option.label,
1238
- type: 'DecisionOption',
1239
- summary: option.summary ?? '',
1240
- attributes: { disposition: 'rejected' },
1241
- ...epistemic
1242
- })),
1243
- {
1244
- key: rationaleKey,
1245
- name: `${input.title} · rationale`,
1246
- type: 'DecisionRationale',
1247
- summary: input.reason,
1248
- attributes: {},
1249
- ...epistemic
1250
- },
1251
- ...validations.map((validation) => ({
1252
- key: `${decisionKey}:validation:${validation.key}`,
1253
- name: `${input.title} · ${validation.key}`,
1254
- type: 'ValidationResult',
1255
- summary: validation.summary,
1256
- attributes: { outcome: validation.outcome },
1257
- ...epistemic
1258
- }))
1259
- ];
1260
- const relationship = (key, target, type, fact) => ({
1261
- key,
1262
- source: decisionKey,
1263
- target,
1264
- type,
1265
- fact,
1266
- confidence: confirmed ? 1 : 0.7,
1267
- attributes: {},
1268
- ...epistemic
1269
- });
1270
- return {
1271
- entities,
1272
- relationships: [
1273
- relationship(
1274
- `${decisionKey}:selected`,
1275
- selectedKey,
1276
- 'SELECTED_OPTION',
1277
- `${input.title} selected ${input.selectedOption.label}.`
1278
- ),
1279
- ...rejected.map((option) => relationship(
1280
- `${decisionKey}:rejected:${option.key}`,
1281
- `${decisionKey}:option:${option.key}`,
1282
- 'REJECTED_OPTION',
1283
- `${input.title} did not select ${option.label}.`
1284
- )),
1285
- relationship(
1286
- `${decisionKey}:motivated-by`,
1287
- rationaleKey,
1288
- 'MOTIVATED_BY',
1289
- input.reason
1290
- ),
1291
- ...validations.map((validation) => relationship(
1292
- `${decisionKey}:validated-by:${validation.key}`,
1293
- `${decisionKey}:validation:${validation.key}`,
1294
- 'VALIDATED_BY',
1295
- `${validation.outcome}: ${validation.summary}`
1296
- ))
1297
- ]
1298
- };
1299
- }
1
+ // The Agent knowledge workflows' public surface. Each capability lives in its
2
+ // own module; this file only names what Agents and the application call.
3
+ export { beginTaskContext, beginTaskFromPreferences } from './task-context-entry.js';
4
+ export { checkpointTaskKnowledge } from './task-knowledge-checkpoint.js';
5
+ export { recordDecisionTrace } from './decision-trace.js';
6
+ export { recordKnowledgeFeedback } from './knowledge-feedback.js';
7
+ export { discoverCommonKnowledgeCandidates, providerCommonKnowledgePromotion } from './common-knowledge-candidates.js';
8
+ export {
9
+ applyPersonalGlobalPreferenceDecision,
10
+ discoverPersonalGlobalPreferenceCandidates,
11
+ previewPersonalGlobalPreferenceDecision
12
+ } from './personal-global-preference-candidates.js';