@octopi-agent/engine 0.90.11 → 0.98.4

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 (246) hide show
  1. package/dist/config-admin/agent-presets.d.ts +70 -0
  2. package/dist/config-admin/agent-presets.js +243 -0
  3. package/dist/config-admin/discover.d.ts +30 -0
  4. package/dist/config-admin/discover.js +48 -0
  5. package/dist/config-admin/env.d.ts +22 -0
  6. package/dist/config-admin/env.js +41 -0
  7. package/dist/config-admin/index.d.ts +20 -0
  8. package/dist/config-admin/index.js +15 -0
  9. package/dist/config-admin/model-presets.d.ts +75 -0
  10. package/dist/config-admin/model-presets.js +249 -0
  11. package/dist/config-admin/name-guard.d.ts +14 -0
  12. package/dist/config-admin/name-guard.js +24 -0
  13. package/dist/config-admin/patch.d.ts +56 -0
  14. package/dist/config-admin/patch.js +201 -0
  15. package/dist/config-admin/port.d.ts +68 -0
  16. package/dist/config-admin/port.js +21 -0
  17. package/dist/config-admin/redact.d.ts +39 -0
  18. package/dist/config-admin/redact.js +42 -0
  19. package/dist/config-schema/agent.d.ts +45 -1
  20. package/dist/config-schema/context.d.ts +6 -1
  21. package/dist/config-schema/context.js +8 -0
  22. package/dist/config-schema/engine.d.ts +110 -4
  23. package/dist/config-schema/governance.d.ts +45 -1
  24. package/dist/config-schema/governance.js +187 -0
  25. package/dist/config-schema/models.d.ts +5 -2
  26. package/dist/config-schema/models.js +4 -1
  27. package/dist/config-schema/observability.d.ts +9 -0
  28. package/dist/config-schema/observability.js +29 -0
  29. package/dist/config-schema/run.d.ts +3 -0
  30. package/dist/config-schema/run.js +14 -0
  31. package/dist/config.d.ts +29 -4
  32. package/dist/config.js +15 -4
  33. package/dist/harness/activation/dispatcher.d.ts +8 -2
  34. package/dist/harness/activation/dispatcher.js +33 -5
  35. package/dist/harness/activation/inbox.d.ts +87 -0
  36. package/dist/harness/activation/inbox.js +169 -0
  37. package/dist/harness/activation/runtime.d.ts +9 -8
  38. package/dist/harness/activation/runtime.js +100 -8
  39. package/dist/harness/activation/types.d.ts +19 -0
  40. package/dist/harness/activation/types.js +2 -0
  41. package/dist/harness/agent/builder.d.ts +26 -1
  42. package/dist/harness/agent/builder.js +85 -37
  43. package/dist/harness/agent/config-bridge.d.ts +5 -0
  44. package/dist/harness/agent/config-bridge.js +3 -0
  45. package/dist/harness/agent/config-integrity.d.ts +138 -0
  46. package/dist/harness/agent/config-integrity.js +235 -0
  47. package/dist/harness/agent/wire-agent-builder.js +7 -1
  48. package/dist/harness/collaboration/autonomous-subsystem/index.d.ts +2 -2
  49. package/dist/harness/collaboration/autonomous-subsystem/index.js +1 -1
  50. package/dist/harness/collaboration/autonomous-subsystem/loader.js +3 -0
  51. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +19 -2
  52. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.d.ts +40 -0
  53. package/dist/harness/collaboration/autonomous-subsystem/think/completion-guard.js +59 -0
  54. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -1
  55. package/dist/harness/collaboration/autonomous-subsystem/think/index.d.ts +2 -0
  56. package/dist/harness/collaboration/autonomous-subsystem/think/index.js +1 -0
  57. package/dist/harness/collaboration/autonomous-subsystem/think/model-resolver.js +1 -1
  58. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +9 -0
  59. package/dist/harness/collaboration/delegation/child-run.js +21 -5
  60. package/dist/harness/collaboration/delegation/notifier.js +4 -3
  61. package/dist/harness/collaboration/delegation/service.js +2 -3
  62. package/dist/harness/collaboration/delegation/wiring.js +6 -5
  63. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.d.ts +1 -1
  64. package/dist/harness/collaboration/orchestration/reflector/llm-reflector.js +1 -1
  65. package/dist/harness/context/capabilities/compact/engine.d.ts +30 -0
  66. package/dist/harness/context/capabilities/compact/engine.js +198 -46
  67. package/dist/harness/context/capabilities/compact/handover.d.ts +78 -0
  68. package/dist/harness/context/capabilities/compact/handover.js +107 -0
  69. package/dist/harness/context/capabilities/compact/index.d.ts +3 -1
  70. package/dist/harness/context/capabilities/compact/index.js +2 -1
  71. package/dist/harness/context/capabilities/compact/types.d.ts +30 -1
  72. package/dist/harness/context/capabilities/summary/executor.js +2 -1
  73. package/dist/harness/context/capabilities/summary/policies.js +8 -5
  74. package/dist/harness/context/capabilities/summary/resolver.d.ts +1 -1
  75. package/dist/harness/context/capabilities/summary/resolver.js +4 -4
  76. package/dist/harness/context/capabilities/summary/types.d.ts +2 -2
  77. package/dist/harness/context/constitution/default-agents.md +11 -10
  78. package/dist/harness/context/default-context-engine.d.ts +34 -4
  79. package/dist/harness/context/default-context-engine.js +194 -49
  80. package/dist/harness/context/hybrid-compressor.js +6 -0
  81. package/dist/harness/context/layers.d.ts +2 -4
  82. package/dist/harness/context/layers.js +9 -11
  83. package/dist/harness/context/llm-summarizer.d.ts +2 -8
  84. package/dist/harness/context/llm-summarizer.js +69 -91
  85. package/dist/harness/context/message-selector.js +4 -3
  86. package/dist/harness/context/summarize.d.ts +3 -1
  87. package/dist/harness/context/summarize.js +9 -4
  88. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  89. package/dist/harness/context/system-prompt-assembler.js +1 -0
  90. package/dist/harness/context/truncate-compressor.js +7 -0
  91. package/dist/harness/context/turn-envelope.d.ts +3 -2
  92. package/dist/harness/context/turn-envelope.js +3 -2
  93. package/dist/harness/context/types.d.ts +33 -1
  94. package/dist/harness/extension/execution-environment/dangerous-commands.d.ts +28 -0
  95. package/dist/harness/extension/execution-environment/dangerous-commands.js +129 -0
  96. package/dist/harness/extension/execution-environment/effect-policy.d.ts +149 -8
  97. package/dist/harness/extension/execution-environment/effect-policy.js +274 -19
  98. package/dist/harness/extension/execution-environment/index.d.ts +4 -2
  99. package/dist/harness/extension/execution-environment/index.js +2 -1
  100. package/dist/harness/extension/execution-environment/kill-switch.d.ts +34 -0
  101. package/dist/harness/extension/execution-environment/kill-switch.js +46 -0
  102. package/dist/harness/extension/execution-environment/ops-audit.d.ts +204 -0
  103. package/dist/harness/extension/execution-environment/ops-audit.js +337 -0
  104. package/dist/harness/extension/execution-environment/privileged-exec.d.ts +158 -0
  105. package/dist/harness/extension/execution-environment/privileged-exec.js +418 -0
  106. package/dist/harness/extension/execution-environment/process-info.d.ts +180 -0
  107. package/dist/harness/extension/execution-environment/process-info.js +466 -0
  108. package/dist/harness/extension/execution-environment/process-isolation.d.ts +7 -0
  109. package/dist/harness/extension/execution-environment/process-isolation.js +9 -0
  110. package/dist/harness/extension/execution-environment/sandbox.d.ts +109 -0
  111. package/dist/harness/extension/execution-environment/sandbox.js +228 -21
  112. package/dist/harness/extension/execution-environment/tool-capabilities.d.ts +1 -1
  113. package/dist/harness/extension/execution-environment/tool-capabilities.js +6 -0
  114. package/dist/harness/extension/execution-environment/types.d.ts +19 -0
  115. package/dist/harness/extension/execution-environment/undo-log.d.ts +6 -2
  116. package/dist/harness/extension/execution-environment/undo-log.js +31 -10
  117. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +5 -0
  118. package/dist/harness/extension/plugin-ecosystem/tools/allowlisted-run.js +33 -0
  119. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.d.ts +4 -5
  120. package/dist/harness/extension/plugin-ecosystem/tools/ask-user.js +5 -15
  121. package/dist/harness/extension/plugin-ecosystem/tools/builtin.d.ts +3 -0
  122. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +70 -26
  123. package/dist/harness/extension/plugin-ecosystem/tools/document-tools.js +3 -9
  124. package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +3 -6
  125. package/dist/harness/extension/plugin-ecosystem/tools/file-ops.js +9 -5
  126. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +9 -130
  127. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +122 -14
  128. package/dist/harness/extension/plugin-ecosystem/tools/index.d.ts +2 -0
  129. package/dist/harness/extension/plugin-ecosystem/tools/index.js +2 -0
  130. package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +4 -13
  131. package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +25 -11
  132. package/dist/harness/extension/plugin-ecosystem/tools/platform.js +168 -62
  133. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.d.ts +43 -0
  134. package/dist/harness/extension/plugin-ecosystem/tools/privileged-tool.js +350 -0
  135. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.d.ts +30 -0
  136. package/dist/harness/extension/plugin-ecosystem/tools/process-tools.js +137 -0
  137. package/dist/harness/governance/human-in-the-loop/decision-cache.d.ts +54 -4
  138. package/dist/harness/governance/human-in-the-loop/decision-cache.js +42 -16
  139. package/dist/harness/governance/security/default-risk-policy.d.ts +1 -0
  140. package/dist/harness/governance/security/default-risk-policy.js +1 -0
  141. package/dist/harness/governance/security/default-security-guard.js +9 -0
  142. package/dist/harness/governance/security/index.d.ts +1 -0
  143. package/dist/harness/governance/security/index.js +2 -0
  144. package/dist/harness/governance/security/risk-evaluator.js +13 -0
  145. package/dist/harness/governance/security/risk-types.d.ts +12 -0
  146. package/dist/harness/governance/security/shell-parser-fallback.d.ts +29 -0
  147. package/dist/harness/governance/security/shell-parser-fallback.js +410 -0
  148. package/dist/harness/governance/security/shell-parser-shared.d.ts +83 -0
  149. package/dist/harness/governance/security/shell-parser-shared.js +188 -0
  150. package/dist/harness/governance/security/shell-parser-treesitter.d.ts +52 -0
  151. package/dist/harness/governance/security/shell-parser-treesitter.js +370 -0
  152. package/dist/harness/governance/security/shell-parser.d.ts +23 -10
  153. package/dist/harness/governance/security/shell-parser.js +37 -496
  154. package/dist/harness/governance/security/temp-path.d.ts +9 -0
  155. package/dist/harness/governance/security/temp-path.js +13 -2
  156. package/dist/harness/governance/security/vendor/README.md +24 -0
  157. package/dist/harness/governance/security/vendor/tree-sitter-bash.LICENSE.txt +21 -0
  158. package/dist/harness/governance/security/vendor/tree-sitter-bash.wasm +0 -0
  159. package/dist/harness/governance/session-acl/seed-roles.js +14 -0
  160. package/dist/harness/index.d.ts +2 -0
  161. package/dist/harness/index.js +2 -0
  162. package/dist/harness/knowledge/fts.js +1 -2
  163. package/dist/harness/knowledge/index-store.js +59 -9
  164. package/dist/harness/memory/index.d.ts +6 -2
  165. package/dist/harness/memory/index.js +4 -1
  166. package/dist/harness/memory/memory-events.d.ts +25 -0
  167. package/dist/harness/memory/memory-events.js +38 -0
  168. package/dist/harness/memory/sqlite/agent-db.js +15 -0
  169. package/dist/harness/memory/sqlite/keyword-search.d.ts +1 -0
  170. package/dist/harness/memory/sqlite/keyword-search.js +4 -3
  171. package/dist/harness/memory/sqlite/wisdom-store.d.ts +7 -2
  172. package/dist/harness/memory/sqlite/wisdom-store.js +51 -2
  173. package/dist/harness/memory/steward-policy.d.ts +3 -0
  174. package/dist/harness/memory/steward-policy.js +1 -1
  175. package/dist/harness/memory/types.d.ts +41 -3
  176. package/dist/harness/memory/wisdom-attribution.d.ts +136 -0
  177. package/dist/harness/memory/wisdom-attribution.js +287 -0
  178. package/dist/harness/memory/wisdom-events.d.ts +37 -0
  179. package/dist/harness/memory/wisdom-events.js +61 -0
  180. package/dist/harness/memory/wisdom-formation.d.ts +20 -1
  181. package/dist/harness/memory/wisdom-formation.js +55 -21
  182. package/dist/harness/memory/wisdom.d.ts +7 -2
  183. package/dist/harness/memory/wisdom.js +40 -2
  184. package/dist/harness/observability/observer/hub.js +8 -0
  185. package/dist/harness/observability/observer/run-snapshot.js +1 -0
  186. package/dist/harness/observability/observer/types.d.ts +4 -0
  187. package/dist/harness/run/agent/agent.d.ts +7 -0
  188. package/dist/harness/run/agent/agent.js +23 -1
  189. package/dist/harness/run/reliability/fallback-provider.d.ts +117 -5
  190. package/dist/harness/run/reliability/fallback-provider.js +262 -22
  191. package/dist/harness/run/reliability/harness-events.d.ts +24 -1
  192. package/dist/harness/run/reliability/model-error-policy.d.ts +32 -0
  193. package/dist/harness/run/reliability/model-error-policy.js +42 -0
  194. package/dist/harness/run/reliability/provider-wrapper.js +29 -2
  195. package/dist/harness/run/reliability/refusal-guard.d.ts +20 -0
  196. package/dist/harness/run/reliability/refusal-guard.js +102 -0
  197. package/dist/harness/run/reliability/run-agent.js +231 -33
  198. package/dist/harness/run/run-guard/default-run-guard.js +1 -1
  199. package/dist/harness/run/run-scope.d.ts +35 -0
  200. package/dist/harness/run/runner.d.ts +141 -2
  201. package/dist/harness/run/runner.js +592 -42
  202. package/dist/harness/session/attachments/llm-intent.js +2 -1
  203. package/dist/harness/session/tasks/render.d.ts +4 -1
  204. package/dist/harness/session/tasks/render.js +10 -7
  205. package/dist/harness/shared/events/agent-event-map.d.ts +66 -0
  206. package/dist/harness/shared/events/agent-event-map.js +5 -0
  207. package/dist/harness/shared/paths/glob.d.ts +52 -0
  208. package/dist/harness/shared/paths/glob.js +218 -0
  209. package/dist/harness/shared/paths/index.d.ts +84 -0
  210. package/dist/harness/shared/paths/index.js +179 -0
  211. package/dist/index.d.ts +3 -3
  212. package/dist/index.js +2 -2
  213. package/dist/integration/agent-runtime/channel-message-source.js +19 -1
  214. package/dist/integration/index.d.ts +2 -0
  215. package/dist/integration/index.js +1 -0
  216. package/dist/integration/observability/loop-watchdog.d.ts +56 -0
  217. package/dist/integration/observability/loop-watchdog.js +177 -0
  218. package/dist/integration/observability/metrics.d.ts +3 -0
  219. package/dist/integration/observability/metrics.js +18 -7
  220. package/dist/integration/providers/anthropic.d.ts +23 -0
  221. package/dist/integration/providers/anthropic.js +97 -12
  222. package/dist/integration/providers/fetch-timeout.d.ts +42 -0
  223. package/dist/integration/providers/fetch-timeout.js +51 -0
  224. package/dist/integration/providers/openai.d.ts +10 -0
  225. package/dist/integration/providers/openai.js +58 -11
  226. package/dist/integration/providers/provider-diagnostics.d.ts +80 -0
  227. package/dist/integration/providers/provider-diagnostics.js +89 -0
  228. package/dist/integration/providers/timeout-coherence.d.ts +52 -0
  229. package/dist/integration/providers/timeout-coherence.js +68 -0
  230. package/dist/integration/providers/wire-dump.d.ts +62 -0
  231. package/dist/integration/providers/wire-dump.js +111 -2
  232. package/dist/integration/storage/jsonl.js +4 -1
  233. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +4 -2
  234. package/dist/subsystems/cognition-steward/conceptualize/handler.js +12 -20
  235. package/dist/subsystems/memory-steward/backfill/config.yaml +4 -2
  236. package/dist/subsystems/memory-steward/backfill/handler.js +44 -52
  237. package/dist/subsystems/wisdom-steward/attribute/SUBSYSTEM.md +24 -0
  238. package/dist/subsystems/wisdom-steward/attribute/config.yaml +60 -0
  239. package/dist/subsystems/wisdom-steward/attribute/handler.d.ts +23 -0
  240. package/dist/subsystems/wisdom-steward/attribute/handler.js +167 -0
  241. package/dist/subsystems/wisdom-steward/evaluate/handler.js +3 -1
  242. package/dist/subsystems/wisdom-steward/formation/config.yaml +12 -5
  243. package/dist/subsystems/wisdom-steward/formation/handler.js +12 -18
  244. package/dist/subsystems/wisdom-steward/govern/config.yaml +1 -1
  245. package/dist/subsystems/wisdom-steward/govern/handler.js +4 -0
  246. package/package.json +8 -2
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Max Brunsfeld
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -14,6 +14,16 @@ function rights(input) {
14
14
  toolRights: input.toolRights ?? { allow: undefined, deny: [], denyCapabilities: [] },
15
15
  };
