@markus-global/cli 0.12.4 → 0.12.5-rc.0

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 (159) hide show
  1. package/dist/background-maintenance.d.ts +25 -0
  2. package/dist/background-maintenance.d.ts.map +1 -1
  3. package/dist/background-maintenance.js +61 -0
  4. package/dist/background-maintenance.js.map +1 -1
  5. package/dist/commands/im-inbound-origin.d.ts +38 -0
  6. package/dist/commands/im-inbound-origin.d.ts.map +1 -0
  7. package/dist/commands/im-inbound-origin.js +48 -0
  8. package/dist/commands/im-inbound-origin.js.map +1 -0
  9. package/dist/commands/start.d.ts.map +1 -1
  10. package/dist/commands/start.js +211 -46
  11. package/dist/commands/start.js.map +1 -1
  12. package/dist/markus.mjs +18520 -9886
  13. package/dist/web-ui/assets/{AsyncState-BTLUPIr1.js → AsyncState-ByYn1wrM.js} +1 -1
  14. package/dist/web-ui/assets/ChatComponents-Bwh8SlUV.js +14 -0
  15. package/dist/web-ui/assets/{ContentRenderer-BZXRiKE3.js → ContentRenderer-GLgoGp2a.js} +6 -6
  16. package/dist/web-ui/assets/DeliverableShareModal-CRfnRuR3.js +1 -0
  17. package/dist/web-ui/assets/{Deliverables-3Y3zjT_1.js → Deliverables-EFsnf6kU.js} +2 -2
  18. package/dist/web-ui/assets/MarkdownMessage-CaLBeMto.js +4 -0
  19. package/dist/web-ui/assets/{Search-BI3hk-5j.js → Search-COiaXUNr.js} +1 -1
  20. package/dist/web-ui/assets/{SendToChat-D_5zHO-k.js → SendToChat-DleryIlc.js} +1 -1
  21. package/dist/web-ui/assets/Settings-CzY8z2Yh.js +8 -0
  22. package/dist/web-ui/assets/{Store-B8ksRjHF.js → Store-C4VpQCM_.js} +1 -1
  23. package/dist/web-ui/assets/Switch-ByogYoGH.js +1 -0
  24. package/dist/web-ui/assets/Team-Cutq2J24.js +93 -0
  25. package/dist/web-ui/assets/Work-BO-mz-na.js +142 -0
  26. package/dist/web-ui/assets/{arc-VmvI7TpW.js → arc-mYv67jdD.js} +1 -1
  27. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-CTUtPasm.js → architectureDiagram-3BPJPVTR-Bzpz_1r6.js} +1 -1
  28. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-xeYAqtZJ.js → blockDiagram-GPEHLZMM-BBrLiivl.js} +1 -1
  29. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-BiFgoGY5.js → c4Diagram-AAUBKEIU-BwDUoXA_.js} +1 -1
  30. package/dist/web-ui/assets/channel-Bx09lbhA.js +1 -0
  31. package/dist/web-ui/assets/{chunk-2J33WTMH-DueHBqOn.js → chunk-2J33WTMH-DCSfJ-S9.js} +1 -1
  32. package/dist/web-ui/assets/{chunk-4BX2VUAB-B8zgDfSV.js → chunk-4BX2VUAB-CI0n1b2H.js} +1 -1
  33. package/dist/web-ui/assets/{chunk-55IACEB6-DieD55CP.js → chunk-55IACEB6-DqlSWLrm.js} +1 -1
  34. package/dist/web-ui/assets/{chunk-727SXJPM-Do4Z9LQ0.js → chunk-727SXJPM-BtmAfGYV.js} +1 -1
  35. package/dist/web-ui/assets/{chunk-AQP2D5EJ-qrYsW5ml.js → chunk-AQP2D5EJ-BgkA4lpQ.js} +1 -1
  36. package/dist/web-ui/assets/{chunk-FMBD7UC4-BSz3QT1q.js → chunk-FMBD7UC4-DCSr1JH4.js} +1 -1
  37. package/dist/web-ui/assets/{chunk-ND2GUHAM-utDWSydt.js → chunk-ND2GUHAM-CETYBRRm.js} +1 -1
  38. package/dist/web-ui/assets/{chunk-QZHKN3VN-Cd86CYHV.js → chunk-QZHKN3VN-C58yD7lH.js} +1 -1
  39. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-DGZqU3iA.js +1 -0
  40. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-DGZqU3iA.js +1 -0
  41. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-Dc6cP9WW.js → cose-bilkent-S5V4N54A-BpvdK03m.js} +1 -1
  42. package/dist/web-ui/assets/{dagre-BM42HDAG-4b0Wf_6D.js → dagre-BM42HDAG-CZ1K-KD5.js} +1 -1
  43. package/dist/web-ui/assets/{diagram-2AECGRRQ-zS_j1Kf4.js → diagram-2AECGRRQ-D136Ok1V.js} +1 -1
  44. package/dist/web-ui/assets/{diagram-5GNKFQAL-CPo-_Ime.js → diagram-5GNKFQAL-Ji6qPYYV.js} +1 -1
  45. package/dist/web-ui/assets/{diagram-KO2AKTUF-CjHOA4_j.js → diagram-KO2AKTUF-B-s2RC-f.js} +1 -1
  46. package/dist/web-ui/assets/{diagram-LMA3HP47-CalZRF6K.js → diagram-LMA3HP47-COWaps70.js} +1 -1
  47. package/dist/web-ui/assets/{diagram-OG6HWLK6-DnLAhsLX.js → diagram-OG6HWLK6-bh6MvwWn.js} +1 -1
  48. package/dist/web-ui/assets/{docx-preview-uRVPnxwM.js → docx-preview-BRynUqJd.js} +1 -1
  49. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-L0nzlMSn.js → erDiagram-TEJ5UH35-DOPh2LlL.js} +1 -1
  50. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-Bdc3UwtW.js → flowDiagram-I6XJVG4X-B_kxDHIp.js} +1 -1
  51. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-CFRmj_qc.js → ganttDiagram-6RSMTGT7-DYBKHOkK.js} +1 -1
  52. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-B5hZwcoJ.js → gitGraphDiagram-PVQCEYII-D8_0BxLC.js} +1 -1
  53. package/dist/web-ui/assets/index-9SXWNIl0.css +1 -0
  54. package/dist/web-ui/assets/index-TAHyKznL.js +867 -0
  55. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-DVT4RgPd.js → infoDiagram-5YYISTIA-DayJP7Ws.js} +1 -1
  56. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-Bf7pvUY_.js → ishikawaDiagram-YF4QCWOH-vzxCYVSq.js} +1 -1
  57. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-NVRjJlnd.js → journeyDiagram-JHISSGLW-B-Fud82o.js} +1 -1
  58. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-Co7BKMut.js → kanban-definition-UN3LZRKU-DzuKdB65.js} +1 -1
  59. package/dist/web-ui/assets/{mermaid.core-CCf28Hq6.js → mermaid.core-D4ql87kI.js} +5 -5
  60. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-DepMhVEb.js → mindmap-definition-RKZ34NQL-DosvXt2g.js} +1 -1
  61. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-Cq9ANaI0.js → pieDiagram-4H26LBE5-DhXtMWhr.js} +1 -1
  62. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-CUY0BWhQ.js → quadrantDiagram-W4KKPZXB-D33pLLOq.js} +1 -1
  63. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-D9fU5rCm.js → requirementDiagram-4Y6WPE33-B-iIz-XM.js} +1 -1
  64. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-CMHhuSQF.js → sankeyDiagram-5OEKKPKP-BMd9AFEW.js} +1 -1
  65. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-Bjx53SID.js → sequenceDiagram-3UESZ5HK-CI1MIdwo.js} +1 -1
  66. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-DVvatKnO.js → stateDiagram-AJRCARHV-Bq6FKPW2.js} +1 -1
  67. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-8nMhmWY5.js +1 -0
  68. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-9I80LG9m.js → timeline-definition-PNZ67QCA-BDdmmSRo.js} +1 -1
  69. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-B82Deutq.js → vennDiagram-CIIHVFJN-DP2q5vY2.js} +1 -1
  70. package/dist/web-ui/assets/{wardley-L42UT6IY-BKXtp57W.js → wardley-L42UT6IY-Bw3fjszD.js} +1 -1
  71. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-DzqTzfYa.js → wardleyDiagram-YWT4CUSO-37bQUocJ.js} +1 -1
  72. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-TowyDWYu.js → xychartDiagram-2RQKCTM6-DnLDZyNC.js} +1 -1
  73. package/dist/web-ui/index.html +2 -2
  74. package/docs/README.md +50 -16
  75. package/docs/api/guides/websocket.md +43 -0
  76. package/docs/api/reference.md +657 -0
  77. package/docs/architecture/a2a-communication.md +303 -0
  78. package/docs/architecture/agent-runtime.md +145 -28
  79. package/docs/architecture/architecture.md +30 -11
  80. package/docs/architecture/cognitive-architecture.md +189 -15
  81. package/docs/architecture/concurrent-processing.md +190 -31
  82. package/docs/architecture/context-assembly.md +264 -0
  83. package/docs/architecture/derived-views.md +463 -0
  84. package/docs/architecture/desktop-auto-update.md +185 -0
  85. package/docs/architecture/facts.md +406 -0
  86. package/docs/architecture/learning-loop.md +11 -0
  87. package/docs/architecture/limits.md +79 -0
  88. package/docs/architecture/mailbox-system.md +786 -668
  89. package/docs/architecture/memory-system.md +1 -1
  90. package/docs/architecture/messaging-gateway.md +7 -0
  91. package/docs/architecture/notification-delivery.md +221 -0
  92. package/docs/architecture/notification-sounds.md +177 -0
  93. package/docs/architecture/prompt-engineering.md +171 -700
  94. package/docs/{design/remote-access-contract.md → architecture/remote-access.md} +4 -0
  95. package/docs/architecture/state-machines.md +288 -5
  96. package/docs/architecture/tool-loop-harness.md +362 -0
  97. package/docs/architecture/tool-system.md +40 -16
  98. package/docs/design/background-callback-in-turn-delivery-2026-11-22.md +95 -0
  99. package/docs/design/c10-0b-pick-identity-leak-2026-11-22.md +233 -0
  100. package/docs/design/c10-a-identity-columns-2026-11-22.md +182 -0
  101. package/docs/design/c10-c-trust-boundary-2026-11-23.md +222 -0
  102. package/docs/design/c10-external-adapters-plan-2026-11-19.md +448 -0
  103. package/docs/design/c8-residual-mechanisms-2026-11-15.md +984 -0
  104. package/docs/design/external-signal-decision-loop-2026-11-25.md +579 -0
  105. package/docs/guides/development.md +1 -1
  106. package/docs/{architecture → guides}/mailbox-audit-checklist.md +7 -0
  107. package/docs/guides/remote-access.md +1 -1
  108. package/docs/{design/agent-stop-intent-audit.md → records/agent-stop-intent-audit-2026-11-08.md} +4 -0
  109. package/docs/records/c10-l5-gate-verification-2026-11-26.md +72 -0
  110. package/docs/records/c10-l5-live-verification-2026-11-25.md +117 -0
  111. package/docs/records/cut6-c4-verification-2026-11-12.md +268 -0
  112. package/docs/records/cut6-mailbox-address-envelope-design-2026-11-12.md +871 -0
  113. package/docs/records/cut7-c7a-red-green-evidence-2026-11-13.md +105 -0
  114. package/docs/records/cut7-c7a-workunit-implementation-2026-11-13.md +116 -0
  115. package/docs/records/cut7-c7b-verification-2026-11-14.md +90 -0
  116. package/docs/records/cut7-live-verification-2026-11-14.md +33 -0
  117. package/docs/records/cut7-wiring-negative-cache-2026-11-14.md +64 -0
  118. package/docs/records/cut7-workunit-execution-plan-2026-11-13.md +206 -0
  119. package/docs/records/cut8-a-entity-keys-design-2026-11-14.md +377 -0
  120. package/docs/records/cut8-b-turn-delta-injection-2026-11-14.md +362 -0
  121. package/docs/records/cut8-c-single-clock-2026-11-14.md +119 -0
  122. package/docs/records/cut8-c-single-clock-design-2026-11-14.md +150 -0
  123. package/docs/records/cut8-d-2026-11-14.md +231 -0
  124. package/docs/records/cut8-live-verification-2026-11-14.md +1018 -0
  125. package/docs/records/cut9-adjacent-identity-paths-2026-11-15.md +200 -0
  126. package/docs/records/cut9-identity-declaration-2026-11-15.md +163 -0
  127. package/docs/records/cut9-inbox-dual-run-diff-2026-11-15.md +117 -0
  128. package/docs/records/cut9-live-verification-2026-11-15.md +222 -0
  129. package/docs/records/cut9-runtime-probe-2026-11-19.md +520 -0
  130. package/docs/{design/deliverable-sharing.md → records/deliverable-sharing-2026-08-12.md} +10 -3
  131. package/docs/records/identity-backlog-disposition-2026-11-22.md +143 -0
  132. package/docs/records/marketplace-orphan-freeze-2026-11-22.md +239 -0
  133. package/docs/{architecture/notify-user-context-truth.md → records/notify-user-context-truth-2026-10-28.md} +6 -0
  134. package/docs/{handoff → records}/remote-access-handoff.md +1 -1
  135. package/package.json +1 -1
  136. package/templates/roles/HANDBOOK.md +1 -1
  137. package/templates/skills/agent-building/SKILL.md +1 -1
  138. package/dist/web-ui/assets/ChatComponents-DTB3H_n2.js +0 -12
  139. package/dist/web-ui/assets/DeliverableShareModal-BwZP39nd.js +0 -1
  140. package/dist/web-ui/assets/MarkdownMessage-DVfFMzM9.js +0 -4
  141. package/dist/web-ui/assets/Settings-DTUjLhJY.js +0 -8
  142. package/dist/web-ui/assets/Switch-RmZHA47D.js +0 -1
  143. package/dist/web-ui/assets/Team-BRgI1zM9.js +0 -85
  144. package/dist/web-ui/assets/Work-nah0UYFz.js +0 -142
  145. package/dist/web-ui/assets/channel-s7K3KXLr.js +0 -1
  146. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-B2mHhFY8.js +0 -1
  147. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-B2mHhFY8.js +0 -1
  148. package/dist/web-ui/assets/index-CzHSs0Vd.css +0 -1
  149. package/dist/web-ui/assets/index-TPf50ZeO.js +0 -867
  150. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-92MmE2MZ.js +0 -1
  151. package/docs/api/api.md +0 -353
  152. package/docs/architecture/llm-provider-timeouts.md +0 -60
  153. package/docs/architecture/state-ownership.md +0 -83
  154. /package/docs/architecture/{frontend/team-chat.md → team-chat.md} +0 -0
  155. /package/docs/{analysis → records}/2026-10-29-a2a-cache-hit-rate.md +0 -0
  156. /package/docs/{fixes → records}/2026-11-12-session-expiry-and-mention-thinking.md +0 -0
  157. /package/docs/{handoff → records}/approval-tri-state-handoff.md +0 -0
  158. /package/docs/{design → records}/overview-attention-redesign.md +0 -0
  159. /package/docs/{remote-access/fast-path-plan.md → records/remote-access-fast-path-plan-2026-10-17.md} +0 -0
