@octopi-agent/engine 0.102.10 → 0.121.15
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.
- package/dist/builtin-model-info.js +28 -7
- package/dist/config-admin/agent-presets.d.ts +32 -0
- package/dist/config-admin/agent-presets.js +133 -0
- package/dist/config-admin/console-access-key.d.ts +46 -0
- package/dist/config-admin/console-access-key.js +47 -0
- package/dist/config-admin/discover.d.ts +33 -4
- package/dist/config-admin/discover.js +101 -6
- package/dist/config-admin/env.d.ts +11 -0
- package/dist/config-admin/env.js +41 -0
- package/dist/config-admin/error-copy.d.ts +106 -0
- package/dist/config-admin/error-copy.js +287 -0
- package/dist/config-admin/i18n.d.ts +21 -0
- package/dist/config-admin/i18n.js +19 -0
- package/dist/config-admin/index.d.ts +8 -2
- package/dist/config-admin/index.js +4 -1
- package/dist/config-admin/model-presets.d.ts +14 -0
- package/dist/config-admin/model-presets.js +595 -70
- package/dist/config-admin/onboarding-apply.d.ts +83 -0
- package/dist/config-admin/onboarding-apply.js +259 -0
- package/dist/config-admin/onboarding.d.ts +160 -0
- package/dist/config-admin/onboarding.js +298 -0
- package/dist/config-admin/password-policy.d.ts +24 -0
- package/dist/config-admin/password-policy.js +31 -0
- package/dist/config-admin/redact.d.ts +42 -9
- package/dist/config-admin/redact.js +69 -5
- package/dist/config-schema/agent.d.ts +5 -1
- package/dist/config-schema/agent.js +20 -2
- package/dist/config-schema/browser.d.ts +62 -0
- package/dist/config-schema/browser.js +89 -0
- package/dist/config-schema/context.d.ts +7 -2
- package/dist/config-schema/context.js +6 -3
- package/dist/config-schema/engine.d.ts +86 -7
- package/dist/config-schema/engine.js +9 -2
- package/dist/config-schema/governance.d.ts +12 -1
- package/dist/config-schema/governance.js +10 -2
- package/dist/config-schema/models.d.ts +12 -8
- package/dist/config-schema/models.js +16 -1
- package/dist/config-schema/run.d.ts +4 -0
- package/dist/config-schema/run.js +10 -0
- package/dist/config-schema/shared.d.ts +1 -0
- package/dist/config-schema/shared.js +4 -2
- package/dist/config-schema/substrate.d.ts +5 -0
- package/dist/config-schema/substrate.js +8 -0
- package/dist/config.d.ts +116 -10
- package/dist/config.js +109 -13
- package/dist/file-mode.d.ts +67 -0
- package/dist/file-mode.js +182 -0
- package/dist/fork-child.d.ts +82 -0
- package/dist/fork-child.js +123 -0
- package/dist/harness/activation/delegated-run.d.ts +42 -0
- package/dist/harness/activation/delegated-run.js +71 -0
- package/dist/harness/activation/dispatcher.js +4 -0
- package/dist/harness/activation/index.d.ts +1 -0
- package/dist/harness/activation/run-backend.d.ts +92 -0
- package/dist/harness/activation/run-backend.js +16 -0
- package/dist/harness/activation/run-protocol.d.ts +392 -0
- package/dist/harness/activation/run-protocol.js +19 -0
- package/dist/harness/activation/runtime.d.ts +33 -0
- package/dist/harness/activation/runtime.js +119 -28
- package/dist/harness/activation/types.d.ts +19 -2
- package/dist/harness/agent/builder.d.ts +12 -0
- package/dist/harness/agent/builder.js +78 -22
- package/dist/harness/agent/config-bridge.d.ts +10 -1
- package/dist/harness/agent/config-bridge.js +15 -3
- package/dist/harness/agent/registered-tool-adapter.d.ts +27 -0
- package/dist/harness/agent/registered-tool-adapter.js +67 -0
- package/dist/harness/agent/wire-agent-builder.d.ts +2 -0
- package/dist/harness/agent/wire-agent-builder.js +9 -2
- package/dist/harness/capabilities/document/backends/plain.js +2 -1
- package/dist/harness/capabilities/document/legacy/factory.js +3 -2
- package/dist/harness/collaboration/autonomous-subsystem/audit/reader.d.ts +17 -0
- package/dist/harness/collaboration/autonomous-subsystem/audit/reader.js +66 -36
- package/dist/harness/collaboration/autonomous-subsystem/audit/writer.d.ts +6 -2
- package/dist/harness/collaboration/autonomous-subsystem/audit/writer.js +27 -7
- package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.js +13 -0
- package/dist/harness/collaboration/autonomous-subsystem/loader.js +1 -0
- package/dist/harness/collaboration/autonomous-subsystem/runtime.d.ts +11 -0
- package/dist/harness/collaboration/autonomous-subsystem/runtime.js +17 -0
- package/dist/harness/collaboration/autonomous-subsystem/sense/engine.d.ts +13 -3
- package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +48 -39
- package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -0
- package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +4 -0
- package/dist/harness/collaboration/delegation/child-run.d.ts +9 -0
- package/dist/harness/collaboration/delegation/child-run.js +34 -2
- package/dist/harness/collaboration/delegation/registry-types.d.ts +2 -0
- package/dist/harness/collaboration/delegation/service.d.ts +9 -4
- package/dist/harness/collaboration/delegation/service.js +33 -12
- package/dist/harness/collaboration/delegation/store.d.ts +2 -0
- package/dist/harness/collaboration/delegation/store.js +1 -0
- package/dist/harness/collaboration/delegation/types.d.ts +11 -0
- package/dist/harness/collaboration/delegation/wiring.d.ts +2 -0
- package/dist/harness/collaboration/delegation/wiring.js +1 -0
- package/dist/harness/context/capabilities/compact/engine.d.ts +44 -5
- package/dist/harness/context/capabilities/compact/engine.js +127 -39
- package/dist/harness/context/capabilities/compact/index.d.ts +2 -1
- package/dist/harness/context/capabilities/compact/index.js +1 -1
- package/dist/harness/context/capabilities/compact/types.d.ts +59 -9
- package/dist/harness/context/capabilities/summary/gate.d.ts +19 -2
- package/dist/harness/context/capabilities/summary/gate.js +53 -6
- package/dist/harness/context/capabilities/summary/registry.js +20 -0
- package/dist/harness/context/capabilities/summary/tool-binding.js +16 -12
- package/dist/harness/context/capabilities/summary/tool-bindings.d.ts +13 -0
- package/dist/harness/context/capabilities/summary/tool-bindings.js +22 -0
- package/dist/harness/context/capabilities/summary/types.d.ts +16 -0
- package/dist/harness/context/constitution/default-agents.md +85 -0
- package/dist/harness/context/context-size-ledger.js +8 -1
- package/dist/harness/context/default-context-engine.d.ts +100 -6
- package/dist/harness/context/default-context-engine.js +382 -89
- package/dist/harness/context/index.d.ts +2 -1
- package/dist/harness/context/index.js +1 -0
- package/dist/harness/context/layer-health.d.ts +4 -0
- package/dist/harness/context/layer-health.js +4 -0
- package/dist/harness/context/layer-types.d.ts +57 -0
- package/dist/harness/context/layer-types.js +73 -1
- package/dist/harness/context/layers.d.ts +3 -0
- package/dist/harness/context/layers.js +13 -6
- package/dist/harness/context/prefix-fingerprint.d.ts +46 -0
- package/dist/harness/context/prefix-fingerprint.js +52 -0
- package/dist/harness/context/summarize.js +18 -0
- package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
- package/dist/harness/context/system-prompt-assembler.js +5 -2
- package/dist/harness/context/tool-result-aging.d.ts +104 -16
- package/dist/harness/context/tool-result-aging.js +211 -57
- package/dist/harness/context/types.d.ts +71 -4
- package/dist/harness/context/types.js +25 -1
- package/dist/harness/extension/execution-environment/effect-policy.d.ts +4 -3
- package/dist/harness/extension/execution-environment/effect-policy.js +2 -2
- package/dist/harness/extension/execution-environment/privileged-exec.js +4 -1
- package/dist/harness/extension/execution-environment/workspace.js +1 -1
- package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +27 -1
- package/dist/harness/extension/plugin-ecosystem/channel-types.js +11 -2
- package/dist/harness/extension/plugin-ecosystem/client-tools/registry.d.ts +12 -0
- package/dist/harness/extension/plugin-ecosystem/client-tools/registry.js +25 -0
- package/dist/harness/extension/plugin-ecosystem/commands/builtin.js +28 -1
- package/dist/harness/extension/plugin-ecosystem/index.d.ts +1 -0
- package/dist/harness/extension/plugin-ecosystem/index.js +1 -0
- package/dist/harness/extension/plugin-ecosystem/plugins/api.d.ts +168 -1
- package/dist/harness/extension/plugin-ecosystem/plugins/api.js +156 -15
- package/dist/harness/extension/plugin-ecosystem/plugins/contribution-instances.d.ts +95 -0
- package/dist/harness/extension/plugin-ecosystem/plugins/contribution-instances.js +170 -0
- package/dist/harness/extension/plugin-ecosystem/plugins/contribution-kinds.d.ts +178 -0
- package/dist/harness/extension/plugin-ecosystem/plugins/contribution-kinds.js +314 -0
- package/dist/harness/extension/plugin-ecosystem/plugins/contribution-registry.d.ts +40 -5
- package/dist/harness/extension/plugin-ecosystem/plugins/contribution-registry.js +45 -26
- package/dist/harness/extension/plugin-ecosystem/plugins/index.d.ts +1 -1
- package/dist/harness/extension/plugin-ecosystem/plugins/loader.d.ts +11 -1
- package/dist/harness/extension/plugin-ecosystem/plugins/loader.js +42 -76
- package/dist/harness/extension/plugin-ecosystem/plugins/manager.d.ts +30 -1
- package/dist/harness/extension/plugin-ecosystem/plugins/manager.js +46 -0
- package/dist/harness/extension/plugin-ecosystem/plugins/manifest.d.ts +9 -0
- package/dist/harness/extension/plugin-ecosystem/plugins/manifest.js +19 -14
- package/dist/harness/extension/plugin-ecosystem/plugins/staging.d.ts +3 -1
- package/dist/harness/extension/plugin-ecosystem/plugins/staging.js +1 -1
- package/dist/harness/extension/plugin-ecosystem/tools/browser-types.d.ts +333 -0
- package/dist/harness/extension/plugin-ecosystem/tools/browser-types.js +16 -0
- package/dist/harness/extension/plugin-ecosystem/tools/browser.d.ts +64 -0
- package/dist/harness/extension/plugin-ecosystem/tools/browser.js +692 -0
- package/dist/harness/extension/plugin-ecosystem/tools/builtin.d.ts +0 -37
- package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +108 -4
- package/dist/harness/extension/plugin-ecosystem/tools/delegation.js +18 -0
- package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +34 -0
- package/dist/harness/extension/plugin-ecosystem/tools/file-search.d.ts +0 -6
- package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +57 -4
- package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +81 -13
- package/dist/harness/extension/plugin-ecosystem/tools/http.js +5 -0
- package/dist/harness/extension/plugin-ecosystem/tools/knowledge.js +13 -7
- package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +126 -14
- package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +1 -1
- package/dist/harness/extension/plugin-ecosystem/tools/platform.js +44 -5
- package/dist/harness/extension/plugin-ecosystem/tools/tool-bus.js +10 -24
- package/dist/harness/extension/plugin-ecosystem/tools/tool-set.d.ts +7 -0
- package/dist/harness/extension/plugin-ecosystem/tools/tool-set.js +4 -0
- package/dist/harness/governance/credentials/db.d.ts +9 -0
- package/dist/harness/governance/credentials/db.js +122 -31
- package/dist/harness/governance/credentials/store.d.ts +68 -7
- package/dist/harness/governance/credentials/store.js +177 -64
- package/dist/harness/governance/credentials/types.d.ts +13 -2
- package/dist/harness/governance/index.d.ts +1 -0
- package/dist/harness/governance/index.js +1 -0
- package/dist/harness/governance/registry/db.d.ts +32 -0
- package/dist/harness/governance/registry/db.js +142 -0
- package/dist/harness/governance/registry/index.d.ts +9 -0
- package/dist/harness/governance/registry/index.js +9 -0
- package/dist/harness/governance/registry/service.d.ts +381 -0
- package/dist/harness/governance/registry/service.js +825 -0
- package/dist/harness/governance/registry/types.d.ts +77 -0
- package/dist/harness/governance/registry/types.js +7 -0
- package/dist/harness/governance/security/default-security-guard.d.ts +3 -0
- package/dist/harness/governance/security/default-security-guard.js +12 -1
- package/dist/harness/governance/security/risk-evaluator.d.ts +13 -3
- package/dist/harness/governance/security/risk-evaluator.js +307 -21
- package/dist/harness/governance/security/shell-parser-treesitter.js +12 -4
- package/dist/harness/governance/session-acl/tool-rights.d.ts +1 -0
- package/dist/harness/index.d.ts +5 -3
- package/dist/harness/index.js +2 -2
- package/dist/harness/knowledge/boot-config.d.ts +2 -0
- package/dist/harness/knowledge/boot-config.js +2 -0
- package/dist/harness/knowledge/client.d.ts +53 -7
- package/dist/harness/knowledge/client.js +77 -20
- package/dist/harness/knowledge/db.d.ts +16 -0
- package/dist/harness/knowledge/db.js +107 -41
- package/dist/harness/knowledge/engine-thread.js +5 -7
- package/dist/harness/knowledge/grounding.js +4 -1
- package/dist/harness/knowledge/http-app.d.ts +15 -0
- package/dist/harness/knowledge/http-app.js +82 -21
- package/dist/harness/knowledge/http-bridge.d.ts +15 -0
- package/dist/harness/knowledge/http-bridge.js +19 -0
- package/dist/harness/knowledge/knowledge-serve-child.js +2 -3
- package/dist/harness/knowledge/query-service.d.ts +12 -2
- package/dist/harness/knowledge/query-service.js +75 -41
- package/dist/harness/knowledge/query-worker-client.d.ts +5 -1
- package/dist/harness/knowledge/query-worker-client.js +4 -1
- package/dist/harness/knowledge/query-worker.js +5 -3
- package/dist/harness/knowledge/read-http.d.ts +2 -0
- package/dist/harness/knowledge/read-http.js +9 -2
- package/dist/harness/knowledge/retriever.d.ts +1 -1
- package/dist/harness/knowledge/retriever.js +1 -2
- package/dist/harness/knowledge/serve.d.ts +6 -1
- package/dist/harness/knowledge/serve.js +5 -6
- package/dist/harness/knowledge/source-store.d.ts +101 -5
- package/dist/harness/knowledge/source-store.js +297 -71
- package/dist/harness/knowledge/start-service-process.d.ts +27 -8
- package/dist/harness/knowledge/start-service-process.js +49 -90
- package/dist/harness/knowledge/tenant-gate.d.ts +81 -0
- package/dist/harness/knowledge/tenant-gate.js +167 -0
- package/dist/harness/knowledge/writer-service.d.ts +18 -2
- package/dist/harness/knowledge/writer-service.js +80 -16
- package/dist/harness/knowledge/writer-worker-client.d.ts +9 -2
- package/dist/harness/knowledge/writer-worker-client.js +20 -3
- package/dist/harness/knowledge/writer-worker.js +11 -4
- package/dist/harness/memory/backfill-trigger.d.ts +10 -3
- package/dist/harness/memory/backfill-trigger.js +19 -19
- package/dist/harness/memory/cognition-seeds.d.ts +45 -0
- package/dist/harness/memory/cognition-seeds.js +67 -0
- package/dist/harness/memory/cognition.d.ts +12 -3
- package/dist/harness/memory/cognition.js +55 -35
- package/dist/harness/memory/conceptualizer.d.ts +11 -1
- package/dist/harness/memory/conceptualizer.js +10 -1
- package/dist/harness/memory/context-slice.d.ts +42 -0
- package/dist/harness/memory/context-slice.js +197 -0
- package/dist/harness/memory/health-probe.d.ts +8 -2
- package/dist/harness/memory/health-probe.js +10 -13
- package/dist/harness/memory/index.d.ts +5 -1
- package/dist/harness/memory/index.js +3 -1
- package/dist/harness/memory/sqlite/agent-db.d.ts +1 -0
- package/dist/harness/memory/sqlite/agent-db.js +9 -8
- package/dist/harness/memory/sqlite/cognition-store.d.ts +26 -3
- package/dist/harness/memory/sqlite/cognition-store.js +103 -45
- package/dist/harness/memory/sqlite/memory-store.js +4 -0
- package/dist/harness/memory/sqlite/sqlite-vec.d.ts +24 -1
- package/dist/harness/memory/sqlite/sqlite-vec.js +37 -1
- package/dist/harness/memory/types.d.ts +18 -2
- package/dist/harness/observability/observer/hub.d.ts +10 -0
- package/dist/harness/observability/observer/hub.js +95 -2
- package/dist/harness/run/agent/agent.js +3 -2
- package/dist/harness/run/concurrency/tool-validator.js +4 -3
- package/dist/harness/run/reliability/run-agent.d.ts +22 -0
- package/dist/harness/run/reliability/run-agent.js +79 -10
- package/dist/harness/run/run-host.d.ts +302 -0
- package/dist/harness/run/run-host.js +978 -0
- package/dist/harness/run/run-scope.d.ts +11 -0
- package/dist/harness/run/run-scope.js +19 -1
- package/dist/harness/run/runner.d.ts +149 -22
- package/dist/harness/run/runner.js +352 -35
- package/dist/harness/session/in-memory-store.js +13 -1
- package/dist/harness/session/schedules/service.d.ts +10 -2
- package/dist/harness/session/schedules/service.js +13 -2
- package/dist/harness/session/tasks/tools.js +12 -0
- package/dist/harness/session/types.d.ts +10 -14
- package/dist/harness/shared/events/agent-event-map.d.ts +29 -0
- package/dist/harness/shared/types/agent-definition.d.ts +6 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/integration/agent-runtime/channel-message-source.d.ts +3 -1
- package/dist/integration/agent-runtime/channel-message-source.js +4 -3
- package/dist/integration/browser/camoufox.d.ts +40 -0
- package/dist/integration/browser/camoufox.js +80 -0
- package/dist/integration/browser/index.d.ts +91 -0
- package/dist/integration/browser/index.js +110 -0
- package/dist/integration/browser/install.d.ts +47 -0
- package/dist/integration/browser/install.js +214 -0
- package/dist/integration/browser/playwright.d.ts +224 -0
- package/dist/integration/browser/playwright.js +925 -0
- package/dist/integration/browser/service.d.ts +41 -0
- package/dist/integration/browser/service.js +181 -0
- package/dist/integration/browser/stealth.d.ts +42 -0
- package/dist/integration/browser/stealth.js +104 -0
- package/dist/integration/providers/anthropic-message-normalize.d.ts +20 -0
- package/dist/integration/providers/anthropic-message-normalize.js +48 -0
- package/dist/integration/providers/anthropic.js +27 -2
- package/dist/integration/providers/fetch-timeout.d.ts +17 -0
- package/dist/integration/providers/fetch-timeout.js +24 -0
- package/dist/integration/providers/openai.d.ts +8 -0
- package/dist/integration/providers/openai.js +41 -1
- package/dist/integration/providers/wire-dump-diff.js +2 -1
- package/dist/integration/providers/wire-dump.d.ts +56 -2
- package/dist/integration/providers/wire-dump.js +119 -6
- package/dist/integration/storage/archive-manager.d.ts +14 -2
- package/dist/integration/storage/archive-manager.js +24 -8
- package/dist/integration/storage/atomic-tmp.d.ts +12 -0
- package/dist/integration/storage/atomic-tmp.js +36 -0
- package/dist/integration/storage/jsonl.d.ts +9 -0
- package/dist/integration/storage/jsonl.js +137 -38
- package/dist/integration/storage/session-index.d.ts +5 -0
- package/dist/integration/storage/session-index.js +25 -4
- package/dist/integration/tools/assemble.d.ts +50 -0
- package/dist/integration/tools/assemble.js +137 -0
- package/dist/paths.d.ts +18 -0
- package/dist/paths.js +36 -0
- package/dist/subsystems/cognition-steward/conceptualize/config.yaml +3 -1
- package/dist/subsystems/cognition-steward/conceptualize/handler.js +74 -5
- package/dist/subsystems/cognition-steward/consolidate/SUBSYSTEM.md +3 -2
- package/dist/subsystems/cognition-steward/consolidate/config.yaml +11 -2
- package/dist/subsystems/cognition-steward/consolidate/handler.d.ts +6 -3
- package/dist/subsystems/cognition-steward/consolidate/handler.js +266 -28
- package/dist/subsystems/memory-steward/backfill/handler.js +3 -2
- package/dist/subsystems/memory-steward/govern/config.yaml +6 -1
- package/dist/subsystems/wisdom-steward/attribute/config.yaml +5 -1
- package/dist/subsystems/wisdom-steward/formation/config.yaml +3 -0
- package/dist/subsystems/wisdom-steward/govern/config.yaml +6 -1
- package/package.json +5 -3
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ContextSlice 提取 — session 消息 + evidence 锚定 → 证据周边语境(±N 条消息)
|
|
3
|
+
*
|
|
4
|
+
* 概念化输入包要求 contextSlice(arch/cognition-graph-formation.md D1)。
|
|
5
|
+
* evidence 多为缩略引文(「…」截断、句读改写),整串精确匹配常失败,
|
|
6
|
+
* 因此按省略号/句读拆片段、以最长命中片段定位锚点消息,再截两侧窗口。
|
|
7
|
+
* 找不到锚点返回空串,由调用方显式失败——禁止用无关窗口冒充语境。
|
|
8
|
+
*
|
|
9
|
+
* 锚定域:user / assistant / tool 的文本消息(evidence 可能引用工具输出,
|
|
10
|
+
* 如文件路径与命令结果)。引擎载体插槽经 `isEngineCarrierSource` 单源过滤。
|
|
11
|
+
*
|
|
12
|
+
* @module harness/memory/context-slice
|
|
13
|
+
*/
|
|
14
|
+
import { elidedCharsMarker } from '@octopi-agent/core/elision.js';
|
|
15
|
+
import { getTextContent } from '@octopi-agent/core/types.js';
|
|
16
|
+
import { isEngineCarrierSource } from '../context/layer-types.js';
|
|
17
|
+
/** 缺省窗口:锚点两侧各取的实质消息条数 */
|
|
18
|
+
export const DEFAULT_CONTEXT_WINDOW_MESSAGES = 2;
|
|
19
|
+
/** 缺省切片字符预算(软上限;elision 标记会略超,见 {@link extractContextSlice}) */
|
|
20
|
+
export const DEFAULT_CONTEXT_SLICE_MAX_CHARS = 4000;
|
|
21
|
+
/** 引号类字符:匹配前剥除(evidence 引文与消息原文的引号使用不一致) */
|
|
22
|
+
const QUOTE_CHARS_RE = /[「」『』“”"'‘’()()【】[\]]/g;
|
|
23
|
+
/**
|
|
24
|
+
* 匹配键归一:剥引号 + 空白折叠 + 拉丁小写(CJK 不受影响)。
|
|
25
|
+
*
|
|
26
|
+
* @param text - 原文
|
|
27
|
+
* @returns 用于包含匹配的归一化文本
|
|
28
|
+
*/
|
|
29
|
+
function matchKey(text) {
|
|
30
|
+
return text.replace(QUOTE_CHARS_RE, ' ').replace(/\s+/g, ' ').trim().toLowerCase();
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* evidence → 候选片段:按省略号/句读/换行/**引号与括号边界**拆开(相邻引文
|
|
34
|
+
* 不粘连成跨引文长片段),归一后保留过阈值的片段。
|
|
35
|
+
*
|
|
36
|
+
* @param evidence - 记忆证据原文
|
|
37
|
+
* @returns 归一化候选片段(保持出现顺序)
|
|
38
|
+
*/
|
|
39
|
+
function evidenceFragments(evidence) {
|
|
40
|
+
const rough = evidence.split(/[…⋯]|\.{3,}|[。!?!?\n;;,,::「」『』“”"'‘’()()【】[\]]/);
|
|
41
|
+
const out = [];
|
|
42
|
+
for (const piece of rough) {
|
|
43
|
+
const cleaned = matchKey(piece);
|
|
44
|
+
if (fragmentAcceptable(cleaned))
|
|
45
|
+
out.push(cleaned);
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
/** CJK 字符(中日韩音节块)——单字信息量高,短引文常足以唯一锚定 */
|
|
50
|
+
const CJK_RE = /[ -〿㐀-䶿一-鿿가-]/;
|
|
51
|
+
/** evidence 片段最小长度:拉丁 ≥8(短通用片段易误锚);含 CJK ≥6(误锚比无锚更糟,宁可不锚定) */
|
|
52
|
+
function fragmentAcceptable(fragment) {
|
|
53
|
+
return fragment.length >= (CJK_RE.test(fragment) ? 6 : 8);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* 工具调用/结果的文本侧写 — evidence 常引用工具输出与调用参数。
|
|
57
|
+
*
|
|
58
|
+
* SessionData 的 toolCalls/toolResults 是一等字段(content 常为空),只取
|
|
59
|
+
* name/purpose/args/result 的文本形态;条目形状未知时跳过。
|
|
60
|
+
*
|
|
61
|
+
* @param value - toolCalls 或 toolResults 数组(未知形状)
|
|
62
|
+
* @returns 侧写文本行(可能为空数组)
|
|
63
|
+
*/
|
|
64
|
+
function toolSidecarLines(value) {
|
|
65
|
+
if (!Array.isArray(value))
|
|
66
|
+
return [];
|
|
67
|
+
const lines = [];
|
|
68
|
+
for (const entry of value) {
|
|
69
|
+
if (!entry || typeof entry !== 'object')
|
|
70
|
+
continue;
|
|
71
|
+
const e = entry;
|
|
72
|
+
const parts = [];
|
|
73
|
+
if (typeof e.name === 'string' && e.name)
|
|
74
|
+
parts.push(e.name);
|
|
75
|
+
if (typeof e.purpose === 'string' && e.purpose)
|
|
76
|
+
parts.push(e.purpose);
|
|
77
|
+
const payload = e.result ?? e.arguments ?? e.input ?? e.args;
|
|
78
|
+
if (payload !== undefined && payload !== null) {
|
|
79
|
+
parts.push(typeof payload === 'string' ? payload : JSON.stringify(payload));
|
|
80
|
+
}
|
|
81
|
+
const line = parts.join(' ').trim();
|
|
82
|
+
if (line)
|
|
83
|
+
lines.push(line);
|
|
84
|
+
}
|
|
85
|
+
return lines;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* 消息是否是可作语境的实质消息。
|
|
89
|
+
*
|
|
90
|
+
* 过滤口径:引擎载体插槽(快照/grounding/附件/摘要/hint/turn 闭标/停止说明)
|
|
91
|
+
* 一律不算语境——快照含记忆原文回显,入语境即自我复制;turnEnd 以 user 角色
|
|
92
|
+
* 落盘但不是发言。角色限 user/assistant/tool:evidence 可能引用工具输出
|
|
93
|
+
* (文件路径、命令结果),故 tool 文本也是合法锚点。
|
|
94
|
+
*
|
|
95
|
+
* @param message - 会话消息(未知形状)
|
|
96
|
+
* @returns 实质消息的文本与角色,否则 null
|
|
97
|
+
*/
|
|
98
|
+
function asSubstantive(message) {
|
|
99
|
+
if (!message || typeof message !== 'object')
|
|
100
|
+
return null;
|
|
101
|
+
const m = message;
|
|
102
|
+
if (isEngineCarrierSource(m.metadata?.source))
|
|
103
|
+
return null;
|
|
104
|
+
if (m.role !== 'user' && m.role !== 'assistant' && m.role !== 'tool')
|
|
105
|
+
return null;
|
|
106
|
+
const raw = m.content;
|
|
107
|
+
// 只取文本块:ContentBlock[] 整体 stringify 会把 tool_use 参数/图片塞进语境
|
|
108
|
+
const contentText = typeof raw === 'string' ? raw : Array.isArray(raw) ? getTextContent(raw) : '';
|
|
109
|
+
// 工具文本是一等字段(content 常为空),必须并入锚定域:evidence 常引用工具输出
|
|
110
|
+
const sidecar = [...toolSidecarLines(m.toolCalls), ...toolSidecarLines(m.toolResults)].join('\n');
|
|
111
|
+
const text = [contentText.trim(), sidecar].filter(Boolean).join('\n');
|
|
112
|
+
if (!text)
|
|
113
|
+
return null;
|
|
114
|
+
return { text, role: String(m.role) };
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* 从会话消息中提取 evidence 周边语境切片。
|
|
118
|
+
*
|
|
119
|
+
* 定位策略:evidence 拆片段后取「能命中某条实质消息的最长片段」(等长片段取
|
|
120
|
+
* evidence 中先出现者),同一片段取最后一次出现的消息(贴近记忆产生时的活跃
|
|
121
|
+
* 语境),锚点 ±windowMessages 条实质消息。
|
|
122
|
+
*
|
|
123
|
+
* 截断:锚点行优先保留,两侧邻居按余量裁剪并以 elision 标记标注。
|
|
124
|
+
* maxChars 为软上限(标记文本会略超)。锚点行自身超预算时保头尾两段,
|
|
125
|
+
* 行内中段(含命中片段本身)可能被裁。
|
|
126
|
+
*
|
|
127
|
+
* @param options - 消息序列 + evidence + 窗口/预算
|
|
128
|
+
* @returns `[role] text` 行拼接的语境切片;无锚点或无实质消息时返回空串
|
|
129
|
+
*/
|
|
130
|
+
export function extractContextSlice(options) {
|
|
131
|
+
const { messages, evidence } = options;
|
|
132
|
+
const windowMessages = Math.max(0, options.windowMessages ?? DEFAULT_CONTEXT_WINDOW_MESSAGES);
|
|
133
|
+
const maxChars = Math.max(1, options.maxChars ?? DEFAULT_CONTEXT_SLICE_MAX_CHARS);
|
|
134
|
+
const substantive = [];
|
|
135
|
+
for (const message of messages) {
|
|
136
|
+
const item = asSubstantive(message);
|
|
137
|
+
if (item)
|
|
138
|
+
substantive.push(item);
|
|
139
|
+
}
|
|
140
|
+
const fragments = evidenceFragments(evidence);
|
|
141
|
+
if (substantive.length === 0 || fragments.length === 0)
|
|
142
|
+
return '';
|
|
143
|
+
const keys = substantive.map((item) => matchKey(item.text));
|
|
144
|
+
let bestLen = 0;
|
|
145
|
+
let anchorIndex = -1;
|
|
146
|
+
for (const fragment of fragments) {
|
|
147
|
+
let lastHit = -1;
|
|
148
|
+
for (let i = 0; i < keys.length; i++) {
|
|
149
|
+
if (keys[i].includes(fragment))
|
|
150
|
+
lastHit = i;
|
|
151
|
+
}
|
|
152
|
+
if (lastHit >= 0 && fragment.length > bestLen) {
|
|
153
|
+
bestLen = fragment.length;
|
|
154
|
+
anchorIndex = lastHit;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (anchorIndex < 0)
|
|
158
|
+
return '';
|
|
159
|
+
const from = Math.max(0, anchorIndex - windowMessages);
|
|
160
|
+
const to = Math.min(substantive.length, anchorIndex + windowMessages + 1);
|
|
161
|
+
const anchorPos = anchorIndex - from;
|
|
162
|
+
const lines = substantive
|
|
163
|
+
.slice(from, to)
|
|
164
|
+
.map((item) => `[${item.role}] ${item.text}`);
|
|
165
|
+
const joined = lines.join('\n');
|
|
166
|
+
if (joined.length <= maxChars)
|
|
167
|
+
return joined;
|
|
168
|
+
// 锚点行在 joined 内的字符区间
|
|
169
|
+
let anchorStart = 0;
|
|
170
|
+
for (let i = 0; i < anchorPos; i++)
|
|
171
|
+
anchorStart += lines[i].length + 1;
|
|
172
|
+
const anchorEnd = anchorStart + lines[anchorPos].length;
|
|
173
|
+
if (anchorEnd - anchorStart >= maxChars) {
|
|
174
|
+
const line = lines[anchorPos];
|
|
175
|
+
const headBudget = Math.floor(maxChars * 0.4);
|
|
176
|
+
const tailBudget = Math.max(0, maxChars - headBudget - 20);
|
|
177
|
+
const tail = tailBudget > 0 ? line.slice(-tailBudget) : '';
|
|
178
|
+
return `${line.slice(0, headBudget)}\n${elidedCharsMarker(line.length - headBudget - tailBudget)}\n${tail}`;
|
|
179
|
+
}
|
|
180
|
+
const room = maxChars - (anchorEnd - anchorStart);
|
|
181
|
+
let left = Math.min(anchorStart, Math.floor(room / 2));
|
|
182
|
+
const right = Math.min(joined.length - anchorEnd, room - left);
|
|
183
|
+
left = Math.min(anchorStart, room - right);
|
|
184
|
+
const start = anchorStart - left;
|
|
185
|
+
const end = anchorEnd + right;
|
|
186
|
+
const parts = [];
|
|
187
|
+
if (start > 0)
|
|
188
|
+
parts.push(elidedCharsMarker(start));
|
|
189
|
+
if (left > 0)
|
|
190
|
+
parts.push(joined.slice(start, anchorStart));
|
|
191
|
+
parts.push(lines[anchorPos]);
|
|
192
|
+
if (right > 0)
|
|
193
|
+
parts.push(joined.slice(anchorEnd, end));
|
|
194
|
+
if (end < joined.length)
|
|
195
|
+
parts.push(elidedCharsMarker(joined.length - end));
|
|
196
|
+
return parts.join('\n');
|
|
197
|
+
}
|
|
@@ -27,9 +27,15 @@ export declare class MemoryHealthProbe {
|
|
|
27
27
|
private readonly limits;
|
|
28
28
|
private readonly shadowBacklogLimit;
|
|
29
29
|
private readonly now;
|
|
30
|
-
private timer?;
|
|
31
30
|
constructor(options: MemoryHealthProbeOptions);
|
|
32
|
-
|
|
31
|
+
/** 脉搏声明(P0c A′):供装配层聚合成实例级 PulseSpec 列表 */
|
|
32
|
+
pulseSpecs(): Array<{
|
|
33
|
+
key: string;
|
|
34
|
+
intervalMs: number;
|
|
35
|
+
}>;
|
|
36
|
+
/** 脉搏入口:gateway 单发驱动一次检查。未知 key fail-loud。 */
|
|
37
|
+
pulse(key: string): Promise<string[]>;
|
|
38
|
+
/** P0c A′:检查已改脉搏驱动,无 self-arm 定时器可停(保留调用面兼容)。 */
|
|
33
39
|
stop(): void;
|
|
34
40
|
/** 立即检查一轮;返回发出的事件类型 */
|
|
35
41
|
check(): Promise<string[]>;
|
|
@@ -19,7 +19,6 @@ export class MemoryHealthProbe {
|
|
|
19
19
|
limits;
|
|
20
20
|
shadowBacklogLimit;
|
|
21
21
|
now;
|
|
22
|
-
timer;
|
|
23
22
|
constructor(options) {
|
|
24
23
|
this.events = options.events;
|
|
25
24
|
this.memoryStore = options.memoryStore;
|
|
@@ -28,20 +27,18 @@ export class MemoryHealthProbe {
|
|
|
28
27
|
this.shadowBacklogLimit = options.shadowBacklogLimit ?? 50;
|
|
29
28
|
this.now = options.now ?? (() => Date.now());
|
|
30
29
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
this.timer = setInterval(() => {
|
|
35
|
-
void this.check();
|
|
36
|
-
}, this.intervalMs);
|
|
37
|
-
this.timer.unref?.();
|
|
30
|
+
/** 脉搏声明(P0c A′):供装配层聚合成实例级 PulseSpec 列表 */
|
|
31
|
+
pulseSpecs() {
|
|
32
|
+
return [{ key: 'memory.health', intervalMs: this.intervalMs }];
|
|
38
33
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
this.
|
|
43
|
-
}
|
|
34
|
+
/** 脉搏入口:gateway 单发驱动一次检查。未知 key fail-loud。 */
|
|
35
|
+
async pulse(key) {
|
|
36
|
+
if (key === 'memory.health')
|
|
37
|
+
return this.check();
|
|
38
|
+
throw new Error(`memory-health-probe: unknown pulse key "${key}"`);
|
|
44
39
|
}
|
|
40
|
+
/** P0c A′:检查已改脉搏驱动,无 self-arm 定时器可停(保留调用面兼容)。 */
|
|
41
|
+
stop() { }
|
|
45
42
|
/** 立即检查一轮;返回发出的事件类型 */
|
|
46
43
|
async check() {
|
|
47
44
|
const emitted = [];
|
|
@@ -15,14 +15,18 @@ export { extractCitations, collectRunAssistantTexts, recordWisdomRunWindow, sele
|
|
|
15
15
|
export type { WisdomRunWindowInfo, AttributionCandidate, AttributionBatch, AttributionVerdict, } from './wisdom-attribution.js';
|
|
16
16
|
export { emitWisdomEvaluateRequest, emitWisdomGoverned, WISDOM_EVALUATE_REQUEST_EVENT, WISDOM_GOVERNED_EVENT, } from './wisdom-events.js';
|
|
17
17
|
export type { WisdomEvaluateRequestPayload } from './wisdom-events.js';
|
|
18
|
+
export { normName, deriveQuerySeeds, createSeedMatcher, } from './cognition-seeds.js';
|
|
19
|
+
export type { DeriveQuerySeedsOptions, SeedMatcher } from './cognition-seeds.js';
|
|
18
20
|
export { evaluateConceptGate, licenseEdge, edgeBasisFromLicense, normalizeForCue, } from './cognition-gates.js';
|
|
19
21
|
export type { ConceptGateOutcome, EdgeLicenseInput, EdgeLicenseOutcome, } from './cognition-gates.js';
|
|
20
22
|
export { DEFAULT_EDGE_DECAY_PER_DAY, DEFAULT_EDGE_DECAY_FLOOR, DEFAULT_RETRIEVE_STATUSES, decayMultiplier, nextEdgeStrength, hebbianStrengthen, counterEvidenceWeaken, } from './cognition-decay.js';
|
|
21
23
|
export type { EdgeDecayConfig } from './cognition-decay.js';
|
|
22
|
-
export { conceptualizeAndAdmit, parseConceptualizerJson, } from './conceptualizer.js';
|
|
24
|
+
export { conceptualizeAndAdmit, hasSufficientContext, parseConceptualizerJson, } from './conceptualizer.js';
|
|
23
25
|
export type { ConceptualizerInput, ConceptualizerResult, ConceptualizerNodeOut, ConceptualizerEdgeOut, RawConceptualizerOutput, } from './conceptualizer.js';
|
|
24
26
|
export { COGNITIZE_REQUEST_EVENT, emitConceptualizeRequest, } from './cognition-trigger.js';
|
|
25
27
|
export type { ConceptualizeRequestPayload } from './cognition-trigger.js';
|
|
28
|
+
export { DEFAULT_CONTEXT_SLICE_MAX_CHARS, DEFAULT_CONTEXT_WINDOW_MESSAGES, extractContextSlice, } from './context-slice.js';
|
|
29
|
+
export type { ContextSliceOptions } from './context-slice.js';
|
|
26
30
|
export { InMemoryMemoryStore } from './store.js';
|
|
27
31
|
export { InMemoryWisdomStore } from './wisdom.js';
|
|
28
32
|
export { InMemoryConceptGraph } from './cognition.js';
|
|
@@ -13,10 +13,12 @@ export { parseWisdomFormationJson, normalizeWisdomFormation, toAdmitWisdomInput,
|
|
|
13
13
|
export { extractCitations, collectRunAssistantTexts, recordWisdomRunWindow, selectAttributionCandidates, planAttributionBatch, buildAttributionDigest, parseAttributionVerdicts, verdictsToOutcomeEvents, } from './wisdom-attribution.js';
|
|
14
14
|
export { emitWisdomEvaluateRequest, emitWisdomGoverned, WISDOM_EVALUATE_REQUEST_EVENT, WISDOM_GOVERNED_EVENT, } from './wisdom-events.js';
|
|
15
15
|
// ── Cognition 门控 / 可塑 / 概念化 ──
|
|
16
|
+
export { normName, deriveQuerySeeds, createSeedMatcher, } from './cognition-seeds.js';
|
|
16
17
|
export { evaluateConceptGate, licenseEdge, edgeBasisFromLicense, normalizeForCue, } from './cognition-gates.js';
|
|
17
18
|
export { DEFAULT_EDGE_DECAY_PER_DAY, DEFAULT_EDGE_DECAY_FLOOR, DEFAULT_RETRIEVE_STATUSES, decayMultiplier, nextEdgeStrength, hebbianStrengthen, counterEvidenceWeaken, } from './cognition-decay.js';
|
|
18
|
-
export { conceptualizeAndAdmit, parseConceptualizerJson, } from './conceptualizer.js';
|
|
19
|
+
export { conceptualizeAndAdmit, hasSufficientContext, parseConceptualizerJson, } from './conceptualizer.js';
|
|
19
20
|
export { COGNITIZE_REQUEST_EVENT, emitConceptualizeRequest, } from './cognition-trigger.js';
|
|
21
|
+
export { DEFAULT_CONTEXT_SLICE_MAX_CHARS, DEFAULT_CONTEXT_WINDOW_MESSAGES, extractContextSlice, } from './context-slice.js';
|
|
20
22
|
// ── 内存实现 ──
|
|
21
23
|
export { InMemoryMemoryStore } from './store.js';
|
|
22
24
|
export { InMemoryWisdomStore } from './wisdom.js';
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
import { randomUUID } from 'node:crypto';
|
|
15
15
|
import { mkdir } from 'node:fs/promises';
|
|
16
16
|
import { dirname } from 'node:path';
|
|
17
|
-
import { ensureMemoryVecTable,
|
|
17
|
+
import { ensureMemoryVecTable, loadSqliteVecOrDegrade } from './sqlite-vec.js';
|
|
18
18
|
export class AgentDatabase {
|
|
19
19
|
db;
|
|
20
20
|
_sqliteVec = false;
|
|
@@ -55,14 +55,15 @@ export class AgentDatabase {
|
|
|
55
55
|
agentDb.createTables();
|
|
56
56
|
// 可选:sqlite-vec + memory_vec 虚拟表
|
|
57
57
|
const vecOpt = options?.sqliteVec;
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
58
|
+
// AgentDatabase 缺省 = 不加载(与 KnowledgeDatabase 的「缺省尝试」不同;缺省在类上显式归一,防再吃 undefined 语义)
|
|
59
|
+
agentDb._sqliteVec = await loadSqliteVecOrDegrade(db, vecOpt ?? false, 'agent.db');
|
|
60
|
+
if (agentDb._sqliteVec && options?.vectorDimensions) {
|
|
61
|
+
const ok = ensureMemoryVecTable(db, options.vectorDimensions);
|
|
62
|
+
// require 档覆盖「实际可用」而不仅是扩展加载:建表失败同样 fail-loud(契约一致,M4)
|
|
63
|
+
if (!ok && typeof vecOpt === 'object' && vecOpt.require === true) {
|
|
64
|
+
throw new Error("sqlite_vec_table_failed: memory_vec table creation failed under vectorEngine='sqlite-vec'");
|
|
65
65
|
}
|
|
66
|
+
agentDb._vecDimensions = ok ? options.vectorDimensions : null;
|
|
66
67
|
}
|
|
67
68
|
return agentDb;
|
|
68
69
|
}
|
|
@@ -6,13 +6,17 @@
|
|
|
6
6
|
*
|
|
7
7
|
* @module
|
|
8
8
|
*/
|
|
9
|
-
import type { ActivatedGraph, AdmitConceptInput, AdmitConceptResult, AdmitEdgeInput, AdmitEdgeResult, ConceptGraph, ConceptGraphStats, ConceptGraphStore, DecayResult, MergeCandidate, SpreadingActivateOptions } from '../cognition-types.js';
|
|
9
|
+
import type { ActivatedGraph, AdmitConceptInput, AdmitConceptResult, AdmitEdgeInput, AdmitEdgeResult, ConceptGraph, ConceptGraphStats, ConceptGraphStore, ConceptKind, DecayResult, MergeCandidate, SpreadingActivateOptions } from '../cognition-types.js';
|
|
10
10
|
import { AgentDatabase } from './agent-db.js';
|
|
11
11
|
import type { EmbeddingProvider } from './embedding.js';
|
|
12
12
|
export interface SqliteConceptGraphOptions {
|
|
13
13
|
embeddingProvider?: EmbeddingProvider | null;
|
|
14
|
-
/**
|
|
14
|
+
/** 强同义距离:≤ 此值的近邻候选在 fingerprintDiff 落 `strong_near`(供裁决优先);不再触发自动合并(跨名一律候选) */
|
|
15
15
|
mergeThreshold?: number;
|
|
16
|
+
/** 语义种子距离带(相关性域:查询→概念名,实测相关对 0.41–0.59);默认 0.65,与 merge 同一性带不同域 */
|
|
17
|
+
semanticSeedMaxDistance?: number;
|
|
18
|
+
/** 语义种子查询嵌入超时(毫秒;热路径防无界延迟,超时降级空种子);默认 5000 */
|
|
19
|
+
semanticSeedEmbedTimeoutMs?: number;
|
|
16
20
|
/** 近阈带上界;[lo, hi) 写 merge_candidates,默认 0.35 */
|
|
17
21
|
candidateBandHi?: number;
|
|
18
22
|
/** capacity 软顶 */
|
|
@@ -29,6 +33,10 @@ export declare class SqliteConceptGraph implements ConceptGraphStore {
|
|
|
29
33
|
private embedding;
|
|
30
34
|
private mergeThreshold;
|
|
31
35
|
private candidateBandHi;
|
|
36
|
+
private semanticSeedMaxDistance;
|
|
37
|
+
private semanticSeedEmbedTimeoutMs;
|
|
38
|
+
/** 已解析向量缓存:key=概念 id,value=updated_at 指纹 + 向量(写入即换指纹,天然失效) */
|
|
39
|
+
private parsedVectorCache;
|
|
32
40
|
private stopNodes;
|
|
33
41
|
private stopEdges;
|
|
34
42
|
private decayFloor;
|
|
@@ -38,6 +46,7 @@ export declare class SqliteConceptGraph implements ConceptGraphStore {
|
|
|
38
46
|
private rowToNode;
|
|
39
47
|
private rowToEdge;
|
|
40
48
|
admitConcept(input: AdmitConceptInput): Promise<AdmitConceptResult>;
|
|
49
|
+
/** 义项指纹冲突:仅 kind 不同。domain 是多值标签不参与义项判定(同名同 kind 合并且 domain 取并集) */
|
|
41
50
|
private fingerprintConflict;
|
|
42
51
|
private insertConcept;
|
|
43
52
|
private insertMergeCandidate;
|
|
@@ -53,7 +62,21 @@ export declare class SqliteConceptGraph implements ConceptGraphStore {
|
|
|
53
62
|
note?: string;
|
|
54
63
|
}): Promise<void>;
|
|
55
64
|
listMergeCandidates(limit?: number): Promise<MergeCandidate[]>;
|
|
56
|
-
|
|
65
|
+
/** 语义种子能力:已注 embeddingProvider 才可做查询近邻 */
|
|
66
|
+
get supportsSemanticSeeds(): boolean;
|
|
67
|
+
/**
|
|
68
|
+
* 查询语义种子:查询文本经自有 provider 嵌入后,对已存向量做近邻扫描。
|
|
69
|
+
* 距离带用 `semanticSeedMaxDistance`(相关性域,默认 0.65)——与 merge 的同一性带
|
|
70
|
+
* (candidateBandHi 0.35)不同域:真模型下「查询句→短概念名」相关对实测 0.41–0.59。
|
|
71
|
+
*
|
|
72
|
+
* @param query - 查询文本
|
|
73
|
+
* @param k - 种子上限(缺省 4)
|
|
74
|
+
* @returns 概念名列表(近者优先);provider 缺失/嵌入失败/无近邻/维度失配行 → 空/跳过(增强路径不 fail)
|
|
75
|
+
*/
|
|
76
|
+
semanticSeeds(query: string, k?: number): Promise<string[]>;
|
|
77
|
+
resolveMerge(id: string, action: 'merge' | 'keep_split' | 'drop', options?: {
|
|
78
|
+
canonicalKind?: ConceptKind;
|
|
79
|
+
}): Promise<void>;
|
|
57
80
|
reinforce(input: {
|
|
58
81
|
nodeIds?: string[];
|
|
59
82
|
edgeIds?: string[];
|
|
@@ -8,23 +8,34 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { counterEvidenceWeaken, DEFAULT_EDGE_DECAY_FLOOR, DEFAULT_RETRIEVE_STATUSES, hebbianStrengthen, nextEdgeStrength, } from '../cognition-decay.js';
|
|
10
10
|
import { evaluateConceptGate, licenseEdge, normalizeForCue } from '../cognition-gates.js';
|
|
11
|
+
import { createSeedMatcher, normName } from '../cognition-seeds.js';
|
|
11
12
|
import { AgentDatabase } from './agent-db.js';
|
|
12
13
|
import { cosineDistance, parseEmbedding, serializeEmbedding } from './vector-search.js';
|
|
13
14
|
function daysBetween(a, b) {
|
|
14
15
|
return Math.max(0, (b - a) / 86_400_000);
|
|
15
16
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
17
|
+
/** 增强路径限时:超时拒绝;内层 Promise 终态经 then 兜底,无悬挂未处理拒绝 */
|
|
18
|
+
function withTimeout(p, ms) {
|
|
19
|
+
return new Promise((resolve, reject) => {
|
|
20
|
+
const t = setTimeout(() => reject(new Error(`timeout after ${ms}ms`)), ms);
|
|
21
|
+
p.then((v) => {
|
|
22
|
+
clearTimeout(t);
|
|
23
|
+
resolve(v);
|
|
24
|
+
}, (e) => {
|
|
25
|
+
clearTimeout(t);
|
|
26
|
+
reject(e);
|
|
27
|
+
});
|
|
28
|
+
});
|
|
22
29
|
}
|
|
23
30
|
export class SqliteConceptGraph {
|
|
24
31
|
db;
|
|
25
32
|
embedding;
|
|
26
33
|
mergeThreshold;
|
|
27
34
|
candidateBandHi;
|
|
35
|
+
semanticSeedMaxDistance;
|
|
36
|
+
semanticSeedEmbedTimeoutMs;
|
|
37
|
+
/** 已解析向量缓存:key=概念 id,value=updated_at 指纹 + 向量(写入即换指纹,天然失效) */
|
|
38
|
+
parsedVectorCache = new Map();
|
|
28
39
|
stopNodes;
|
|
29
40
|
stopEdges;
|
|
30
41
|
decayFloor;
|
|
@@ -34,6 +45,8 @@ export class SqliteConceptGraph {
|
|
|
34
45
|
this.embedding = options?.embeddingProvider ?? null;
|
|
35
46
|
this.mergeThreshold = options?.mergeThreshold ?? 0.2;
|
|
36
47
|
this.candidateBandHi = options?.candidateBandHi ?? 0.35;
|
|
48
|
+
this.semanticSeedMaxDistance = options?.semanticSeedMaxDistance ?? 0.65;
|
|
49
|
+
this.semanticSeedEmbedTimeoutMs = options?.semanticSeedEmbedTimeoutMs ?? 5000;
|
|
37
50
|
this.stopNodes = options?.stopNodes ?? 10_000;
|
|
38
51
|
this.stopEdges = options?.stopEdges ?? 40_000;
|
|
39
52
|
this.decayFloor = options?.decayFloor ?? DEFAULT_EDGE_DECAY_FLOOR;
|
|
@@ -99,8 +112,10 @@ export class SqliteConceptGraph {
|
|
|
99
112
|
return { action: 'rejected', reason: gate.reason, message: gate.message };
|
|
100
113
|
}
|
|
101
114
|
const nameKey = normName(input.name);
|
|
115
|
+
// 注意:SQLite LOWER() 仅折 ASCII,与 JS toLowerCase 的 Unicode 折叠有别(CJK 无碍)——
|
|
116
|
+
// 归一根治(name_key 列)见 arch/open-problems OP-9R 遗留
|
|
102
117
|
const existing = this.db.raw
|
|
103
|
-
.prepare('SELECT * FROM concepts WHERE LOWER(name) = ?')
|
|
118
|
+
.prepare('SELECT * FROM concepts WHERE LOWER(name) = ? ORDER BY created_at ASC, id ASC')
|
|
104
119
|
.all(nameKey);
|
|
105
120
|
// 同名多义项:指纹兼容则合并,冲突则新建 + merge_candidate
|
|
106
121
|
const conflicts = [];
|
|
@@ -112,9 +127,10 @@ export class SqliteConceptGraph {
|
|
|
112
127
|
continue;
|
|
113
128
|
}
|
|
114
129
|
const memIds = new Set([...node.memoryIds, ...(input.memoryIds ?? [])]);
|
|
130
|
+
const domains = new Set([...node.domain, ...(input.domain ?? [])]);
|
|
115
131
|
this.db.raw
|
|
116
|
-
.prepare('UPDATE concepts SET frequency = frequency + 1, memory_ids = ?, description = COALESCE(description, ?), updated_at = ? WHERE id = ?')
|
|
117
|
-
.run(JSON.stringify([...memIds]), input.description ?? null, Date.now(), node.id);
|
|
132
|
+
.prepare('UPDATE concepts SET frequency = frequency + 1, memory_ids = ?, domain = ?, description = COALESCE(description, ?), updated_at = ? WHERE id = ?')
|
|
133
|
+
.run(JSON.stringify([...memIds]), JSON.stringify([...domains]), input.description ?? null, Date.now(), node.id);
|
|
118
134
|
return { action: 'merged', id: node.id, reason: 'ok' };
|
|
119
135
|
}
|
|
120
136
|
// embedding 近邻
|
|
@@ -122,17 +138,14 @@ export class SqliteConceptGraph {
|
|
|
122
138
|
const vec = await this.embedding.embed(input.name);
|
|
123
139
|
const near = await this.findSimilarConcept(vec);
|
|
124
140
|
if (near) {
|
|
141
|
+
// 跨名一律退候选、不自动合并(拍板 2026-11-19):自动合并会静默吞名、无审计、支撑虚高
|
|
125
142
|
const conflict = this.fingerprintConflict(near.node, input);
|
|
143
|
+
const id = this.insertConcept(input, vec);
|
|
144
|
+
const fingerprintDiff = conflict ? [conflict] : [];
|
|
126
145
|
if (!conflict && near.distance <= this.mergeThreshold) {
|
|
127
|
-
|
|
128
|
-
this.db.raw
|
|
129
|
-
.prepare('UPDATE concepts SET frequency = frequency + 1, memory_ids = ?, updated_at = ? WHERE id = ?')
|
|
130
|
-
.run(JSON.stringify([...memIds]), Date.now(), near.node.id);
|
|
131
|
-
return { action: 'merged', id: near.node.id, reason: 'ok' };
|
|
146
|
+
fingerprintDiff.push('strong_near');
|
|
132
147
|
}
|
|
133
|
-
|
|
134
|
-
const id = this.insertConcept(input, vec);
|
|
135
|
-
const candidateId = this.insertMergeCandidate(near.node.id, id, conflict ?? 'embedding_band', near.distance, conflict ? [conflict] : []);
|
|
148
|
+
const candidateId = this.insertMergeCandidate(near.node.id, id, conflict ?? 'embedding_band', near.distance, fingerprintDiff);
|
|
136
149
|
return {
|
|
137
150
|
action: 'merge_candidate',
|
|
138
151
|
id,
|
|
@@ -154,19 +167,10 @@ export class SqliteConceptGraph {
|
|
|
154
167
|
}
|
|
155
168
|
return { action: 'created', id, reason: 'ok' };
|
|
156
169
|
}
|
|
170
|
+
/** 义项指纹冲突:仅 kind 不同。domain 是多值标签不参与义项判定(同名同 kind 合并且 domain 取并集) */
|
|
157
171
|
fingerprintConflict(existing, input) {
|
|
158
|
-
if (existing.kind !== input.kind && existing.kind !== 'construct' && input.kind !== 'construct') {
|
|
159
|
-
return `kind:${existing.kind}≠${input.kind}`;
|
|
160
|
-
}
|
|
161
172
|
if (existing.kind !== input.kind)
|
|
162
173
|
return `kind:${existing.kind}≠${input.kind}`;
|
|
163
|
-
const a = new Set(existing.domain);
|
|
164
|
-
const b = new Set(input.domain ?? []);
|
|
165
|
-
if (a.size > 0 && b.size > 0) {
|
|
166
|
-
const overlap = [...b].some((d) => a.has(d));
|
|
167
|
-
if (!overlap)
|
|
168
|
-
return 'domain_disjoint';
|
|
169
|
-
}
|
|
170
174
|
return null;
|
|
171
175
|
}
|
|
172
176
|
insertConcept(input, vec) {
|
|
@@ -175,7 +179,7 @@ export class SqliteConceptGraph {
|
|
|
175
179
|
this.db.raw
|
|
176
180
|
.prepare(`INSERT INTO concepts (id, name, kind, description, frequency, memory_ids, domain, status, embedding, created_at, updated_at)
|
|
177
181
|
VALUES (?, ?, ?, ?, 1, ?, ?, 'shadow', ?, ?, ?)`)
|
|
178
|
-
.run(id, input.name.trim(), input.kind, input.description ?? null, JSON.stringify(input.memoryIds ?? []), JSON.stringify(input.domain ?? []), vec ? serializeEmbedding(vec) : null, now, now);
|
|
182
|
+
.run(id, input.name.trim(), input.kind, input.description ?? null, JSON.stringify([...new Set(input.memoryIds ?? [])]), JSON.stringify([...new Set(input.domain ?? [])]), vec ? serializeEmbedding(vec) : null, now, now);
|
|
179
183
|
return id;
|
|
180
184
|
}
|
|
181
185
|
insertMergeCandidate(leftId, rightId, reason, distance, fingerprintDiff) {
|
|
@@ -194,8 +198,8 @@ export class SqliteConceptGraph {
|
|
|
194
198
|
let best = null;
|
|
195
199
|
for (const row of rows) {
|
|
196
200
|
const vec = parseEmbedding(row.embedding);
|
|
197
|
-
if (!vec)
|
|
198
|
-
continue;
|
|
201
|
+
if (!vec || vec.length !== embedding.length)
|
|
202
|
+
continue; // 维度失配行跳过(与 semanticSeeds 同守卫)
|
|
199
203
|
const distance = cosineDistance(embedding, vec);
|
|
200
204
|
if (!best || distance < best.distance) {
|
|
201
205
|
best = { node: this.rowToNode(row), distance };
|
|
@@ -318,7 +322,7 @@ export class SqliteConceptGraph {
|
|
|
318
322
|
}
|
|
319
323
|
async listMergeCandidates(limit = 50) {
|
|
320
324
|
const rows = this.db.raw
|
|
321
|
-
.prepare(`SELECT * FROM concept_merge_candidates WHERE status = 'open' ORDER BY created_at
|
|
325
|
+
.prepare(`SELECT * FROM concept_merge_candidates WHERE status = 'open' ORDER BY created_at ASC LIMIT ?`)
|
|
322
326
|
.all(limit);
|
|
323
327
|
return rows.map((r) => ({
|
|
324
328
|
id: r.id,
|
|
@@ -333,7 +337,55 @@ export class SqliteConceptGraph {
|
|
|
333
337
|
resolvedAction: r.resolved_action ?? undefined,
|
|
334
338
|
}));
|
|
335
339
|
}
|
|
336
|
-
|
|
340
|
+
/** 语义种子能力:已注 embeddingProvider 才可做查询近邻 */
|
|
341
|
+
get supportsSemanticSeeds() {
|
|
342
|
+
return this.embedding != null;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* 查询语义种子:查询文本经自有 provider 嵌入后,对已存向量做近邻扫描。
|
|
346
|
+
* 距离带用 `semanticSeedMaxDistance`(相关性域,默认 0.65)——与 merge 的同一性带
|
|
347
|
+
* (candidateBandHi 0.35)不同域:真模型下「查询句→短概念名」相关对实测 0.41–0.59。
|
|
348
|
+
*
|
|
349
|
+
* @param query - 查询文本
|
|
350
|
+
* @param k - 种子上限(缺省 4)
|
|
351
|
+
* @returns 概念名列表(近者优先);provider 缺失/嵌入失败/无近邻/维度失配行 → 空/跳过(增强路径不 fail)
|
|
352
|
+
*/
|
|
353
|
+
async semanticSeeds(query, k = 4) {
|
|
354
|
+
if (!this.embedding || !query.trim())
|
|
355
|
+
return [];
|
|
356
|
+
const limit = Math.max(1, Math.floor(k));
|
|
357
|
+
let vec;
|
|
358
|
+
try {
|
|
359
|
+
vec = await withTimeout(this.embedding.embed(query), this.semanticSeedEmbedTimeoutMs);
|
|
360
|
+
}
|
|
361
|
+
catch {
|
|
362
|
+
// 增强路径:嵌入失败/超时降级空种子(词面召回照常),不向上抛
|
|
363
|
+
return [];
|
|
364
|
+
}
|
|
365
|
+
const rows = this.db.raw
|
|
366
|
+
.prepare('SELECT id, name, embedding, updated_at FROM concepts WHERE embedding IS NOT NULL')
|
|
367
|
+
.all();
|
|
368
|
+
const scored = [];
|
|
369
|
+
const freshCache = new Map();
|
|
370
|
+
for (const r of rows) {
|
|
371
|
+
const stamp = `${r.updated_at}`;
|
|
372
|
+
let entry = this.parsedVectorCache.get(r.id);
|
|
373
|
+
if (!entry || entry.stamp !== stamp) {
|
|
374
|
+
const parsed = r.embedding ? parseEmbedding(r.embedding) : null;
|
|
375
|
+
entry = parsed ? { stamp, vec: parsed } : null;
|
|
376
|
+
}
|
|
377
|
+
freshCache.set(r.id, entry);
|
|
378
|
+
if (!entry || entry.vec.length !== vec.length)
|
|
379
|
+
continue; // 维度失配行跳过(provider 换代遗留向量)
|
|
380
|
+
const distance = cosineDistance(vec, entry.vec);
|
|
381
|
+
if (distance <= this.semanticSeedMaxDistance)
|
|
382
|
+
scored.push({ name: r.name, distance });
|
|
383
|
+
}
|
|
384
|
+
this.parsedVectorCache = freshCache; // 顺带清掉已删行的缓存
|
|
385
|
+
scored.sort((a, b) => a.distance - b.distance);
|
|
386
|
+
return scored.slice(0, limit).map((s) => s.name);
|
|
387
|
+
}
|
|
388
|
+
async resolveMerge(id, action, options) {
|
|
337
389
|
const row = this.db.raw
|
|
338
390
|
.prepare('SELECT * FROM concept_merge_candidates WHERE id = ?')
|
|
339
391
|
.get(id);
|
|
@@ -351,7 +403,7 @@ export class SqliteConceptGraph {
|
|
|
351
403
|
if (!right && row.right_id.startsWith('pending:')) {
|
|
352
404
|
const pendingName = row.right_id.slice('pending:'.length).toLowerCase();
|
|
353
405
|
const candidates = this.db.raw
|
|
354
|
-
.prepare('SELECT * FROM concepts WHERE LOWER(name) = ?')
|
|
406
|
+
.prepare('SELECT * FROM concepts WHERE LOWER(name) = ? ORDER BY created_at ASC, id ASC')
|
|
355
407
|
.all(pendingName);
|
|
356
408
|
// 同名多义项:取非 left 的第一个
|
|
357
409
|
right = candidates.find((c) => c.id !== row.left_id);
|
|
@@ -369,7 +421,14 @@ export class SqliteConceptGraph {
|
|
|
369
421
|
...safeJsonArray(left.memory_ids),
|
|
370
422
|
...safeJsonArray(right.memory_ids),
|
|
371
423
|
]);
|
|
372
|
-
|
|
424
|
+
const domains = new Set([
|
|
425
|
+
...safeJsonArray(left.domain),
|
|
426
|
+
...safeJsonArray(right.domain),
|
|
427
|
+
]);
|
|
428
|
+
db.prepare('UPDATE concepts SET frequency = frequency + ?, memory_ids = ?, domain = ?, description = COALESCE(description, ?), updated_at = ? WHERE id = ?').run(right.frequency, JSON.stringify([...memIds]), JSON.stringify([...domains]), right.description ?? null, Date.now(), left.id);
|
|
429
|
+
if (options?.canonicalKind && left.kind !== options.canonicalKind) {
|
|
430
|
+
db.prepare('UPDATE concepts SET kind = ?, updated_at = ? WHERE id = ?').run(options.canonicalKind, Date.now(), left.id);
|
|
431
|
+
}
|
|
373
432
|
// 迁边前:丢掉会变自环的边
|
|
374
433
|
db.prepare('DELETE FROM concept_edges WHERE (source_id = ? AND target_id = ?) OR (source_id = ? AND target_id = ?)')
|
|
375
434
|
.run(left.id, right.id, right.id, left.id);
|
|
@@ -500,17 +559,16 @@ export class SqliteConceptGraph {
|
|
|
500
559
|
return empty;
|
|
501
560
|
const statusPlace = statuses.map(() => '?').join(',');
|
|
502
561
|
const statusSet = new Set(statuses);
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
}
|
|
513
|
-
const seedIds = [...seedMap.keys()];
|
|
562
|
+
// 反向匹配(token 含 name)无法下推 SQL:轻列扫描 + 共享谓词(cognition-seeds 单源)
|
|
563
|
+
const candidateRows = this.db.raw
|
|
564
|
+
.prepare(`SELECT id, name, description FROM concepts WHERE status IN (${statusPlace})`)
|
|
565
|
+
.all(...statuses);
|
|
566
|
+
const seedMatcher = createSeedMatcher(seeds);
|
|
567
|
+
const seedIds = [];
|
|
568
|
+
for (const r of candidateRows) {
|
|
569
|
+
if (seedMatcher(r.name, r.description))
|
|
570
|
+
seedIds.push(r.id);
|
|
571
|
+
}
|
|
514
572
|
if (!seedIds.length)
|
|
515
573
|
return empty;
|
|
516
574
|
const activation = new Map();
|