16
16
  }
17
+ /**
18
+ * 提权请求者授权(ops §8.6 拍板:T1 缺省仅 owner 可请求):
19
+ * 非 owner 角色默认 deny `priv_exec`——缺权参与者在 toolRights 层即拒,
20
+ * 连确认闸都到不了。owner 显式不受限。
21
+ */
22
+ const NON_OWNER_PRIVILEGE = {
23
+ allow: undefined,
24
+ deny: ['priv_exec'],
25
+ denyCapabilities: [],
26
+ };
17
27
  /** Built-in five-role catalog (v1: no consultant) */
18
28
  export const BUILTIN_SESSION_ROLES = [
19
29
  {
@@ -37,6 +47,7 @@ export const BUILTIN_SESSION_ROLES = [
37
47
  readScope: 'full',
38
48
  writeMemory: true,
39
49
  canManageTasks: true,
50
+ toolRights: NON_OWNER_PRIVILEGE,
40
51
  canHandoff: false,
41
52
  }),
42
53
  },
@@ -49,6 +60,7 @@ export const BUILTIN_SESSION_ROLES = [
49
60
  readScope: 'full',
50
61
  writeMemory: false,
51
62
  canManageTasks: false,
63
+ toolRights: NON_OWNER_PRIVILEGE,
52
64
  canHandoff: false,
53
65
  }),