@@ -3,11 +3,12 @@ import { existsSync, readFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { createRequire } from 'node:module';
5
5
  import { allTemplateDirs, resolveTemplatesDir, resolveWebUiDir } from '../paths.js';
6
- import { loadConfig, saveConfig, getDefaultConfigPath, createLogger, closeRuntimeLogger, checkForUpdate, installCrashGuard, markRunStarted, markCleanShutdown, memoryWatermarkWatchdog, detectUncleanShutdown, APP_VERSION, userId, PROVIDERS, resolveJwtSecret, resolveGatewaySecret, pickOrgSecretary, setEnvValue, resolveActionSecret, resolveHostLocale, installEgress, } from '@markus/shared';
7
- import { AgentManager, LLMRouter, LLMLogger, ModelCatalogService, RoleLoader, createDefaultSkillRegistry, ExternalAgentGateway, proxyFetch, } from '@markus/core';
8
- import { OrganizationService, TaskService, APIServer, HITLService, ApprovalApplier, routeRecordedDecision, BillingService, LicenseService, TelemetryService, AuditService, ProjectService, RequirementService, KnowledgeService, FileKnowledgeStore, DeliverableService, KnowledgeSyncService, ReportService, TrustService, ArchiveService, StaleDetector, ScheduledTaskRunner, initStorage, searchRegistries, installSkill, importSkillFromDirectory, WorkflowService, WorkflowRunner, WorkflowScheduler, loadPlatformBindings, readStoredPlatformConfig, isAnswerableByTap, recordInstanceVerification, } from '@markus/org-manager';
6
+ import { loadConfig, saveConfig, getDefaultConfigPath, createLogger, closeRuntimeLogger, checkForUpdate, installCrashGuard, markRunStarted, markCleanShutdown, memoryWatermarkWatchdog, detectUncleanShutdown, APP_VERSION, userId, PROVIDERS, resolveJwtSecret, resolveGatewaySecret, pickOrgSecretary, setEnvValue, resolveActionSecret, resolveHostLocale, installEgress, catchAllTargetOf, } from '@markus/shared';
7
+ import { AgentManager, LLMRouter, LLMLogger, ModelCatalogService, RoleLoader, createDefaultSkillRegistry, ExternalAgentGateway, proxyFetch, rehydrateStructuredFields, } from '@markus/core';
8
+ import { OrganizationService, TaskService, APIServer, HITLService, ApprovalApplier, routeRecordedDecision, BillingService, LicenseService, TelemetryService, AuditService, ProjectService, RequirementService, KnowledgeService, FileKnowledgeStore, DeliverableService, KnowledgeSyncService, ReportService, TrustService, ArchiveService, StaleDetector, ScheduledTaskRunner, initStorage, searchRegistries, installSkill, importSkillFromDirectory, WorkflowService, WorkflowRunner, WorkflowScheduler, loadPlatformBindings, readStoredPlatformConfig, isAnswerableByTap, recordInstanceVerification, ExternalSourceService, } from '@markus/org-manager';
9
9
  import { MessageRouter, PLATFORM_MANIFESTS, setHttpFetch, getManifest, RepoBindingLookup, MAIN_CONVERSATION_KEY, resolveCardActionValue, ConnectionTestRegistry } from '@markus/comms';
10
10
  import { setupOutboundDispatch } from './outbound.js';
11
+ import { buildImInboundOrigin, buildImInboundWorkUnitRef } from './im-inbound-origin.js';
11
12
  import { buildApprovalCardResolution, cardActorFields, scheduleCardRewrite } from './approval-card.js';
12
13
  import { initStartupLogger, startupLog, startupBlank, startupSection, closeStartupLogger, getStartupLogFile } from '../utils/logger.js';
13
14
  import { openBrowserAfterHealthCheck } from '../utils/browser.js';
@@ -587,6 +588,11 @@ export async function createServices(config) {
587
588
  if (typeof config.agent?.maxPendingTasksPerAgent === 'number') {
588
589
  agentManager.maxPendingTasksPerAgent = config.agent.maxPendingTasksPerAgent;
589
590
  }
591
+ // 每个 agent 的待审需求提案上限(同一个「每 agent 待办队列」策略族)。
592
+ // 必须读回,否则设置页存了 markus.json 但重启后失效 —— 「改了没用」类缺陷。
593
+ if (typeof config.agent?.maxPendingRequirementProposals === 'number') {
594
+ agentManager.maxPendingRequirementProposals = config.agent.maxPendingRequirementProposals;
595
+ }
590
596
  if (config.codingTools) {
591
597
  agentManager.setCodingToolsConfig(config.codingTools);
592
598
  }
@@ -994,38 +1000,51 @@ async function startServerCore(config, values, opts) {
994
1000
  const archiveService = new ArchiveService(taskService, projectService);
995
1001
  archiveService.setRequirementService(requirementService);
996
1002
  archiveService.start();
997
- // Stale task detection: alert humans when tasks are stuck in review/in_progress/pending
1003
+ // Stale task detection. Scope (Owner 2026-11-18): the ONLY things this periodic
1004
+ // scan may surface are (a) `stuck_task` → one human notification, and
1005
+ // (b) `review_reminder` → a message to the RESPONSIBLE REVIEWER agent.
1006
+ //
1007
+ // Removed on purpose: the timed "Stale review" human notification (a card waiting on
1008
+ // a NAMED reviewer does not need the whole org pinged on a clock), and the human
1009
+ // fallback when a reviewer is unreachable (it surfaced as "Unstarted task", wrong on
1010
+ // both counts — not unstarted, and not the reader's job). A reminder that cannot be
1011
+ // delivered is logged and dropped; it never becomes a human notification.
998
1012
  const staleDetector = new StaleDetector(taskService, undefined, (items) => {
999
1013
  for (const item of items) {
1000
- // A review reminder belongs to the REVIEWER, not to a human. The 2026-10-17
1001
- // failure was exactly this inversion: nobody able to act was ever told, and the
1002
- // only signal fired 12h later into the human's bell. Wake the owner of the step
1003
- // first; escalate to a human only if that agent cannot be reached.
1004
- if (item.type === 'review_reminder' && item.agentId) {
1014
+ if (item.type === 'review_reminder') {
1015
+ if (!item.agentId) {
1016
+ log.warn('Review reminder has no reviewer to wake — dropped (no human escalation)', {
1017
+ taskId: item.taskId,
1018
+ });
1019
+ continue;
1020
+ }
1005
1021
  try {
1006
1022
  const reviewer = agentManager.getAgent(item.agentId);
1007
1023
  void reviewer
1008
1024
  .sendMessage(item.message, undefined, undefined, {
1009
1025
  sourceType: 'review_request',
1026
+ // 评审提醒 = 评审回合(mailboxScenario('review_request') = 'review')。
1027
+ scenario: 'review',
1010
1028
  ...(item.taskId ? { taskId: item.taskId } : {}),
1011
1029
  })
1012
1030
  .catch((err) => log.warn('Review reminder delivery failed', { taskId: item.taskId, error: String(err) }));
1013
- continue;
1014
1031
  }
1015
1032
  catch (err) {
1016
- log.warn('Reviewer unavailable for reminder — escalating to human', {
1033
+ log.warn('Reviewer unavailable for reminder — dropped (no human escalation)', {
1017
1034
  agentId: item.agentId,
1018
1035
  taskId: item.taskId,
1019
1036
  error: String(err),
1020
1037
  });
1021
1038
  }
1039
+ continue;
1022
1040
  }
1041
+ // Only `stuck_task` reaches the human notification list.
1023
1042
  hitlService.notify({
1024
1043
  targetUserId: 'all',
1025
1044
  type: 'system',
1026
- title: item.type === 'review_stale' ? 'Stale review' : item.type === 'stuck_task' ? 'Stuck task' : 'Unstarted task',
1045
+ title: 'Stuck task',
1027
1046
  body: item.message,
1028
- priority: item.type === 'review_stale' ? 'high' : 'normal',
1047
+ priority: 'normal',
1029
1048
  actionType: item.taskId ? 'navigate' : 'none',
1030
1049
  actionTarget: item.taskId ? JSON.stringify({ path: `/work?openTask=${item.taskId}` }) : undefined,
1031
1050
  metadata: {
@@ -1035,9 +1054,7 @@ async function startServerCore(config, values, opts) {
1035
1054
  // The title and body as structure: the detector knows *what* to say,
1036
1055
  // this is the only place that knows the sentence's key.
1037
1056
  i18n: {
1038
- titleKey: item.type === 'review_stale'
1039
- ? 'notifications.titles.staleReview'
1040
- : 'notifications.titles.stuckTask',
1057
+ titleKey: 'notifications.titles.stuckTask',
1041
1058
  ...(item.i18n ?? {}),
1042
1059
  },
1043
1060
  },
@@ -1098,6 +1115,9 @@ async function startServerCore(config, values, opts) {
1098
1115
  orgService.addHumanUser(firstOrgId, 'Owner', 'owner', { id: ownerUserId });
1099
1116
  }
1100
1117
  }
1118
+ // 第七刀 C7 的装配已在 `APIServer.setStorage()` 里完成(单一执行点)。
1119
+ // 这里**不再重复**:装配写在启动文件里就必然有第二个启动路径(桌面端走
1120
+ // `cli/backend.ts#startBackend`)漏掉 —— 2026-11-14 真机事故的成因。
1101
1121
  // Seed default team + Secretary agent (runs for both DB and in-memory mode)
1102
1122
  await orgService.seedDefaultTeam(firstOrgId, ownerUserId);
1103
1123
  // Register builder context providers on agents with building skills (e.g. Secretary)
@@ -1208,6 +1228,12 @@ async function startServerCore(config, values, opts) {
1208
1228
  allowFreeform: opts.allowFreeform,
1209
1229
  questions: opts.questions,
1210
1230
  details: { priority: opts.priority, taskId: opts.relatedTaskId, taskTitle },
1231
+ // This装配点 is reached ONLY from the agent's `request_user_input` /
1232
+ // `request_user_approval` tool (see core/agent.ts — it is the only caller of
1233
+ // `userApprovalRequester`), so the ask is a question to the human, not a gate
1234
+ // decision applied to a target. Tagging it here is what lets consumers tell
1235
+ // the two apart without guessing from the payload shape.
1236
+ askKind: 'input',
1211
1237
  });
1212
1238
  });
1213
1239
  // Wire user notifier through HITL service
@@ -1875,6 +1901,8 @@ async function startServerCore(config, values, opts) {
1875
1901
  taskId: activity.taskId,
1876
1902
  mailboxItemId: activity.mailboxItemId,
1877
1903
  startedAt: activity.startedAt,
1904
+ // C9-B:身份由生产者带入(回合的 WorkUnit ref),不在这里反推。
1905
+ workUnitRef: activity.workUnitRef ?? null,
1878
1906
  });
1879
1907
  }
1880
1908
  catch (err) {
@@ -1892,6 +1920,8 @@ async function startServerCore(config, values, opts) {
1892
1920
  type: data.type,
1893
1921
  content: data.content,
1894
1922
  metadata: data.metadata,
1923
+ // C9-B:与所属 activity 同一个 ref(同一回合身份,不在读路径再猜)。
1924
+ workUnitRef: data.workUnitRef ?? null,
1895
1925
  });
1896
1926
  }
1897
1927
  catch (err) {
@@ -1907,7 +1937,8 @@ async function startServerCore(config, values, opts) {
1907
1937
  },
1908
1938
  onEnd: (activityId, summary) => {
1909
1939
  try {
1910
- actRepo.updateActivity(activityId, summary);
1940
+ // C10-0E:结束不是改写活动行,而是追加一条 activity_end 事件(append-only)。
1941
+ actRepo.appendActivityEnd(activityId, summary);
1911
1942
  }
1912
1943
  catch (err) {
1913
1944
  log.warn('Failed to persist activity end', { activityId, error: String(err) });
@@ -1937,6 +1968,82 @@ async function startServerCore(config, values, opts) {
1937
1968
  if (storage?.chatSessionRepo) {
1938
1969
  agentManager.setSessionRepo(storage.chatSessionRepo);
1939
1970
  }
1971
+ // 邮箱地址自助工具(第六刀 C1):把 storage 的唯一写者/解析器接进 Agent 工具面。
1972
+ // 未接线 ⇒ 工具不注册(见 AgentManager.setAddressBindingPort 的说明)。
1973
+ if (storage?.addressBindingRepo) {
1974
+ const addressRepo = storage.addressBindingRepo;
1975
+ agentManager.setAddressBindingPort({
1976
+ bind: (input) => addressRepo.bind(input),
1977
+ revoke: (input) => addressRepo.revoke(input),
1978
+ list: (input) => addressRepo.listVisible(input),
1979
+ });
1980
+ }
1981
+ // C10-D:组织身份 / 余额查询工具(org_info / org_list / org_usage)。
1982
+ // info+list 读本地投影(唯一写者 = SqliteOrgRepo);余额走 apiServer.getOrgUsage,
1983
+ // 它只搬运 hub 的单一实现,不在本地重算「月配额+购买+赠送-已用」。
1984
+ // 未接线 ⇒ 工具不注册(与地址工具同一惰性纪律)。
1985
+ if (storage?.orgRepo) {
1986
+ const orgRepo = storage.orgRepo;
1987
+ const toView = (o) => ({
1988
+ id: o.id,
1989
+ name: o.name,
1990
+ orgSlug: o.orgSlug ?? null,
1991
+ hubOrgId: o.hubOrgId ?? null,
1992
+ plan: o.plan ?? 'free',
1993
+ hubSyncedAt: o.hubSyncedAt ?? null,
1994
+ addressCount: orgRepo.countBoundAddresses(o.id),
1995
+ });
1996
+ agentManager.setOrgQueryPort({
1997
+ info: ({ orgId }) => {
1998
+ const org = orgRepo.findOrgById(orgId);
1999
+ return org ? toView(org) : null;
2000
+ },
2001
+ list: () => orgRepo.listOrgs().map(toView),
2002
+ usage: ({ orgId }) => apiServer.getOrgUsage(orgId),
2003
+ });
2004
+ }
2005
+ // C10-B:外部信号源(webhook/RSS)—— 地址簿 lookup + 自助工具 + 唯一 ingest 服务 + RSS 轮询。
2006
+ // 未接线(缺 repo)⇒ 工具不注册、路由 503(同 address-tools 惰性纪律,不注册空能力)。
2007
+ if (storage?.addressBindingRepo && storage?.externalSourceRepo) {
2008
+ const addressRepo = storage.addressBindingRepo;
2009
+ const sourceRepo = storage.externalSourceRepo;
2010
+ const findActive = (addr) => {
2011
+ const row = addressRepo.findActive(addr);
2012
+ return row ? { agentId: row.agentId, targetRef: row.targetRef } : undefined;
2013
+ };
2014
+ // D8:地址簿只读端口接进每 agent mailbox(外部信号路由跟绑定走,不跟源主走)。
2015
+ agentManager.setAddressLookup({ findActive });
2016
+ const externalSourceService = new ExternalSourceService({
2017
+ sources: sourceRepo,
2018
+ findActive,
2019
+ mailboxOf: (agentId) => {
2020
+ try {
2021
+ return agentManager.getAgent(agentId)?.getMailbox();
2022
+ }
2023
+ catch {
2024
+ return undefined;
2025
+ }
2026
+ },
2027
+ // C10-F:组织级入站策略的现读口(org-manager 只做决策,不自己持库)。
2028
+ // 缺行 / 缺列 ⇒ 'off':失败关闭,与列默认值一致。
2029
+ ingressPolicy: (orgId) => {
2030
+ const row = storage.orgRepo.findOrgById(orgId);
2031
+ const policy = row?.externalIngress;
2032
+ return policy === 'accept' || policy === 'observe' ? policy : 'off';
2033
+ },
2034
+ });
2035
+ // 工具端口:归属裁决在 service(org-manager 唯一写者),core 工具面只翻译表面语义。
2036
+ agentManager.setExternalSourcePort({
2037
+ register: (input) => externalSourceService.registerSource(input),
2038
+ list: (input) => ({
2039
+ policy: externalSourceService.policyOf(input.orgId),
2040
+ sources: externalSourceService.listSources(input.orgId, input.agentId),
2041
+ }),
2042
+ toggle: (input) => externalSourceService.setSourceEnabled(input),
2043
+ });
2044
+ apiServer.setExternalSourceService(externalSourceService);
2045
+ externalSourceService.startPolling();
2046
+ }
1940
2047
  // Wire mailbox + decision persistence to SQLite
1941
2048
  if (storage?.mailboxRepo && storage?.decisionRepo) {
1942
2049
  const mbRepo = storage.mailboxRepo;
@@ -1949,12 +2056,31 @@ async function startServerCore(config, values, opts) {
1949
2056
  save: (item, dedupKey) => {
1950
2057
  try {
1951
2058
  const inserted = mbRepo.save({
2059
+ // C8 第七层根因:这里是**手写字段列举**,列到 `dropReason` 就结束 ——
2060
+ // 以后每加一个字段(本轮就是 `workUnitRef`)都会被静默丢掉,而两端
2061
+ // “看起来都对”。改成展开 + 覆盖:新字段自动流过,只显式覆盖需要
2062
+ // 转型的那几个(信封序列化、结构投影)。
2063
+ ...item,
1952
2064
  id: item.id, agentId: item.agentId, sourceType: item.sourceType,
1953
2065
  priority: item.priority, status: item.status,
1954
2066
  payload: item.payload,
1955
2067
  metadata: (item.metadata ?? {}),
1956
2068
  queuedAt: item.queuedAt,
1957
2069
  dedupKey,
2070
+ // 第六刀 C2:信封与它的结构投影一起落库(单一写入点)。
2071
+ envelope: item.envelope ? JSON.stringify(item.envelope) : null,
2072
+ messageId: item.envelope?.messageId ?? null,
2073
+ signalClass: item.envelope?.signalClass ?? null,
2074
+ intent: item.envelope?.intent ?? null,
2075
+ dropReason: item.dropReason ?? null,
2076
+ // C8 第七层:**适配器也得带身份**。
2077
+ //
2078
+ // 这一层是 core → storage 的手写字段映射,之前只写到 `dropReason` 就结束,
2079
+ // `workUnitRef` 在这里被丢掉。后果:task-service / requirement-service /
2080
+ // enqueueFor 全都“传对了”,save() 也“会写了”,但真机落库仍是 NULL ——
2081
+ // 取消投递行带着 `invalidatesPremise:true` 却没有身份,delta 永远匹配不到。
2082
+ // 2026-11-14 三次重建都没发现,就是因为只看两端、没人看中间的搬运层。
2083
+ workUnitRef: item.workUnitRef ?? null,
1958
2084
  });
1959
2085
  if (!inserted) {
1960
2086
  // P0 幂等键:重复投递(同 agent + 同 dedup_key)被 DB 拒绝,不产生第二行。
@@ -1980,7 +2106,7 @@ async function startServerCore(config, values, opts) {
1980
2106
  log.warn('Failed to update mailbox status', { itemId, error: String(e) });
1981
2107
  }
1982
2108
  },
1983
- markStaleProcessingAsDropped: (aid, nowIso, ownerId) => mbRepo.markStaleProcessingAsDropped(aid, nowIso, ownerId),
2109
+ markStaleProcessingAsBounced: (aid, nowIso, ownerId) => mbRepo.markStaleProcessingAsBounced(aid, nowIso, ownerId),
1984
2110
  loadQueued: (aid) => {
1985
2111
  const rows = mbRepo.getByAgent(aid, { status: 'queued' });
1986
2112
  return rows.map((r) => ({
@@ -1991,6 +2117,8 @@ async function startServerCore(config, values, opts) {
1991
2117
  status: r.status,
1992
2118
  payload: r.payload,
1993
2119
  metadata: r.metadata,
2120
+ // C2:信封/轮次结构字段(含旧行唯一一次回填解码,见 rehydrateStructuredFields)
2121
+ ...rehydrateStructuredFields(r),
1994
2122
  queuedAt: r.queuedAt,
1995
2123
  startedAt: r.startedAt ?? undefined,
1996
2124
  completedAt: r.completedAt ?? undefined,
@@ -2009,6 +2137,8 @@ async function startServerCore(config, values, opts) {
2009
2137
  status: r.status,
2010
2138
  payload: r.payload,
2011
2139
  metadata: r.metadata,
2140
+ // C2:同 loadQueued(同一解码函数,不写第二份)。
2141
+ ...rehydrateStructuredFields(r),
2012
2142
  queuedAt: r.queuedAt,
2013
2143
  startedAt: r.startedAt ?? undefined,
2014
2144
  completedAt: r.completedAt ?? undefined,
@@ -2029,10 +2159,43 @@ async function startServerCore(config, values, opts) {
2029
2159
  requeueItem: (itemId, opts) => mbRepo.requeueItem(itemId, opts),
2030
2160
  // findByDedupKey:只读,供 mailbox 三态判定(新增/幂等抑制/复用原行回队)取既有行状态。
2031
2161
  findByDedupKey: (aid, dedupKey) => mbRepo.findByDedupKey(aid, dedupKey),
2162
+ // ── 第六刀 C2:信封幂等(V5)与退信行写入 ────────────────────────
2163
+ // findByMessageId:同一 messageId 已在队/已收口 → mailbox 写一条
2164
+ // `duplicate_message_id` 退信行后返回(不再静默 suppressed)。
2165
+ findByMessageId: (aid, messageId) => mbRepo.findByMessageId(aid, messageId),
2166
+ saveBounced: (item, dropReason) => {
2167
+ try {
2168
+ mbRepo.save({
2169
+ id: item.id, agentId: item.agentId, sourceType: item.sourceType,
2170
+ priority: item.priority, status: 'bounced',
2171
+ payload: item.payload,
2172
+ metadata: (item.metadata ?? {}),
2173
+ queuedAt: item.queuedAt,
2174
+ dedupKey: undefined,
2175
+ envelope: item.envelope ? JSON.stringify(item.envelope) : null,
2176
+ // 退信行**不占** messageId 唯一键(它记录的是“这次没进去”,
2177
+ // 不是同一条消息的第二份)——见 uq_mailbox_agent_message 的谓词。
2178
+ messageId: null,
2179
+ signalClass: item.envelope?.signalClass ?? null,
2180
+ intent: item.envelope?.intent ?? null,
2181
+ dropReason,
2182
+ // 第六刀 C3:退信行直接带上归集桶(构造时就已确定,不靠后续 UPDATE 补)。
2183
+ bounceTarget: catchAllTargetOf(agentId),
2184
+ });
2185
+ }
2186
+ catch (e) {
2187
+ log.warn('Failed to persist bounced mailbox item', { id: item.id, dropReason, error: String(e) });
2188
+ }
2189
+ },
2190
+ // 第六刀 C3:路由取证 / catch-all 概览(工具面的两个只读端口)。
2191
+ findRouteByMessageId: (aid, messageId) => mbRepo.findRouteByMessageId(aid, messageId),
2192
+ listCatchAll: (aid, limit) => mbRepo.listCatchAll(aid, limit),
2193
+ // ghost drop 读真实状态,让状态机矩阵能裁制它(不盲写)。
2194
+ getStatus: (id) => mbRepo.getStatus(id),
2032
2195
  });
2033
- const { dropped, restored, expired, merged } = mailbox.recoverStaleItems();
2034
- if (dropped > 0 || restored > 0 || expired > 0 || merged > 0)
2035
- log.info('Mailbox recovery on startup', { agentId, dropped, restored, expired, merged });
2196
+ const { bounced, restored, expired, merged } = mailbox.recoverStaleItems();
2197
+ if (bounced > 0 || restored > 0 || expired > 0 || merged > 0)
2198
+ log.info('Mailbox recovery on startup', { agentId, bounced, restored, expired, merged });
2036
2199
  agent.getAttentionController().setDecisionPersistence({
2037
2200
  save: (decision) => {
2038
2201
  try {
@@ -2042,6 +2205,13 @@ async function startServerCore(config, values, opts) {
2042
2205
  context: decision.context,
2043
2206
  reasoning: decision.reasoning ?? '',
2044
2207
  outcome: decision.outcome,
2208
+ // 身份与判断来源必须一起穿过这一层。此前这里逐字段手抄却漏了
2209
+ // workUnitRef —— 上游 recordDecision 写了、下游 INSERT 也有列,
2210
+ // 唯独中间的适配器把它丢掉,于是 22.7 万条决策 0 条能回溯到回合
2211
+ //(2026-11-18 实测)。字段在两端都存在,不代表它穿得过中间。
2212
+ workUnitRef: decision.workUnitRef ?? null,
2213
+ source: decision.source,
2214
+ overrode: decision.overrode,
2045
2215
  createdAt: decision.createdAt,
2046
2216
  });
2047
2217
  }
@@ -2050,30 +2220,12 @@ async function startServerCore(config, values, opts) {
2050
2220
  }
2051
2221
  },
2052
2222
  });
2053
- // Wire LLM interrupt judge — evaluates whether to preempt current
2054
- // work when a new message arrives (e.g. "stop publishing", "pause that task").
2055
- // Only called when heuristics return 'continue' for ambiguous cases.
2056
- const triageProvider = agent.config.llmConfig?.modelMode === 'custom'
2057
- ? agent.config.llmConfig.primary : undefined;
2058
- const interruptSystemPrompt = 'You are an attention interrupt judge. Decide whether to interrupt current work for a new incoming message. Reply with ONLY one word: continue, preempt, cancel, merge, or defer. Use "preempt" to pause (resume later) and "cancel" to permanently stop current work.';
2059
- const interruptCacheSegments = [{ content: interruptSystemPrompt, cacheBreakpoint: true }];
2060
- agent.getAttentionController().setLLMJudge(async (prompt) => {
2061
- const response = await llmRouter.chat({
2062
- messages: [
2063
- { role: 'system', content: interruptSystemPrompt },
2064
- { role: 'user', content: prompt },
2065
- ],
2066
- systemCacheSegments: interruptCacheSegments,
2067
- temperature: 0.1,
2068
- // No maxTokens cap: a tight cap (e.g. 32) is fully consumed by a
2069
- // reasoning model's hidden reasoning, leaving content empty so the
2070
- // judge always degrades to 'continue'. The router fills the model's
2071
- // real limit; the one-word answer stops the generation naturally.
2072
- }, triageProvider);
2073
- const raw = response.content.trim().toLowerCase();
2074
- const valid = ['continue', 'preempt', 'cancel', 'merge', 'defer'];
2075
- return valid.includes(raw) ? raw : 'continue';
2076
- });
2223
+ // Interrupt decisions are purely heuristic (priority + type). There is
2224
+ // deliberately no LLM judge here: "should I pause this work for that
2225
+ // message?" is a decidable rule question, not a reasoning question.
2226
+ // The old wiring paid a model call on every same-priority interrupt and
2227
+ // could only answer 'continue' when the model produced no content —
2228
+ // a silent degradation nobody could observe.
2077
2229
  }
2078
2230
  catch { /* agent not found */ }
2079
2231
  };
@@ -2229,7 +2381,20 @@ async function startServerCore(config, values, opts) {
2229
2381
  // session. A channel designated `main` maps to the agent's own main session
2230
2382
  // (no per-channel key).
2231
2383
  const channelKey = target.conversationKey === MAIN_CONVERSATION_KEY ? undefined : target.conversationKey;
2232
- const reply = await agent.sendMessage(message.content.text ?? '', message.senderId, undefined, { channelKey });
2384
+ const reply = await agent.sendMessage(message.content.text ?? '', message.senderId, undefined, {
2385
+ // IM 入站 = 外部人类发来的消息 → 聊天回合(显式表态)。
2386
+ scenario: 'chat',
2387
+ channelKey,
2388
+ // 第六刀 C2(§2.3 投递点 1)+ C10-B2(S1):IM 入站信封头的唯一写者
2389
+ // 是 buildImInboundOrigin。messageId = 适配器在分派点 surface 的 native
2390
+ // id(飞书 om_*)→ 重投命中 V5 (agent, messageId) 去重;未 envelope 化
2391
+ // 的平台回退 message.id(原行为不变)。
2392
+ origin: buildImInboundOrigin(message),
2393
+ // C10-B2(S3):IM 入口入队前铸 per-message external ref(唯一 C10-B
2394
+ // 构造器),经 options.workUnitRef 传入 → 装配点 ensureIdentity 保证实体。
2395
+ // 与 Web UI prepareChatTurnWorkUnit / injectFollowUp 同一不变量:入口写 ref。
2396
+ workUnitRef: buildImInboundWorkUnitRef(message),
2397
+ });
2233
2398
  auditService.record({
2234
2399
  orgId: 'default',
2235
2400
  agentId,