@jjh32456/longlive 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* inject-order.mjs — pre-step 注入顺序 / 去重 / 路径级排除的**纯函数**。
|
|
3
|
+
*
|
|
4
|
+
* 这里只处理普通对象(消息数组、卡数组),不碰 ctx、不碰 fs,方便单测。
|
|
5
|
+
*
|
|
6
|
+
* 真实 Cordis 合成语义(cordis/src/events.ts:234-242):
|
|
7
|
+
* `prepend:true` 的监听器被 unshift 到最外层、最先执行;`prepend:false` 走 push,
|
|
8
|
+
* 在内层执行。开机卡由 identity-router 在最外层、`next()` **之前**插进
|
|
9
|
+
* `payload.messages`,所以内层的 auto-recall 一定看得到它。最终顺序(v4):
|
|
10
|
+
*
|
|
11
|
+
* [user, boot, runtime, auto]
|
|
12
|
+
*
|
|
13
|
+
* 开机卡插在**第一条真实 user 消息之后**,不再 unshift 到最前:宿主 TurnNavigator
|
|
14
|
+
* 取该轮第一个可见 `kind:'user'` 节点做 tooltip 的 prompt(client.js:8373-8384),
|
|
15
|
+
* boot 在最前会让第 1 轮显示【开机卡】而不是用户提问(复核第三轮 mustFix #2)。
|
|
16
|
+
*
|
|
17
|
+
* auto 只负责把自己 append 到最后;不再把消息插到 boot 后面(那会得到
|
|
18
|
+
* `[boot, auto, user, runtime]`,复核 S2 的顺序问题)。
|
|
19
|
+
*
|
|
20
|
+
* v4 / 复核第四轮 M1(2026-11-04):注入消息的 source.kind 从 'user' 改为
|
|
21
|
+
* 'session-reference',形状固定为
|
|
22
|
+
*
|
|
23
|
+
* { kind:'session-reference', form:'recall', version:1, references:[] }
|
|
24
|
+
*
|
|
25
|
+
* 宿主渲染层把 `kind !== 'user'` 的 user/message 投影成 **context 节点**
|
|
26
|
+
* (client.js:9887-9893),`isVisibleChatNode()` 对普通 context 返回 false
|
|
27
|
+
* (client.js:8226-8228)——所以【开机卡】/【自动想起】不再变成聊天里的用户气泡。
|
|
28
|
+
* 模型侧不受影响:`session.deriveMessages()` 仍包含正文;`references: []` 让
|
|
29
|
+
* `recalledSessions()` 返回 null,RecallBody 退化成 opaque 行,不会抛
|
|
30
|
+
* `unreachable context form`。
|
|
31
|
+
*
|
|
32
|
+
* 代价(已与用户确认,不阻塞本次):用户看不到「想起了什么」。可见性改由
|
|
33
|
+
* **潜望镜面板**承担(后续加页签,见 README「可见性」/ WIRING §3);在面板上线前,
|
|
34
|
+
* 注入只服务模型,不在聊天流里露脸。
|
|
35
|
+
*
|
|
36
|
+
* 识别契约:
|
|
37
|
+
* - 本插件 / identity-router 的注入靠 kind 直接识别(不再依赖正文标记);
|
|
38
|
+
* - 正文标记(【自动想起】/【开机卡】)继续保留,用于识别历史消息与外部记忆注入
|
|
39
|
+
* 风格的注入,also keeps firstUserText from eating a legacy card;
|
|
40
|
+
* - **外部插件**仍可能用 kind:'user' 把文本插到真实提问前(复核 ADV1)。识别不了
|
|
41
|
+
* 任意纯文本,所以 firstUserText 的取值在 index.js 里按「第 1 轮最后一条真人
|
|
42
|
+
* 消息」锁定,isRealUserMessage 只负责排掉已知注入形态。
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 宿主 MessageSourceMap 的完整成员(dsh-llm/lib/typert.host.js:475-477)。
|
|
47
|
+
* 注入只允许白名单内的 kind;坏 kind 会在 append 时被本插件拒绝,避免日志被
|
|
48
|
+
* 毒化(append 接受任意非空字符串,但 adoptSessionEvent 会抛 invalid source)。
|
|
49
|
+
*/
|
|
50
|
+
import { isExternalMemoryKind } from '../adapters/constants.js';
|
|
51
|
+
|
|
52
|
+
export const HOST_SOURCE_KINDS = Object.freeze([
|
|
53
|
+
'user', 'model', 'tool', 'system-prompt', 'model-selection', 'runtime-context',
|
|
54
|
+
'working-directory', 'user-approval', 'ptc-mode', 'tool-registry', 'user-rpc',
|
|
55
|
+
'agent-message', 'subagent-settled', 'skill-invocation', 'compact-checkpoint',
|
|
56
|
+
'cordis-host-runner', 'team-message', 'user-question-reply', 'goal', 'plan-mode',
|
|
57
|
+
'schedule', 'session-reference', 'webhook',
|
|
58
|
+
]);
|
|
59
|
+
|
|
60
|
+
/** 宿主的隐藏注入 kind:不渲染气泡、但正文仍进模型上下文。 */
|
|
61
|
+
export const HOST_USER_SOURCE_KIND = 'session-reference';
|
|
62
|
+
|
|
63
|
+
/** 真实的用户消息 kind(session-reference 不是)。 */
|
|
64
|
+
export const REAL_USER_SOURCE_KIND = 'user';
|
|
65
|
+
|
|
66
|
+
/** session-reference 的 recall 形状(见 dsh-llm 的 SessionReferenceSource)。 */
|
|
67
|
+
export const INJECTION_SOURCE_FORM = 'recall';
|
|
68
|
+
export const INJECTION_SOURCE_VERSION = 1;
|
|
69
|
+
|
|
70
|
+
/** 旧版越界 kind:只用于识别历史消息,不再写入。 */
|
|
71
|
+
export const AUTO_LEGACY_SOURCE_KIND = 'plugin:dsh-auto-recall';
|
|
72
|
+
export const IDENTITY_LEGACY_SOURCE_KIND = 'plugin:dsh-identity-router';
|
|
73
|
+
|
|
74
|
+
/** 旧版 source.sections 名(同样只用于识别)。 */
|
|
75
|
+
export const AUTO_SECTION = 'auto-recall.cards';
|
|
76
|
+
export const IDENTITY_SECTION = 'identity-router.open-card';
|
|
77
|
+
|
|
78
|
+
/** 正文首行标记:保留用于识别历史消息与外部注入。 */
|
|
79
|
+
// 2.0.0 hardgate 起头带 recallId(`【自动想起 · recallId=…】`),零命中块同头;
|
|
80
|
+
// 因此只认前缀,不再要求恰好以 `】` 结尾。
|
|
81
|
+
export const AUTO_TEXT_MARK = '【自动想起';
|
|
82
|
+
export const IDENTITY_TEXT_MARK = '【开机卡】';
|
|
83
|
+
/**
|
|
84
|
+
* 1.8.8 M2:归档兜底块的标记。它是 auto-recall 的第三种正文形态
|
|
85
|
+
* (常规召回/链路命中之外的归档兜底),必须与 AUTO_TEXT_MARK 一样被
|
|
86
|
+
* isAutoMessage / injectedTexts / mergeInjectionOrder 识别,否则:
|
|
87
|
+
* ① 旧归档块不会被 mergeInjectionOrder 幂等替换;
|
|
88
|
+
* ② 归档块会被 isRealUserMessage 当真人消息,污染 firstUserText。
|
|
89
|
+
*/
|
|
90
|
+
export const ARCHIVE_TEXT_MARK = '【自动想起·归档】';
|
|
91
|
+
|
|
92
|
+
/** 只在文本里认这两类路径;其它目录不参与(防止把任意 .md 当卡)。 */
|
|
93
|
+
const CARD_PATH_RE = /(?:^|[\s"'`(()【\[,,;;/])((?:topics|handover)\/[^\s"'`))】\],,;;]+\.md)/g;
|
|
94
|
+
|
|
95
|
+
export function isHostSourceKind(kind) {
|
|
96
|
+
return typeof kind === 'string' && HOST_SOURCE_KINDS.includes(kind);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 构造一条注入消息的 source(每次返回新对象,避免引用共享)。 */
|
|
100
|
+
export function injectionSource() {
|
|
101
|
+
return {
|
|
102
|
+
kind: HOST_USER_SOURCE_KIND,
|
|
103
|
+
form: INJECTION_SOURCE_FORM,
|
|
104
|
+
version: INJECTION_SOURCE_VERSION,
|
|
105
|
+
references: [],
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function badSource(code, message) {
|
|
110
|
+
const error = new Error(message);
|
|
111
|
+
error.code = code;
|
|
112
|
+
return error;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* append 前的守卫:坏 kind / 坏形状直接拒绝,不让它写进 session 日志。
|
|
117
|
+
* 只校验本插件自己的消息;外部插件写的消息由宿主负责,我们只能在 firstUserText
|
|
118
|
+
* 层面降低影响(ADV1)。
|
|
119
|
+
* @param {object} message
|
|
120
|
+
* @returns {object} 原消息
|
|
121
|
+
*/
|
|
122
|
+
export function assertInjectionMessage(message) {
|
|
123
|
+
const kind = sourceKindOf(message);
|
|
124
|
+
if (!isHostSourceKind(kind)) {
|
|
125
|
+
throw badSource('E_BAD_SOURCE_KIND', `injection source.kind ${JSON.stringify(kind)} 不在宿主封闭 union(${HOST_SOURCE_KINDS.length} 个合法值)`);
|
|
126
|
+
}
|
|
127
|
+
if (kind !== HOST_USER_SOURCE_KIND) {
|
|
128
|
+
throw badSource('E_UNEXPECTED_INJECTION_KIND', `插件注入必须用 ${HOST_USER_SOURCE_KIND},得到 ${JSON.stringify(kind)}`);
|
|
129
|
+
}
|
|
130
|
+
const source = message?.source ?? {};
|
|
131
|
+
if (source.form !== INJECTION_SOURCE_FORM
|
|
132
|
+
|| source.version !== INJECTION_SOURCE_VERSION
|
|
133
|
+
|| !Array.isArray(source.references)) {
|
|
134
|
+
throw badSource('E_BAD_SOURCE_SHAPE', 'session-reference 注入需要 { form:"recall", version:1, references:[] }');
|
|
135
|
+
}
|
|
136
|
+
return message;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function sourceKindOf(message) {
|
|
140
|
+
return String(message?.source?.kind ?? '');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function startsWithMark(message, mark) {
|
|
144
|
+
return textsOf(message).some((text) => String(text).trimStart().startsWith(mark));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function isIdentityMessage(message) {
|
|
148
|
+
const kind = sourceKindOf(message);
|
|
149
|
+
if (kind === IDENTITY_LEGACY_SOURCE_KIND || kind.startsWith(`${IDENTITY_LEGACY_SOURCE_KIND}:`)) return true;
|
|
150
|
+
return startsWithMark(message, IDENTITY_TEXT_MARK);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function isAutoMessage(message) {
|
|
154
|
+
const kind = sourceKindOf(message);
|
|
155
|
+
if (kind === AUTO_LEGACY_SOURCE_KIND) {
|
|
156
|
+
const sections = message?.source?.sections;
|
|
157
|
+
if (!Array.isArray(sections) || sections.length === 0) return true;
|
|
158
|
+
return sections.some((s) => s?.name === AUTO_SECTION);
|
|
159
|
+
}
|
|
160
|
+
return startsWithMark(message, AUTO_TEXT_MARK) || startsWithMark(message, ARCHIVE_TEXT_MARK);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 真正的用户消息:role==='user'、source.kind 缺省或为宿主真实的 'user',
|
|
165
|
+
* 且不是本插件 / identity-router / 已知外部注入形态。
|
|
166
|
+
*
|
|
167
|
+
* v4 起注入用 kind:'session-reference',kind 本身就能挡掉;这里再按正文特征
|
|
168
|
+
* 排一层(复核 ADV1):带 `source.form` / `source.sections` 的、首行是已知标记的,
|
|
169
|
+
* 都不算真人消息。无法凭正文区分「任意外部插件写的纯文本 kind:user」——那类消息
|
|
170
|
+
* 由 firstUserText 的「第 1 轮最后一条」规则处理(见 index.js)。
|
|
171
|
+
* @param {object} message
|
|
172
|
+
* @returns {boolean}
|
|
173
|
+
*/
|
|
174
|
+
export function isRealUserMessage(message) {
|
|
175
|
+
if (message?.role !== 'user') return false;
|
|
176
|
+
const kind = sourceKindOf(message);
|
|
177
|
+
if (kind !== '' && kind !== REAL_USER_SOURCE_KIND) return false; // session-reference / runtime-context 等
|
|
178
|
+
const source = message?.source ?? {};
|
|
179
|
+
if (source.form !== undefined || Array.isArray(source.sections)) return false;
|
|
180
|
+
return !isIdentityMessage(message) && !isAutoMessage(message);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** 一条消息里所有可读文本(content blocks + source.sections),去重后返回。 */
|
|
184
|
+
export function textsOf(message) {
|
|
185
|
+
const out = [];
|
|
186
|
+
for (const block of Array.isArray(message?.content) ? message.content : []) {
|
|
187
|
+
if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim() !== '') out.push(block.text);
|
|
188
|
+
}
|
|
189
|
+
for (const section of Array.isArray(message?.source?.sections) ? message.source.sections : []) {
|
|
190
|
+
if (typeof section?.text === 'string' && section.text.trim() !== '') out.push(section.text);
|
|
191
|
+
}
|
|
192
|
+
return [...new Set(out)];
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 本轮已经注入的文本:identity 开机卡 + 旧 plugin:* / 外部记忆注入消息。
|
|
197
|
+
* 给 chooseRecall 做文本级去重;kind 合法化成 session-reference 后不能只靠 kind 判断。
|
|
198
|
+
*/
|
|
199
|
+
export function injectedTexts(messages) {
|
|
200
|
+
const out = [];
|
|
201
|
+
for (const message of Array.isArray(messages) ? messages : []) {
|
|
202
|
+
if (isIdentityMessage(message) || isAutoMessage(message)) {
|
|
203
|
+
out.push(...textsOf(message));
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
const kind = sourceKindOf(message);
|
|
207
|
+
if (!kind.startsWith('plugin:') && !isExternalMemoryKind(kind)) continue;
|
|
208
|
+
out.push(...textsOf(message));
|
|
209
|
+
}
|
|
210
|
+
return out;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** message.source 里显式声明的卡路径(约定字段;当前 identity-router 还不发)。 */
|
|
214
|
+
function declaredPaths(message) {
|
|
215
|
+
const source = message?.source;
|
|
216
|
+
const out = [];
|
|
217
|
+
if (Array.isArray(source?.cardPaths)) out.push(...source.cardPaths);
|
|
218
|
+
for (const section of Array.isArray(source?.sections) ? source.sections : []) {
|
|
219
|
+
if (Array.isArray(section?.cardPaths)) out.push(...section.cardPaths);
|
|
220
|
+
if (typeof section?.path === 'string') out.push(section.path);
|
|
221
|
+
}
|
|
222
|
+
return out.filter((p) => typeof p === 'string' && p.trim() !== '');
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function normalizePath(p) {
|
|
226
|
+
return String(p ?? '').trim().replace(/\\/g, '/').replace(/^\.\//, '');
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* 一条消息里能识别出的卡路径。
|
|
231
|
+
* @param {object} message
|
|
232
|
+
* @param {{cards?:object[], titleMinChars?:number}} [opts]
|
|
233
|
+
*/
|
|
234
|
+
export function cardPathsInMessage(message, { cards = [], titleMinChars = 6 } = {}) {
|
|
235
|
+
const paths = new Set(declaredPaths(message).map(normalizePath));
|
|
236
|
+
const texts = textsOf(message);
|
|
237
|
+
for (const raw of texts) {
|
|
238
|
+
const text = raw.replace(/\\/g, '/');
|
|
239
|
+
CARD_PATH_RE.lastIndex = 0;
|
|
240
|
+
let m = CARD_PATH_RE.exec(text);
|
|
241
|
+
while (m !== null) {
|
|
242
|
+
paths.add(normalizePath(m[1]));
|
|
243
|
+
if (CARD_PATH_RE.lastIndex === m.index) CARD_PATH_RE.lastIndex += 1;
|
|
244
|
+
m = CARD_PATH_RE.exec(text);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
// identity-router 只注入 cardText(不含路径);对**交接卡**再退一步按标题认。
|
|
248
|
+
const joined = texts.join('\n');
|
|
249
|
+
for (const card of cards) {
|
|
250
|
+
if (!card || card.dir !== 'handover') continue;
|
|
251
|
+
const title = String(card.title ?? '').trim();
|
|
252
|
+
if (title.length >= titleMinChars && joined.includes(title)) paths.add(normalizePath(card.path));
|
|
253
|
+
}
|
|
254
|
+
return [...paths];
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** identity-router 已注入的卡路径(并入 chooseRecall 的 seenPaths)。 */
|
|
258
|
+
export function identityInjectedPaths(messages, opts = {}) {
|
|
259
|
+
const out = new Set();
|
|
260
|
+
for (const message of Array.isArray(messages) ? messages : []) {
|
|
261
|
+
if (!isIdentityMessage(message)) continue;
|
|
262
|
+
for (const p of cardPathsInMessage(message, opts)) out.add(p);
|
|
263
|
+
}
|
|
264
|
+
return [...out];
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* 把 auto-recall 的注入消息合并进 decision.messages:
|
|
269
|
+
* - 先移除本插件旧的消息(幂等:重复 merge 只剩一条);
|
|
270
|
+
* - 总是 append 到末尾:identity-router 已把开机卡插在第一条真实 user 之后,
|
|
271
|
+
* auto 的目标位置就是 `[user, boot, runtime, auto]` 的最后一位;
|
|
272
|
+
* - 不再「插到 identity 后面」——那会得到 `[boot, auto, user, runtime]`。
|
|
273
|
+
* @param {object[]} messages
|
|
274
|
+
* @param {object} message auto-recall 的消息
|
|
275
|
+
*/
|
|
276
|
+
export function mergeInjectionOrder(messages, message) {
|
|
277
|
+
const list = (Array.isArray(messages) ? messages : []).filter((m) => !isAutoMessage(m));
|
|
278
|
+
return [...list, message];
|
|
279
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 1.8.8 M2 链路直连:把 links.mjs 的「词 → 卡」命中变成可注入的候选条目。
|
|
3
|
+
*
|
|
4
|
+
* 分工:
|
|
5
|
+
* - links.mjs 只管数据(存储/匹配/学习/原子写);
|
|
6
|
+
* - 本模块只管「候选 → 注入条目」:查卡、隐私整卡丢弃、去重、预算、摘要;
|
|
7
|
+
* - 最终文本仍由 recall-core 的 renderInjection 渲染(不另造一套注入格式)。
|
|
8
|
+
*
|
|
9
|
+
* 隐私口径与既有召回完全一致(规格 §2.4):
|
|
10
|
+
* - 卡 frontmatter `local_only` → 整卡丢弃;
|
|
11
|
+
* - title/path/excerpt 任一命中隐私扫描 → 默认整卡丢弃;privacyPolicy:'title'
|
|
12
|
+
* 时把 excerpt 换成 [已隐藏](与 chooseRecall 的既有语义一致)。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { estimateTokens, pickExcerpt, renderInjection, sanitizeDataText } from './recall-core.mjs';
|
|
16
|
+
import { defaultPrivacyScan } from './recall-core.mjs';
|
|
17
|
+
import { linkCardsForText, LINKS_DEFAULTS, normalizeCardPath, normalizeLinksConfig } from './links.mjs';
|
|
18
|
+
|
|
19
|
+
export const LINK_SOURCE = 'link';
|
|
20
|
+
export const LINK_REASON_TEXT = 'link';
|
|
21
|
+
const PRIVACY_HIDDEN_MARK = '[已隐藏]';
|
|
22
|
+
const PRIVACY_HIDDEN_PATH = '<hidden>';
|
|
23
|
+
const DEDUPE_CONTAINMENT = 0.6;
|
|
24
|
+
|
|
25
|
+
function round3(n) {
|
|
26
|
+
return Math.round(Number(n) * 1000) / 1000;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 链路权重(seed w 可到 13.63)→ 0..1 的相关度口径,便于与既有条目同栏显示。
|
|
31
|
+
* 单调变换 w/(1+w):w=1 → 0.5,w=13.63 → 0.932,排序不变。
|
|
32
|
+
*/
|
|
33
|
+
export function linkScore(weight) {
|
|
34
|
+
const w = Math.max(0, Number(weight) || 0);
|
|
35
|
+
return round3(w / (1 + w));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 扫描器返回什么形态都归一成 boolean;抛错按命中处理(fail-closed,与 recall-core 一致)。 */
|
|
39
|
+
function privacyBlocked(scan, text) {
|
|
40
|
+
try {
|
|
41
|
+
const result = scan(text);
|
|
42
|
+
if (!result) return false;
|
|
43
|
+
if (typeof result === 'string') return result === 'local_only';
|
|
44
|
+
return result.verdict === 'local_only' || result.blocked === true;
|
|
45
|
+
} catch {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function bigrams(text) {
|
|
51
|
+
const s = String(text ?? '').toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '');
|
|
52
|
+
const out = new Set();
|
|
53
|
+
const chars = Array.from(s);
|
|
54
|
+
for (let i = 0; i + 1 < chars.length; i += 1) out.add(chars[i] + chars[i + 1]);
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 与 recall-core 的 containment 同口径(候选摘要被已注入文本覆盖的比例)。 */
|
|
59
|
+
function containment(candidate, existing) {
|
|
60
|
+
const a = bigrams(candidate);
|
|
61
|
+
if (a.size === 0) return 0;
|
|
62
|
+
const b = bigrams(existing);
|
|
63
|
+
if (b.size === 0) return 0;
|
|
64
|
+
let inter = 0;
|
|
65
|
+
for (const g of a) if (b.has(g)) inter += 1;
|
|
66
|
+
return round3(inter / a.size);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function isSamePath(a, b) {
|
|
70
|
+
return normalizeCardPath(a, '') === normalizeCardPath(b, '');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 从链路命中生成注入条目。
|
|
75
|
+
* @param {object} args
|
|
76
|
+
* @param {string} args.queryText 本轮**真实用户消息**原文(不是 buildQueryText 的拼接串)
|
|
77
|
+
* @param {object} args.store loadLinks() 的返回值
|
|
78
|
+
* @param {object[]} args.cards loadCards() 的卡片
|
|
79
|
+
* @param {string[]} [args.seenPaths] 本轮已注入过的卡路径(路径级去重)
|
|
80
|
+
* @param {string[]} [args.injectedTexts] 本轮已注入文本(文本级去重)
|
|
81
|
+
* @param {object} [args.options]
|
|
82
|
+
* @returns {{items:object[], matchedTerms:string[], tokens:number, stats:object}}
|
|
83
|
+
*/
|
|
84
|
+
export function selectLinkItems({
|
|
85
|
+
queryText = '',
|
|
86
|
+
store = null,
|
|
87
|
+
cards = [],
|
|
88
|
+
seenPaths = [],
|
|
89
|
+
injectedTexts = [],
|
|
90
|
+
options = {},
|
|
91
|
+
} = {}) {
|
|
92
|
+
const cfg = normalizeLinksConfig(options.links ?? LINKS_DEFAULTS);
|
|
93
|
+
const privacyScan = typeof options.privacyScan === 'function' ? options.privacyScan : defaultPrivacyScan;
|
|
94
|
+
const privacyPolicy = options.privacyPolicy === 'title' ? 'title' : 'drop';
|
|
95
|
+
const maxItems = Math.max(1, Math.min(5, Number(options.maxItems) || cfg.maxCardsPerTurn));
|
|
96
|
+
const budgetTokens = Math.max(50, Math.min(2000, Number(options.budgetTokens) || 2000));
|
|
97
|
+
const maxExcerptTokens = Math.max(40, Math.min(240, Number(options.maxExcerptTokens) || cfg.maxExcerptTokens));
|
|
98
|
+
const stats = {
|
|
99
|
+
candidates: 0,
|
|
100
|
+
injected: 0,
|
|
101
|
+
terms: 0,
|
|
102
|
+
droppedByMissingCard: 0,
|
|
103
|
+
droppedBySeen: 0,
|
|
104
|
+
droppedByLocalOnly: 0,
|
|
105
|
+
droppedByPrivacy: 0,
|
|
106
|
+
droppedByDedupe: 0,
|
|
107
|
+
droppedByBudget: 0,
|
|
108
|
+
droppedByMaxItems: 0,
|
|
109
|
+
redactedByPrivacy: 0,
|
|
110
|
+
};
|
|
111
|
+
const empty = { items: [], matchedTerms: [], tokens: 0, stats };
|
|
112
|
+
if (!store || store.error || !Array.isArray(store.edges) || store.edges.length === 0) return empty;
|
|
113
|
+
if (String(queryText ?? '').trim() === '' || !Array.isArray(cards) || cards.length === 0) return empty;
|
|
114
|
+
|
|
115
|
+
const match = linkCardsForText(queryText, store.edges, cfg);
|
|
116
|
+
stats.terms = match.matchedTerms.length;
|
|
117
|
+
if (match.matchedTerms.length === 0) return { ...empty, matchedTerms: [] };
|
|
118
|
+
|
|
119
|
+
const cardIndex = new Map();
|
|
120
|
+
for (const card of cards) {
|
|
121
|
+
cardIndex.set(normalizeCardPath(card?.path, ''), card);
|
|
122
|
+
}
|
|
123
|
+
const seen = new Set((Array.isArray(seenPaths) ? seenPaths : []).map((p) => normalizeCardPath(p, '')));
|
|
124
|
+
const injectedList = Array.isArray(injectedTexts) ? injectedTexts : [];
|
|
125
|
+
const items = [];
|
|
126
|
+
let tokens = 0;
|
|
127
|
+
for (const candidate of match.cards) {
|
|
128
|
+
stats.candidates += 1;
|
|
129
|
+
const card = cardIndex.get(normalizeCardPath(candidate.cardPath, ''));
|
|
130
|
+
if (!card) { stats.droppedByMissingCard += 1; continue; }
|
|
131
|
+
if (seen.has(normalizeCardPath(card.path, ''))) { stats.droppedBySeen += 1; continue; }
|
|
132
|
+
if (card.localOnly === true) { stats.droppedByLocalOnly += 1; continue; }
|
|
133
|
+
if (items.length >= maxItems) { stats.droppedByMaxItems += 1; continue; }
|
|
134
|
+
|
|
135
|
+
const hits = candidate.terms.map((term) => ({ phrase: term, weight: 1.5 + Math.min(1, Array.from(term).length / 8) }));
|
|
136
|
+
let excerpt = pickExcerpt(card, hits, maxExcerptTokens);
|
|
137
|
+
let redacted = false;
|
|
138
|
+
// 2026-11-26 P1-1 修:标题/路径命中一律整卡丢弃(与 recall-core.mjs:594-595 对齐);
|
|
139
|
+
// privacyPolicy='title' 只作用于「摘要命中」——摘要命中时保留标题 + [已隐藏]。
|
|
140
|
+
if (privacyBlocked(privacyScan, card.title) || privacyBlocked(privacyScan, card.path)) {
|
|
141
|
+
stats.droppedByPrivacy += 1;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (privacyBlocked(privacyScan, excerpt)) {
|
|
145
|
+
if (privacyPolicy === 'title') {
|
|
146
|
+
excerpt = PRIVACY_HIDDEN_MARK;
|
|
147
|
+
redacted = true;
|
|
148
|
+
stats.redactedByPrivacy += 1;
|
|
149
|
+
} else {
|
|
150
|
+
stats.droppedByPrivacy += 1;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (!redacted && injectedList.length > 0) {
|
|
155
|
+
const duplicated = injectedList.some((text) => containment(excerpt, text) >= DEDUPE_CONTAINMENT);
|
|
156
|
+
if (duplicated) { stats.droppedByDedupe += 1; continue; }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const item = {
|
|
160
|
+
path: normalizeCardPath(card.path, ''),
|
|
161
|
+
title: String(card.title ?? card.path ?? ''),
|
|
162
|
+
score: linkScore(candidate.weight),
|
|
163
|
+
reason: LINK_REASON_TEXT,
|
|
164
|
+
source: LINK_SOURCE,
|
|
165
|
+
excerpt,
|
|
166
|
+
link: { weight: candidate.weight, terms: candidate.terms.slice(0, 6) },
|
|
167
|
+
...(redacted ? { privacyRedacted: true } : {}),
|
|
168
|
+
};
|
|
169
|
+
const nextTokens = estimateTokens(renderInjection({ items: [...items, item] }, { privacyScan }));
|
|
170
|
+
if (nextTokens > budgetTokens) { stats.droppedByBudget += 1; continue; }
|
|
171
|
+
items.push(item);
|
|
172
|
+
tokens = nextTokens;
|
|
173
|
+
}
|
|
174
|
+
stats.injected = items.length;
|
|
175
|
+
return { items, matchedTerms: match.matchedTerms, tokens, stats };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** 链路条目的标题行(link 场景下带上命中词,方便审计)。 */
|
|
179
|
+
export function renderLinkItemLine(item) {
|
|
180
|
+
const path = privacyBlocked(defaultPrivacyScan, item.path) ? PRIVACY_HIDDEN_PATH : sanitizeDataText(item.path, 200);
|
|
181
|
+
const terms = Array.isArray(item?.link?.terms) ? item.link.terms.join('/') : '';
|
|
182
|
+
return `- 《${sanitizeDataText(item.title, 160)}》(${path} · 相关度 ${Number(item.score).toFixed(2)}${terms ? ` · 命中 ${sanitizeDataText(terms, 80)}` : ''})`;
|
|
183
|
+
}
|