54
66
  },
@@ -61,6 +73,7 @@ export const BUILTIN_SESSION_ROLES = [
61
73
  readScope: 'none',
62
74
  writeMemory: false,
63
75
  canManageTasks: false,
76
+ toolRights: NON_OWNER_PRIVILEGE,
64
77
  canHandoff: false,
65
78
  }),
66
79
  },
@@ -73,6 +86,7 @@ export const BUILTIN_SESSION_ROLES = [
73
86
  readScope: 'full',
74
87
  writeMemory: true,
75
88
  canManageTasks: true,
89
+ toolRights: NON_OWNER_PRIVILEGE,
76
90
  canHandoff: false,
77
91
  }),
78
92
  },
@@ -47,6 +47,8 @@ export { RunMetricsCollector } from './run/reliability/run-metrics-collector.js'
47
47
  export { CircuitBreaker } from './run/reliability/circuit-breaker.js';
48
48
  export { wrapProviderWithCircuitBreaker } from './run/reliability/provider-wrapper.js';
49
49
  export { FallbackProvider } from './run/reliability/fallback-provider.js';
50
+ export { guardRefusalProvider } from './run/reliability/refusal-guard.js';
51
+ export { detectSummaryContamination } from './context/capabilities/compact/engine.js';
50
52
  export { PluginManager } from './extension/plugin-ecosystem/plugins/manager.js';
51
53
  export { definePluginEntry, defineChannelPluginEntry } from './extension/plugin-ecosystem/plugins/entry.js';
52
54
  export type { OctopiPluginDefinition, OctopiChannelPluginDefinition } from './extension/plugin-ecosystem/plugins/entry.js';
@@ -38,6 +38,8 @@ export { RunMetricsCollector } from './run/reliability/run-metrics-collector.js'
38
38
  export { CircuitBreaker } from './run/reliability/circuit-breaker.js';
39
39
  export { wrapProviderWithCircuitBreaker } from './run/reliability/provider-wrapper.js';
40
40
  export { FallbackProvider } from './run/reliability/fallback-provider.js';
41
+ export { guardRefusalProvider } from './run/reliability/refusal-guard.js';
42
+ export { detectSummaryContamination } from './context/capabilities/compact/engine.js';
41
43
  // ── Plugin Ecosystem ──
42
44
  export { PluginManager } from './extension/plugin-ecosystem/plugins/manager.js';
43
45
  export { definePluginEntry, defineChannelPluginEntry } from './extension/plugin-ecosystem/plugins/entry.js';
@@ -4,9 +4,8 @@
4
4
  * 中文不靠默认分词:索引/查询都写入「词 + CJK 二元组」token 流(对齐 Memory)。
5
5
  * FTS 表非权威;upsert/remove 同步维护,可整库 rebuild。
6
6
  */
7
- import { tokenizeKeywordQuery } from '../memory/sqlite/keyword-search.js';
7
+ import { CJK_RE, tokenizeKeywordQuery } from '../memory/sqlite/keyword-search.js';
8
8
  const TOKEN_SPLIT = /[^\p{L}\p{N}_]+/u;
9
- const CJK_RE = /[㐀-䶿一-鿿豈-﫿぀-ヿ]/;
10
9
  /** 超长 token(base64/uuid/hash/压缩 JS 标识)不进倒排,避免 FTS 膨胀 */
11
10
  const MAX_TOKEN_CHARS = 32;
12
11
  /** 单 chunk token 流上限,防止病态正文写爆 FTS */
@@ -12,6 +12,29 @@ import { toVecBlob } from '../memory/sqlite/sqlite-vec.js';
12
12
  import { asChunkId, asSourceId } from './types.js';
13
13
  import { normalizePathLexical, realIdentitySync } from './file-identity.js';
14
14
  const EMBEDDABLE_WHERE = "(f.adapter_id IS NULL OR f.adapter_id NOT IN ('code-tree'))";
15
+ /** B+ 匹配语义分界:2–3 字符纯 ASCII 字母数字词用词边界,其余用子串(语义细节见 search 兜底注释)。 */
16
+ const SUBSTRING_FALLBACK_MIN_CHARS = 4; // 3 字符(api/db)碰撞面大需边界保护;≥4 起子词召回价值高于碰撞成本
17
+ /**
18
+ * weak-only 命中的绝对相关性地板(scoreKeywordCoverage 口径)。
19
+ * 中文长段查询靠二元组重叠召回是本义(「会话签名校验」须命中「校验会话签名」,4/5 重叠 ≈ 0.57),
20
+ * 但 1–2 个虚词二元组擦边是噪音(≈ 0.14–0.29)——界线 0.3。
21
+ */
22
+ const WEAK_ONLY_SCORE_FLOOR = 0.3;
23
+ /** B+ 分类单源:该 token 是否走词边界语义(兜底 SQL 子句与 JS 判定共用,防语义漂移)。 */
24
+ function isBoundaryToken(token) {
25
+ return token.length < SUBSTRING_FALLBACK_MIN_CHARS && /^[a-z0-9]+$/.test(token);
26
+ }
27
+ /** B+ 语义命中判定:token 是否命中 text/path(与兜底 SQL 子句同源的边界/子串语义)。 */
28
+ function tokenMatchesBPlus(token, text, path) {
29
+ const t = token.toLowerCase();
30
+ const textL = text.toLowerCase();
31
+ const pathL = path.toLowerCase();
32
+ if (isBoundaryToken(token)) {
33
+ const boundary = new RegExp(`(^|[^a-z0-9])${t}([^a-z0-9]|$)`);
34
+ return boundary.test(textL) || boundary.test(pathL);
35
+ }
36
+ return textL.includes(t) || pathL.includes(t);
37
+ }
15
38
  function defaultIdentityKey(path) {
16
39
  try {
17
40
  return `path:${normalizePathLexical(path)}`;
@@ -875,14 +898,34 @@ export class KnowledgeIndexStore {
875
898
  .all(...ftsIds, ...opts.sourceIds);
876
899
  }
877
900
  if (!rows || rows.length === 0) {
878
- const likeClauses = [];
879
- const likeParams = [];
901
+ // 兜底匹配语义(B+):SQL 子串取候选、按 token 分类给精确判定——
902
+ // · 2–3 字符纯 ASCII 字母数字词:词边界命中(防跨词字母碰撞 be ⊂ obeswy)。
903
+ // GLOB 字符类回溯较 LIKE 慢约 10×(20k chunk 实测 235ms vs 23ms),故仅此小类承担,
904
+ // 且只在 FTS 零命中时触发。不用「LIKE 取候选 + JS 边界校验」:LIMIT 窗口会被子串噪音
905
+ // 占满而丢真命中,GLOB 在 SQL 侧精确过滤无此问题。
906
+ // · 其余 token(≥ SUBSTRING_FALLBACK_MIN_CHARS、非纯 ASCII 字母数字):子串命中——
907
+ // 长词保留子词/词干召回(assembly → contextAssembly;其边界命中是子串命中的子集,
908
+ // 词边界子句纯冗余);非 ASCII(CJK/韩/西里尔/混合)无词边界语义,显式并入子串。
909
+ // 边界 = 非 [a-z0-9] 字符(含 _/标点/CJK):_ 与 FTS unicode61 切分一致;CJK 作为边界是
910
+ // **有意放宽**(「api接口」须能命中 api),并非对齐 unicode61(其视 foo文bar 为单 token)。
911
+ // GLOB 不变式由 ^[a-z0-9]+$ 守门:将来 tokenizer 放行 `-`/`.`/`*`/`[`/`]` 等也不会进 GLOB 分支。
912
+ const matchClauses = [];
913
+ const matchParams = [];
880
914
  for (const token of tokens) {
881
- const like = `%${token.toLowerCase().replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
882
- likeClauses.push(`LOWER(c.text) LIKE ? ESCAPE '\\'`);
883
- likeParams.push(like);
884
- likeClauses.push(`LOWER(m.logical_path) LIKE ? ESCAPE '\\'`);
885
- likeParams.push(like);
915
+ if (!isBoundaryToken(token)) {
916
+ const likePattern = `%${token.toLowerCase().replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
917
+ matchClauses.push(`LOWER(c.text) LIKE ? ESCAPE '\\'`);
918
+ matchParams.push(likePattern);
919
+ matchClauses.push(`LOWER(m.logical_path) LIKE ? ESCAPE '\\'`);
920
+ matchParams.push(likePattern);
921
+ }
922
+ else {
923
+ const globPattern = `*[^a-z0-9]${token}[^a-z0-9]*`;
924
+ matchClauses.push(`(' ' || LOWER(c.text) || ' ') GLOB ?`);
925
+ matchParams.push(globPattern);
926
+ matchClauses.push(`(' ' || LOWER(m.logical_path) || ' ') GLOB ?`);
927
+ matchParams.push(globPattern);
928
+ }
886
929
  }
887
930
  rows = this.db.raw
888
931
  .prepare(`SELECT c.id, c.file_id, c.ordinal, c.text, c.start_line, c.end_line,
@@ -891,9 +934,9 @@ export class KnowledgeIndexStore {
891
934
  JOIN knowledge_files f ON f.id = c.file_id AND f.status <> 'indexing'
892
935
  JOIN knowledge_memberships m ON m.file_id = c.file_id
893
936
  WHERE m.source_id IN (${placeholders})
894
- AND (${likeClauses.join(' OR ')})
937
+ AND (${matchClauses.join(' OR ')})
895
938
  LIMIT ?`)
896
- .all(...opts.sourceIds, ...likeParams, Math.max(limit * 8, 64));
939
+ .all(...opts.sourceIds, ...matchParams, Math.max(limit * 8, 64));
897
940
  }
898
941
  const byChunk = new Map();
899
942
  for (const r of rows) {
@@ -901,6 +944,8 @@ export class KnowledgeIndexStore {
901
944
  if (!h) {
902
945
  if (byChunk.size >= limit * 3)
903
946
  continue;
947
+ // 打分仍是子串口径(scoreKeywordCoverage 共享 memory 域):与匹配语义的差异是有意留待统一的
948
+ // 已知项(见 v0.97.2 CHANGELOG 遗留),本层不改共享打分契约。
904
949
  const score = scoreKeywordCoverage({ content: r.text, tags: r.logical_path }, tokenDetail);
905
950
  h = {
906
951
  chunkId: r.id,
@@ -920,7 +965,12 @@ export class KnowledgeIndexStore {
920
965
  h.sourceIds.push(r.source_id);
921
966
  h.logicalPaths[r.source_id] = r.logical_path;
922
967
  }
968
+ // 弱命中地板(执行分词器既有契约:weak 滑窗二元组单独命中不足以过相关性地板):
969
+ // strong 命中直接过;weak-only 命中须过 WEAK_ONLY_SCORE_FLOOR——防中文虚词二元组
970
+ // (的时/是的…)擦边命中灌满结果集,同时保住长段复合查询的二元组重叠召回。
923
971
  return [...byChunk.values()]
972
+ .filter((h) => tokenDetail.strong.some((t) => tokenMatchesBPlus(t, h.text, h.path)) ||
973
+ h.score >= WEAK_ONLY_SCORE_FLOOR)
924
974
  .sort((a, b) => b.score - a.score)
925
975
  .slice(0, limit)
926
976
  .map((h) => ({
@@ -4,13 +4,17 @@
4
4
  * 价值模型:fact / method / norm(见 docs/memory.md、arch/memory-system-redesign.md)。
5
5
  * system prompt ContextLayer 契约在 harness/context/。
6
6
  */
7
- export type { MemoryType, MemoryChannel, MemoryStatus, SoftDeleteReason, MemoryEntry, MemoryQuery, MemoryStats, MemoryStore, MemoryWriteSlot, WisdomStatus, WisdomOrigin, WisdomKind, WisdomRetireReason, WisdomScenario, WisdomEffect, WisdomDerivation, WisdomCounterevidence, WisdomOutcomes, WisdomEntry, WisdomGateReason, WisdomGateOutcome, AdmitWisdomInput, AdmitWisdomAction, AdmitWisdomResult, WisdomInjectQuery, WisdomInjectPick, WisdomOutcomeSignal, WisdomOutcomeEvent, WisdomStats, WisdomStore, ConceptKind, ConceptRelationType, ConceptStatus, EvidenceClass, EdgeBasis, ConceptNode, ConceptEdge, ConceptGraph, MergeCandidate, EdgeAux, AdmitConceptInput, AdmitConceptResult, AdmitEdgeInput, AdmitEdgeResult, ConceptGateReason, SpreadingActivateOptions, ActivatedGraph, ConceptGraphStats, DecayResult, ConceptGraphStore, } from './types.js';
7
+ export type { MemoryType, MemoryChannel, MemoryStatus, SoftDeleteReason, MemoryEntry, MemoryQuery, MemoryStats, MemoryStore, MemoryWriteSlot, WisdomStatus, WisdomOrigin, WisdomKind, WisdomRetireReason, WisdomScenario, WisdomEffect, WisdomDerivation, WisdomCounterevidence, WisdomOutcomes, WisdomEntry, WisdomGateReason, WisdomGateOutcome, AdmitWisdomInput, AdmitWisdomAction, AdmitWisdomResult, WisdomInjectQuery, WisdomInjectPick, WisdomOutcomeSignal, WisdomOutcomeEvent, WisdomAttributionCitation, WisdomAttributionWindowInput, WisdomAttributionWindow, WisdomStats, WisdomStore, ConceptKind, ConceptRelationType, ConceptStatus, EvidenceClass, EdgeBasis, ConceptNode, ConceptEdge, ConceptGraph, MergeCandidate, EdgeAux, AdmitConceptInput, AdmitConceptResult, AdmitEdgeInput, AdmitEdgeResult, ConceptGateReason, SpreadingActivateOptions, ActivatedGraph, ConceptGraphStats, DecayResult, ConceptGraphStore, } from './types.js';
8
8
  export { MEMORY_TYPES, WISDOM_STATUSES, WISDOM_INJECTABLE_STATUSES, WISDOM_ORIGINS, WISDOM_KINDS, CONCEPT_KINDS, CONCEPT_RELATION_TYPES, STRONG_RELATION_TYPES, } from './types.js';
9
9
  export { evaluateWisdomGate, resolveInitialWisdomStatus, normalizeStatement, looksOpposed, WISDOM_DEFAULT_MIN_SUPPORT, } from './wisdom-gates.js';
10
10
  export { DEFAULT_WISDOM_EVALUATION, DEFAULT_WISDOM_GOVERN, foldOutcomeEvents, planConfidenceUpdate, planWisdomGovern, wisdomUtility, wisdomInjectScore, } from './wisdom-policy.js';
11
11
  export type { WisdomEvaluationConfig, WisdomGovernConfig, WisdomConfidenceUpdate, WisdomGoverPlanItem, } from './wisdom-policy.js';
12
- export { parseWisdomFormationJson, normalizeWisdomFormation, toAdmitWisdomInput, formAndAdmit, scenarioMatchScore, pickForInjection, formatWisdomBody, } from './wisdom-formation.js';
12
+ export { parseWisdomFormationJson, normalizeWisdomFormation, toAdmitWisdomInput, formAndAdmit, scenarioMatchScore, scenarioMatchDetail, isCoreEligible, pickForInjection, formatWisdomBody, } from './wisdom-formation.js';
13
13
  export type { RawWisdomFormationOutput, ParsedWisdomItem, ParsedWisdomFormation, } from './wisdom-formation.js';
14
+ export { extractCitations, collectRunAssistantTexts, recordWisdomRunWindow, selectAttributionCandidates, planAttributionBatch, buildAttributionDigest, parseAttributionVerdicts, verdictsToOutcomeEvents, } from './wisdom-attribution.js';
15
+ export type { WisdomRunWindowInfo, AttributionCandidate, AttributionBatch, AttributionVerdict, } from './wisdom-attribution.js';
16
+ export { emitWisdomEvaluateRequest, emitWisdomGoverned, WISDOM_EVALUATE_REQUEST_EVENT, WISDOM_GOVERNED_EVENT, } from './wisdom-events.js';
17
+ export type { WisdomEvaluateRequestPayload } from './wisdom-events.js';
14
18
  export { evaluateConceptGate, licenseEdge, edgeBasisFromLicense, normalizeForCue, } from './cognition-gates.js';
15
19
  export type { ConceptGateOutcome, EdgeLicenseInput, EdgeLicenseOutcome, } from './cognition-gates.js';
16
20
  export { DEFAULT_EDGE_DECAY_PER_DAY, DEFAULT_EDGE_DECAY_FLOOR, DEFAULT_RETRIEVE_STATUSES, decayMultiplier, nextEdgeStrength, hebbianStrengthen, counterEvidenceWeaken, } from './cognition-decay.js';
@@ -8,7 +8,10 @@ export { MEMORY_TYPES, WISDOM_STATUSES, WISDOM_INJECTABLE_STATUSES, WISDOM_ORIGI
8
8
  // ── Wisdom 门控 / 策略 / 形成 ──
9
9
  export { evaluateWisdomGate, resolveInitialWisdomStatus, normalizeStatement, looksOpposed, WISDOM_DEFAULT_MIN_SUPPORT, } from './wisdom-gates.js';
10
10
  export { DEFAULT_WISDOM_EVALUATION, DEFAULT_WISDOM_GOVERN, foldOutcomeEvents, planConfidenceUpdate, planWisdomGovern, wisdomUtility, wisdomInjectScore, } from './wisdom-policy.js';
11
- export { parseWisdomFormationJson, normalizeWisdomFormation, toAdmitWisdomInput, formAndAdmit, scenarioMatchScore, pickForInjection, formatWisdomBody, } from './wisdom-formation.js';
11
+ export { parseWisdomFormationJson, normalizeWisdomFormation, toAdmitWisdomInput, formAndAdmit, scenarioMatchScore, scenarioMatchDetail, isCoreEligible, pickForInjection, formatWisdomBody, } from './wisdom-formation.js';
12
+ // ── Wisdom 归因窗口 / 判决事件 ──
13
+ export { extractCitations, collectRunAssistantTexts, recordWisdomRunWindow, selectAttributionCandidates, planAttributionBatch, buildAttributionDigest, parseAttributionVerdicts, verdictsToOutcomeEvents, } from './wisdom-attribution.js';
14
+ export { emitWisdomEvaluateRequest, emitWisdomGoverned, WISDOM_EVALUATE_REQUEST_EVENT, WISDOM_GOVERNED_EVENT, } from './wisdom-events.js';
12
15
  // ── Cognition 门控 / 可塑 / 概念化 ──
13
16
  export { evaluateConceptGate, licenseEdge, edgeBasisFromLicense, normalizeForCue, } from './cognition-gates.js';
14
17
  export { DEFAULT_EDGE_DECAY_PER_DAY, DEFAULT_EDGE_DECAY_FLOOR, DEFAULT_RETRIEVE_STATUSES, decayMultiplier, nextEdgeStrength, hebbianStrengthen, counterEvidenceWeaken, } from './cognition-decay.js';
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Memory 存量变化信号 — 每条命题落库后 emit `memory.stored`
3
+ *
4
+ * 消费方(sense.filter.events 订阅):wisdom.steward.formation 等增量触发的子系统。
5
+ * 事件类型必须真实存在于 EventBus;发射失败静默(不得阻断 memory 写路径)。
6
+ *
7
+ * @module harness/memory/memory-events
8
+ */
9
+ import type { EventBus } from '@octopi-agent/core/primitives/event-bus.js';
10
+ /** 命题落库信号(每条一发;消费方按 minEvents 累积节流) */
11
+ export declare const MEMORY_STORED_EVENT = "memory.stored";
12
+ export interface MemoryStoredPayload {
13
+ memoryId: string;
14
+ type?: string;
15
+ status?: string;
16
+ sessionId?: string;
17
+ agentId?: string;
18
+ }
19
+ /**
20
+ * 发射命题落库信号。失败静默(不得阻断 Memory 写入)。
21
+ *
22
+ * @param events - EventBus
23
+ * @param payload - 落库载荷
24
+ */
25
+ export declare function emitMemoryStored(events: EventBus | undefined, payload: MemoryStoredPayload): void;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Memory 存量变化信号 — 每条命题落库后 emit `memory.stored`
3
+ *
4
+ * 消费方(sense.filter.events 订阅):wisdom.steward.formation 等增量触发的子系统。
5
+ * 事件类型必须真实存在于 EventBus;发射失败静默(不得阻断 memory 写路径)。
6
+ *
7
+ * @module harness/memory/memory-events
8
+ */
9
+ /** 命题落库信号(每条一发;消费方按 minEvents 累积节流) */
10
+ export const MEMORY_STORED_EVENT = 'memory.stored';
11
+ /**
12
+ * 发射命题落库信号。失败静默(不得阻断 Memory 写入)。
13
+ *
14
+ * @param events - EventBus
15
+ * @param payload - 落库载荷
16
+ */
17
+ export function emitMemoryStored(events, payload) {
18
+ if (!events)
19
+ return;
20
+ try {
21
+ events.emit({
22
+ type: MEMORY_STORED_EVENT,
23
+ timestamp: Date.now(),
24
+ agentId: payload.agentId,
25
+ sessionId: payload.sessionId,
26
+ data: {
27
+ memoryId: payload.memoryId,
28
+ type: payload.type,
29
+ status: payload.status,
30
+ sessionId: payload.sessionId,
31
+ agentId: payload.agentId,
32
+ },
33
+ });
34
+ }
35
+ catch {
36
+ // 总线异常不得拖垮 Memory 写入
37
+ }
38
+ }
@@ -297,6 +297,21 @@ export class AgentDatabase {
297
297
  CREATE INDEX IF NOT EXISTS idx_wisdom_status ON wisdom(status);
298
298
  CREATE INDEX IF NOT EXISTS idx_wisdom_priority ON wisdom(priority);
299
299
 
300
+ -- ── Wisdom 归因窗口(弱归因验证:run 收尾记账,判官批量判决)──
301
+ CREATE TABLE IF NOT EXISTS wisdom_attribution_windows (
302
+ id TEXT PRIMARY KEY,
303
+ session_id TEXT NOT NULL,
304
+ agent_id TEXT,
305
+ query TEXT NOT NULL DEFAULT '',
306
+ outcome TEXT NOT NULL DEFAULT '',
307
+ injected_ids TEXT NOT NULL DEFAULT '[]',
308
+ citations TEXT NOT NULL DEFAULT '[]',
309
+ created_at INTEGER NOT NULL,
310
+ judged_at INTEGER
311
+ );
312
+ CREATE INDEX IF NOT EXISTS idx_wisdom_windows_judged ON wisdom_attribution_windows(judged_at);
313
+ CREATE INDEX IF NOT EXISTS idx_wisdom_windows_created ON wisdom_attribution_windows(created_at);
314
+
300
315
  -- ── Knowledge Sources 注册表 ──
301
316
  CREATE TABLE IF NOT EXISTS knowledge_sources (
302
317
  id TEXT PRIMARY KEY,
@@ -12,6 +12,7 @@ export interface KeywordFields {
12
12
  anchors?: string[] | string | null;
13
13
  evidence?: string | null;
14
14
  }
15
+ export declare const CJK_RE: RegExp;
15
16
  /**
16
17
  * 查询分词:空白/标点切分;连续 CJK 片段额外产出二元组。
17
18
  *
@@ -4,7 +4,7 @@
4
4
  * 中英混合:空格/标点切词 + CJK 二元组,扩大「技术栈 vs 技术选型」类弱重叠召回。
5
5
  * 字段权重:content > future_use/tags > evidence/anchors。
6
6
  */
7
- const CJK_RE = /[㐀-䶿一-鿿豈-﫿぀-ヿ]/;
7
+ export const CJK_RE = /[㐀-䶿一-鿿豈-﫿぀-ヿ]/;
8
8
  function isCjk(ch) {
9
9
  return CJK_RE.test(ch);
10
10
  }
@@ -190,9 +190,10 @@ export function buildKeywordLikeSql(tokens) {
190
190
  const clauses = [];
191
191
  const params = [];
192
192
  for (const token of tokens) {
193
- const like = `%${token.toLowerCase()}%`;
193
+ // LIKE 通配符转义:`_`/`%` 对用户是字面量(get_user_id 不得命中 getXuserXid)
194
+ const like = `%${token.toLowerCase().replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
194
195
  for (const col of columns) {
195
- clauses.push(`${col} LIKE ?`);
196
+ clauses.push(`${col} LIKE ? ESCAPE '\\'`);
196
197
  params.push(like);
197
198
  }
198
199
  }
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * @module
7
7
  */
8
- import type { AdmitWisdomInput, AdmitWisdomResult, WisdomEntry, WisdomInjectPick, WisdomInjectQuery, WisdomOutcomeEvent, WisdomRetireReason, WisdomStats, WisdomStore } from '../types.js';
8
+ import type { AdmitWisdomInput, AdmitWisdomResult, WisdomAttributionWindow, WisdomAttributionWindowInput, WisdomEntry, WisdomInjectPick, WisdomInjectQuery, WisdomOutcomeEvent, WisdomRetireReason, WisdomStats, WisdomStore } from '../types.js';
9
9
  import { AgentDatabase } from './agent-db.js';
10
10
  export interface SqliteWisdomStoreOptions {
11
11
  /** admit 硬顶(存活面);默认 80 */
@@ -29,8 +29,13 @@ export declare class SqliteWisdomStore implements WisdomStore {
29
29
  by: string;
30
30
  reason: WisdomRetireReason | string;
31
31
  }): Promise<void>;
32
- recordOutcomes(events: WisdomOutcomeEvent[]): Promise<void>;
32
+ recordOutcomes(events: WisdomOutcomeEvent[], config?: import('../wisdom-policy.js').WisdomEvaluationConfig): Promise<void>;
33
33
  touchApplied(ids: string[]): Promise<void>;
34
+ recordAttributionWindow(input: WisdomAttributionWindowInput): Promise<string>;
35
+ listPendingWindows(limit?: number): Promise<WisdomAttributionWindow[]>;
36
+ markWindowsJudged(ids: string[], at?: number): Promise<string[]>;
37
+ pruneWindows(before: number): Promise<void>;
38
+ private rowToWindow;
34
39
  stats(): Promise<WisdomStats>;
35
40
  /** 存活面计数(candidate/trial/active/strengthened/contested) */
36
41
  countLive(): number;
@@ -112,7 +112,7 @@ export class SqliteWisdomStore {
112
112
  exceptions: [...(current.exceptions ?? []), `retired:${meta.reason}:${meta.by}`],
113
113
  });
114
114
  }
115
- async recordOutcomes(events) {
115
+ async recordOutcomes(events, config) {
116
116
  if (events.length === 0)
117
117
  return;
118
118
  const byId = new Map();
@@ -127,7 +127,7 @@ export class SqliteWisdomStore {
127
127
  continue;
128
128
  const folded = foldOutcomeEvents(current, evs);
129
129
  let next = { ...current, ...folded, updatedAt: Date.now() };
130
- const plan = planConfidenceUpdate(next);
130
+ const plan = planConfidenceUpdate(next, config);
131
131
  if (plan) {
132
132
  next = {
133
133
  ...next,
@@ -174,6 +174,55 @@ export class SqliteWisdomStore {
174
174
  .run(JSON.stringify(outcomes), now, id);
175
175
  }
176
176
  }
177
+ async recordAttributionWindow(input) {
178
+ const id = AgentDatabase.generateId('waw');
179
+ this.db.raw
180
+ .prepare(`INSERT INTO wisdom_attribution_windows
181
+ (id, session_id, agent_id, query, outcome, injected_ids, citations, created_at)
182
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
183
+ .run(id, input.sessionId, input.agentId ?? null, input.query, input.outcome, JSON.stringify(input.injectedIds), JSON.stringify(input.citations), Date.now());
184
+ return id;
185
+ }
186
+ async listPendingWindows(limit) {
187
+ const rows = this.db.raw
188
+ .prepare(`SELECT * FROM wisdom_attribution_windows WHERE judged_at IS NULL
189
+ ORDER BY created_at ASC LIMIT ?`)
190
+ .all(limit && limit > 0 ? limit : 500);
191
+ return rows.map((r) => this.rowToWindow(r));
192
+ }
193
+ async markWindowsJudged(ids, at) {
194
+ if (ids.length === 0)
195
+ return [];
196
+ const now = at ?? Date.now();
197
+ const stmt = this.db.raw.prepare(`UPDATE wisdom_attribution_windows SET judged_at = ? WHERE id = ? AND judged_at IS NULL`);
198
+ const newlyJudged = [];
199
+ for (const id of ids) {
200
+ // 只有真正置上的才算本次标记(跨进程幂等:他方先标则不发事件)
201
+ const res = stmt.run(now, id);
202
+ if (Number(res.changes ?? 0) > 0)
203
+ newlyJudged.push(id);
204
+ }
205
+ return newlyJudged;
206
+ }
207
+ async pruneWindows(before) {
208
+ this.db.raw
209
+ .prepare(`DELETE FROM wisdom_attribution_windows WHERE judged_at IS NOT NULL AND judged_at < ?`)
210
+ .run(before);
211
+ }
212
+ rowToWindow(r) {
213
+ return {
214
+ id: String(r.id),
215
+ sessionId: String(r.session_id),
216
+ agentId: r.agent_id == null ? undefined : String(r.agent_id),
217
+ query: String(r.query ?? ''),
218
+ outcome: String(r.outcome ?? ''),
219
+ // 坏行不得毒化整批(手工损坏/半写 JSON 跳过字段而非抛错)
220
+ injectedIds: safeParse(String(r.injected_ids ?? ''), []),
221
+ citations: safeParse(String(r.citations ?? ''), []),
222
+ createdAt: Number(r.created_at),
223
+ judgedAt: r.judged_at == null ? undefined : Number(r.judged_at),
224
+ };
225
+ }
177
226
  async stats() {
178
227
  const rows = this.db.raw.prepare(`SELECT * FROM wisdom`).all();
179
228
  const byStatus = Object.fromEntries(WISDOM_STATUSES.map((s) => [s, 0]));
@@ -76,6 +76,9 @@ export interface AdmitResult {
76
76
  id: string;
77
77
  type: MemoryType;
78
78
  status: string;
79
+ proposition: string;
80
+ channel: string;
81
+ evidence?: string;
79
82
  }>;
80
83
  rejected: Array<{
81
84
  reason: AdmitRejectReason;
@@ -275,7 +275,7 @@ export async function admitCandidates(store, candidates, source) {
275
275
  if (idx >= 0)
276
276
  live.splice(idx, 1);
277
277
  }
278
- accepted.push({ id, type, status });
278
+ accepted.push({ id, type, status, proposition: c.proposition, channel: c.channel ?? 'model_inference', evidence: c.evidence });
279
279
  sourceCount += 1;
280
280
  // 同批后续候选可对刚写入条目判重
281
281
  live.push({
@@ -4,6 +4,7 @@
4
4
  * @layer harness/memory — Context Intelligence 存储协议。
5
5
  * 实现:InMemory* / Sqlite*(AgentDatabase)。非 Kernel。
6
6
  */
7
+ import type { WisdomEvaluationConfig } from './wisdom-policy.js';
7
8
  /**
8
9
  * 记忆类型 — 蒸馏产物三类(见 docs/memory.md)
9
10
  *
@@ -243,7 +244,7 @@ export interface WisdomInjectQuery {
243
244
  coreMaxItems?: number;
244
245
  /** 场景条数硬顶 */
245
246
  scenarioMaxItems?: number;
246
- /** 是否包含 trial(默认 false) */
247
+ /** 是否包含 trial(默认 true——trial 的意义就是被试用;显式 false 只注入已站稳条目) */
247
248
  includeTrial?: boolean;
248
249
  }
249
250
  export interface WisdomInjectPick {
@@ -262,6 +263,30 @@ export interface WisdomOutcomeEvent {
262
263
  note?: string;
263
264
  ref?: string;
264
265
  }
266
+ /** 归因窗口中的一处引用摘录(判官强证据) */
267
+ export interface WisdomAttributionCitation {
268
+ wisdomId: string;
269
+ excerpt: string;
270
+ }
271
+ /** 归因窗口输入(run 收尾记账) */
272
+ export interface WisdomAttributionWindowInput {
273
+ sessionId: string;
274
+ agentId?: string;
275
+ /** 本轮任务/查询文本(判官 digest 证据) */
276
+ query: string;
277
+ /** run 收尾原因(completed/aborted/error…)——仅作判官上下文,不作判决 */
278
+ outcome: string;
279
+ /** 本轮注入的 wisdom id(装配 manifest sources) */
280
+ injectedIds: string[];
281
+ citations: WisdomAttributionCitation[];
282
+ }
283
+ /** 归因窗口:弱归因验证的记账单位(run 收尾 → 判官批量判决) */
284
+ export interface WisdomAttributionWindow extends WisdomAttributionWindowInput {
285
+ id: string;
286
+ createdAt: number;
287
+ /** 缺省 = 未判决 */
288
+ judgedAt?: number;
289
+ }
265
290
  export interface WisdomStats {
266
291
  total: number;
267
292
  byStatus: Record<WisdomStatus, number>;
@@ -292,10 +317,23 @@ export interface WisdomStore {
292
317
  by: string;
293
318
  reason: WisdomRetireReason | string;
294
319
  }): Promise<void>;
295
- /** 弱归因结局入账 */
296
- recordOutcomes(events: WisdomOutcomeEvent[]): Promise<void>;
320
+ /** 弱归因结局入账(含 confidence/状态迁移);config 缺省用默认评估参数 */
321
+ recordOutcomes(events: WisdomOutcomeEvent[], config?: WisdomEvaluationConfig): Promise<void>;
297
322
  /** 注入命中轻量入账(S1 applied);不跑 confidence 规划 */
298
323
  touchApplied(ids: string[]): Promise<void>;
324
+ /** 归因窗口:run 收尾记账;返回窗口 id */
325
+ recordAttributionWindow(input: WisdomAttributionWindowInput): Promise<string>;
326
+ /** 未判决窗口(判官取件;createdAt 升序;缺省上限 500,两实现一致) */
327
+ listPendingWindows(limit?: number): Promise<WisdomAttributionWindow[]>;
328
+ /**
329
+ * 标记窗口已判决(`judged_at IS NULL` 原子标记;先标记后发判决事件:宁丢勿重)。
330
+ *
331
+ * @returns 本次真正被标记的 id(已被他方标记的不在内——调用方只对返回集发
332
+ *判决事件,构成跨进程幂等)
333
+ */
334
+ markWindowsJudged(ids: string[], at?: number): Promise<string[]>;
335
+ /** 清理 judgedAt 早于 before 的旧窗口(保留期外) */
336
+ pruneWindows(before: number): Promise<void>;
299
337
  stats(): Promise<WisdomStats>;
300
338
  }
301
339
  /** 概念种类 — 基本层级偏置 */