@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,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 1.8.8 M2 强制触发策略(纯函数,无 IO、无随机、无时钟)。
|
|
3
|
+
*
|
|
4
|
+
* 用户原话(1.8.8 需求):触发太钝、不够强制——「我说我要做什么,就直连老记忆」。
|
|
5
|
+
* 所以 M2 在 `agent/pre-step` 的第 1 步加一条**用户任务消息**的强制通道:
|
|
6
|
+
*
|
|
7
|
+
* step===1 且最后一条消息是真实 user 消息(isRealUserMessage)
|
|
8
|
+
* 且这条消息**不是纯应答** → 强制召回一次,不再看 everyNTurns、不被 quiet 挡。
|
|
9
|
+
*
|
|
10
|
+
* 纯应答的机械判据(规格 §2.2,可复算、不是语义猜测):
|
|
11
|
+
* 去掉空白/标点/emoji 后,长度 ≤ ACK_MAX_CHARS 且不含任何任务动词。
|
|
12
|
+
* 例:好 / 嗯 / ok / 继续 / 谢谢 / 收到 / 好的,继续。
|
|
13
|
+
* 「继续」被用户列为纯应答样例,所以它**不在**任务动词表里。
|
|
14
|
+
*
|
|
15
|
+
* 问句例外(1.8.11 R11 P1-4 修订,SPEC §3 验收 #4):
|
|
16
|
+
* 短问句(如「五问是哪五问?」)虽然 ≤ ACK_MAX_CHARS,但它是提问、不是应答,
|
|
17
|
+
* 必须进强制召回通道。机械判据(不看语义):
|
|
18
|
+
* 原文含问号(?/?)或含疑问词(哪/什么/怎么/为什么/吗/呢/是否/几)。
|
|
19
|
+
* 这条规则**先于长度判定**:命中即非纯应答,不看字数。
|
|
20
|
+
* 「好了吗」「收到??」这类也会被当问句,属于机械规则的既定取舍(宁可多插一次)。
|
|
21
|
+
*
|
|
22
|
+
* 边界(写进 docs/AUTO-RECALL.md,别当秘密):
|
|
23
|
+
* - 长度 ≤6 且没有任务动词、也没有问句信号的真实短任务(如「v39战役」)会被当纯应答跳过;
|
|
24
|
+
* 这是按规格的机械规则执行的既定取舍,宁可少插一次,也不在每句应答后灌上下文。
|
|
25
|
+
* - 任务动词表/疑问词表是固定常量,不从记忆/配置里学;改词表会改行为,属于版本变更。
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** 纯应答的最大「去空白/标点后」字符数(规格 §2.2)。 */
|
|
29
|
+
export const ACK_MAX_CHARS = 6;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 问号字符:原文里出现任意一个就按问句处理(不需要成对判断)。
|
|
33
|
+
* 用原文判断而不是 compactText,因为标点会被 compactText 去掉。
|
|
34
|
+
*/
|
|
35
|
+
export const QUESTION_MARKS = Object.freeze(['?', '?']);
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 疑问词:原文包含任意一个就按问句处理(机械规则,不做语法判断)。
|
|
39
|
+
* 覆盖 SPEC §3 验收 #4 的实际问句「五问是哪五问?」(命中「哪」)。
|
|
40
|
+
*/
|
|
41
|
+
export const QUESTION_WORDS = Object.freeze(['哪', '什么', '怎么', '为什么', '吗', '呢', '是否', '几']);
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 任务动词:出现任意一个就说明这条消息在派活/改方向,不是纯应答。
|
|
45
|
+
* 注意:`继续`、`好`、`行`、`可以`、`收到`、`谢谢`、`嗯`、`ok` 都不在这里
|
|
46
|
+
* (它们是用户明确列出的纯应答样例)。
|
|
47
|
+
*/
|
|
48
|
+
export const TASK_VERBS = Object.freeze([
|
|
49
|
+
// 动作类
|
|
50
|
+
'做', '搞', '弄', '办', '干', '改', '修', '写', '读', '看', '查', '找', '搜',
|
|
51
|
+
'跑', '测', '试', '装', '卸', '删', '加', '换', '发', '停', '开', '关', '搬',
|
|
52
|
+
// 交付类
|
|
53
|
+
'发布', '部署', '上线', '重启', '启动', '同步', '更新', '升级', '整理', '清理',
|
|
54
|
+
'推进', '继续做', '接着做', '帮我', '检查', '确认', '核对',
|
|
55
|
+
'对比', '分析', '实现', '补齐', '补', '迁移', '回滚', '恢复', '备份', '导出',
|
|
56
|
+
'导入', '生成', '识别', '扒', '编', '混', '配', '调', '渲染', '验收', '签字',
|
|
57
|
+
'审', '下载', '上传', '安装', '提交', '推送', '合并', '建', '拆', '编译', '打包',
|
|
58
|
+
'优化', '排查', '定位', '复现', '跑一遍', '来一份', '来一段', '来一个',
|
|
59
|
+
]);
|
|
60
|
+
|
|
61
|
+
/** 纯应答示例(给测试/文档对齐用;判定本身不依赖这个表)。 */
|
|
62
|
+
export const ACK_EXAMPLES = Object.freeze(['好', '嗯', 'ok', '继续', '谢谢', '收到', '好的', '行', '可以']);
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 只保留「真正的字」:去掉空白、标点、符号、emoji、markdown 记号。
|
|
66
|
+
* 与 recall-core 的 norm 不同:这里只用于长度/词表判定,不参与打分。
|
|
67
|
+
* @param {string} text
|
|
68
|
+
* @returns {string}
|
|
69
|
+
*/
|
|
70
|
+
export function compactText(text) {
|
|
71
|
+
return String(text ?? '').replace(/[\s\p{P}\p{S}\p{Extended_Pictographic}]+/gu, '');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 消息是否含任务动词(在**原文**里找;动词本身可能被标点隔开)。
|
|
76
|
+
* @param {string} text
|
|
77
|
+
* @returns {boolean}
|
|
78
|
+
*/
|
|
79
|
+
export function hasTaskVerb(text) {
|
|
80
|
+
const compact = compactText(text);
|
|
81
|
+
if (compact === '') return false;
|
|
82
|
+
return TASK_VERBS.some((verb) => compact.includes(verb));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 消息是否带问句信号(原文判断:问号或疑问词)。
|
|
87
|
+
* @param {string} text
|
|
88
|
+
* @returns {boolean}
|
|
89
|
+
*/
|
|
90
|
+
export function hasQuestionSignal(text) {
|
|
91
|
+
const raw = String(text ?? '');
|
|
92
|
+
if (raw === '') return false;
|
|
93
|
+
if (QUESTION_MARKS.some((mark) => raw.includes(mark))) return true;
|
|
94
|
+
return QUESTION_WORDS.some((word) => raw.includes(word));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* 纯应答判定:去空白/标点后长度 ≤ ACK_MAX_CHARS 且不含任务动词、且无问句信号。
|
|
99
|
+
* 空消息按纯应答处理(不触发强制召回)。
|
|
100
|
+
* 问句信号优先于长度(1.8.11 P1-4):短问句不是应答。
|
|
101
|
+
* @param {string} text
|
|
102
|
+
* @returns {boolean}
|
|
103
|
+
*/
|
|
104
|
+
export function isPureAcknowledgement(text) {
|
|
105
|
+
const raw = String(text ?? '');
|
|
106
|
+
const compact = compactText(raw);
|
|
107
|
+
if (compact === '') return true;
|
|
108
|
+
if (hasQuestionSignal(raw)) return false;
|
|
109
|
+
if (Array.from(compact).length > ACK_MAX_CHARS) return false;
|
|
110
|
+
return !hasTaskVerb(raw);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 这条真实用户消息是否应当触发「强制召回」。
|
|
115
|
+
* 只有真实用户消息才谈得上强制;空消息/纯应答返回 false。
|
|
116
|
+
* @param {string} text
|
|
117
|
+
* @returns {boolean}
|
|
118
|
+
*/
|
|
119
|
+
export function shouldForceRecallForMessage(text) {
|
|
120
|
+
const raw = String(text ?? '').trim();
|
|
121
|
+
if (raw === '') return false;
|
|
122
|
+
return !isPureAcknowledgement(raw);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 反馈词判定(在线学习用;也放这里,避免 learning 模块自己再定义一套口径)。
|
|
127
|
+
* 只判「上一轮注入之后他这句是在确认还是否认」,不做更多语义推断。
|
|
128
|
+
* 否认优先:一句里同时出现「不是这个…就对了」按否认算(宁可少加权重)。
|
|
129
|
+
* @param {string} text
|
|
130
|
+
* @returns {'confirm'|'deny'|null}
|
|
131
|
+
*/
|
|
132
|
+
export function classifyLinkFeedback(text) {
|
|
133
|
+
const s = String(text ?? '').trim();
|
|
134
|
+
if (s === '') return null;
|
|
135
|
+
if (/(不对|不是这个|不是它|不是我要|不是那张|错了|搞错|记错|弄错|不准确|没对上|不相关)/u.test(s)) return 'deny';
|
|
136
|
+
if (/(对的|对呀|对。|对,|对$|就是这个|就是它|没错|正是|准确|精准|靠谱|这个对|就是这张|对了)/u.test(s)) return 'confirm';
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// N04 · hardgate 链式日志(gate-log / land-log 同构)
|
|
2
|
+
//
|
|
3
|
+
// 契约(DESIGN v0.5.1 §6 A1 / §7 B):
|
|
4
|
+
// <memoryRoot>/.longlive/hardgate/gate-log.jsonl
|
|
5
|
+
// <memoryRoot>/.longlive/hardgate/gate-log-head.json
|
|
6
|
+
// 每行 {schema,at,sessionId,turn,gate,decision,reason,evidence[],sha,prevSha};
|
|
7
|
+
// sha = sha256(canonical({schema,at,sessionId,turn,gate,decision,reason,evidence}))
|
|
8
|
+
// prevSha = 前一行的 sha;首行 null。
|
|
9
|
+
// 2.0.0 B3:行内可选携带注入度量 {injectedChars,injectedTokens,elapsedMs};只在本行真的
|
|
10
|
+
// 有该字段时进入 sha 域(旧行逐字不变,链校验/回放保持兼容)。
|
|
11
|
+
// head 文件 = {rows, tailSha, updatedAt},每次 append 同锁更新。
|
|
12
|
+
//
|
|
13
|
+
// 任何写入失败都抛错(fail-closed):调用方要么让本轮硬门显式失败,要么把错误
|
|
14
|
+
// 记进 stderr/日志——禁止静默当成功。读取失败时调用方自己决定是否降级。
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import crypto from 'node:crypto';
|
|
19
|
+
|
|
20
|
+
export const HARDGATE_DIRNAME = 'hardgate';
|
|
21
|
+
export const GATE_LOG_SCHEMA = 'hardgate-gate-log/v1';
|
|
22
|
+
export const LAND_LOG_SCHEMA = 'land-gate/v1';
|
|
23
|
+
export const GATE_LOG_FILE = 'gate-log.jsonl';
|
|
24
|
+
export const GATE_LOG_HEAD_FILE = 'gate-log-head.json';
|
|
25
|
+
export const LAND_LOG_FILE = 'land-log.jsonl';
|
|
26
|
+
export const LAND_LOG_HEAD_FILE = 'land-log-head.json';
|
|
27
|
+
|
|
28
|
+
export const GATE_DECISIONS = Object.freeze(['ok', 'zero-hit', 'disabled', 'fail', 'warn', 'skip']);
|
|
29
|
+
|
|
30
|
+
// gate-reason 草案:B4「每次注入必带 reason code(无 reason fail-closed)」+ B3 C4(每行非空
|
|
31
|
+
// reason)。写器层兜底:调用方显式给非空 reason 就原样保留;没给/给空串时,按 decision 取
|
|
32
|
+
// 一个确定性的非空 reason,绝不落空串。不变量:写出的每一行 reason 都是非空字符串。
|
|
33
|
+
export const DEFAULT_GATE_LOG_REASON = Object.freeze({
|
|
34
|
+
ok: 'hit',
|
|
35
|
+
'zero-hit': 'zero-hit',
|
|
36
|
+
disabled: 'disabled',
|
|
37
|
+
fail: 'fail',
|
|
38
|
+
warn: 'warn',
|
|
39
|
+
skip: 'skip',
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
export function normalizeGateLogReason(input = {}) {
|
|
43
|
+
const explicit = [input.reason, input.reasonCode, input.reason_code].find(
|
|
44
|
+
(value) => typeof value === 'string' && value.trim() !== '',
|
|
45
|
+
);
|
|
46
|
+
if (explicit !== undefined) return explicit.trim();
|
|
47
|
+
const decision = typeof input.decision === 'string' && input.decision.trim() !== ''
|
|
48
|
+
? input.decision.trim()
|
|
49
|
+
: 'ok';
|
|
50
|
+
return DEFAULT_GATE_LOG_REASON[decision] ?? decision;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// B3 C4:可选的注入度量字段(与 src/recall/gate-metrics.mjs 的 GATE_METRIC_KEYS 同口径;
|
|
54
|
+
// 本地常量避免 gate-log → gate-metrics 的单向依赖被测试替身打断)。
|
|
55
|
+
const GATE_METRIC_KEYS = Object.freeze(['injectedChars', 'injectedTokens', 'elapsedMs']);
|
|
56
|
+
|
|
57
|
+
function hardgateDir(memoryRoot) {
|
|
58
|
+
if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
|
|
59
|
+
throw hardgateError('E_HG_GATELOG_NO_ROOT', 'gate-log 需要 memoryRoot');
|
|
60
|
+
}
|
|
61
|
+
return path.join(path.resolve(memoryRoot), '.longlive', HARDGATE_DIRNAME);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function hardgateError(code, message) {
|
|
65
|
+
const error = new Error(message);
|
|
66
|
+
error.code = code;
|
|
67
|
+
return error;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 与夹具 harness 完全一致的 canonical JSON:键名按码点升序,数组保序,无空白。 */
|
|
71
|
+
export function canonicalJson(value) {
|
|
72
|
+
if (value === undefined) return 'null';
|
|
73
|
+
if (value === null || typeof value !== 'object') {
|
|
74
|
+
if (typeof value === 'number' && !Number.isFinite(value)) return 'null';
|
|
75
|
+
return JSON.stringify(value);
|
|
76
|
+
}
|
|
77
|
+
if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(',')}]`;
|
|
78
|
+
const keys = Object.keys(value).sort();
|
|
79
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function sha256(value) {
|
|
83
|
+
return crypto.createHash('sha256').update(value, 'utf8').digest('hex');
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function gateLogPaths(memoryRoot) {
|
|
87
|
+
const dir = hardgateDir(memoryRoot);
|
|
88
|
+
return {
|
|
89
|
+
dir,
|
|
90
|
+
logFile: path.join(dir, GATE_LOG_FILE),
|
|
91
|
+
headFile: path.join(dir, GATE_LOG_HEAD_FILE),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function landLogPaths(memoryRoot) {
|
|
96
|
+
const dir = hardgateDir(memoryRoot);
|
|
97
|
+
return {
|
|
98
|
+
dir,
|
|
99
|
+
logFile: path.join(dir, LAND_LOG_FILE),
|
|
100
|
+
headFile: path.join(dir, LAND_LOG_HEAD_FILE),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function readHeadState(headFile) {
|
|
105
|
+
try {
|
|
106
|
+
const parsed = JSON.parse(fs.readFileSync(headFile, 'utf8'));
|
|
107
|
+
if (parsed && typeof parsed === 'object') {
|
|
108
|
+
return {
|
|
109
|
+
rows: Number.isFinite(parsed.rows) ? parsed.rows : 0,
|
|
110
|
+
tailSha: typeof parsed.tailSha === 'string' ? parsed.tailSha : null,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
} catch {
|
|
114
|
+
/* head 缺失/坏:靠日志末行重建 */
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function lastRowOf(logFile) {
|
|
120
|
+
try {
|
|
121
|
+
const text = fs.readFileSync(logFile, 'utf8');
|
|
122
|
+
const lines = text.split(/\r?\n/).filter((line) => line.trim() !== '');
|
|
123
|
+
if (lines.length === 0) return null;
|
|
124
|
+
return JSON.parse(lines[lines.length - 1]);
|
|
125
|
+
} catch {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function writeHead(headFile, rows, tailSha) {
|
|
131
|
+
const payload = JSON.stringify({
|
|
132
|
+
rows,
|
|
133
|
+
tailSha,
|
|
134
|
+
updatedAt: new Date().toISOString(),
|
|
135
|
+
});
|
|
136
|
+
const tmp = `${headFile}.tmp-${process.pid}-${Date.now()}`;
|
|
137
|
+
fs.writeFileSync(tmp, `${payload}\n`, 'utf8');
|
|
138
|
+
fs.renameSync(tmp, headFile);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* B3 C4:gate-log 行的注入度量。只接受有限数值;null/undefined/'' 视为「本行没有」,
|
|
143
|
+
* 不进 sha 域(旧行兼容:旧行没有这三个字段时域与 sha 一字不变)。
|
|
144
|
+
*/
|
|
145
|
+
function metricValue(value) {
|
|
146
|
+
if (value === null || value === undefined || value === '') return null;
|
|
147
|
+
const n = Number(value);
|
|
148
|
+
return Number.isFinite(n) ? n : null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** B3:三个可选度量字段的顺序固定,append 与 verify 用同一份域构造。 */
|
|
152
|
+
function metricDomainFields(input) {
|
|
153
|
+
const fields = {};
|
|
154
|
+
for (const key of GATE_METRIC_KEYS) {
|
|
155
|
+
const value = metricValue(input?.[key]);
|
|
156
|
+
if (value !== null) fields[key] = value;
|
|
157
|
+
}
|
|
158
|
+
return fields;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 往链式日志追加一行。返回写入的完整行(含 sha/prevSha)。
|
|
163
|
+
* 同进程内同步写;跨进程并发由调用方(capture-host)串行化。
|
|
164
|
+
*/
|
|
165
|
+
export function appendChainedRow(paths, schema, input = {}) {
|
|
166
|
+
const evidence = Array.isArray(input.evidence) ? input.evidence.map((item) => String(item)) : [];
|
|
167
|
+
const domain = {
|
|
168
|
+
schema,
|
|
169
|
+
at: typeof input.at === 'string' ? input.at : new Date().toISOString(),
|
|
170
|
+
sessionId: input.sessionId ?? null,
|
|
171
|
+
turn: Number.isFinite(input.turn) ? input.turn : null,
|
|
172
|
+
gate: input.gate ?? 'recall',
|
|
173
|
+
decision: input.decision ?? 'ok',
|
|
174
|
+
reason: normalizeGateLogReason(input),
|
|
175
|
+
evidence,
|
|
176
|
+
// 2.0.0 W3b:A6 五码族要能被 gate-log 读回(D19 N3 读 row.code)。可选字段:
|
|
177
|
+
// 旧行没有它 → 域与 sha 都不变,链校验/回放保持兼容。
|
|
178
|
+
...(typeof input.code === 'string' && input.code !== '' ? { code: input.code } : {}),
|
|
179
|
+
// 2.0.0 B3:每轮注入度量(字符/token/延迟)。旧行没有 → 域与 sha 不变。
|
|
180
|
+
...metricDomainFields(input),
|
|
181
|
+
};
|
|
182
|
+
const rowSha = sha256(canonicalJson(domain));
|
|
183
|
+
const head = readHeadState(paths.headFile);
|
|
184
|
+
const last = head === null ? lastRowOf(paths.logFile) : null;
|
|
185
|
+
const previous = head ?? {
|
|
186
|
+
rows: last ? 1 : 0,
|
|
187
|
+
tailSha: typeof last?.sha === 'string' ? last.sha : null,
|
|
188
|
+
};
|
|
189
|
+
const row = {
|
|
190
|
+
...domain,
|
|
191
|
+
sha: rowSha,
|
|
192
|
+
prevSha: previous.tailSha ?? null,
|
|
193
|
+
};
|
|
194
|
+
fs.mkdirSync(paths.dir, { recursive: true });
|
|
195
|
+
fs.appendFileSync(paths.logFile, `${JSON.stringify(row)}\n`, 'utf8');
|
|
196
|
+
writeHead(paths.headFile, previous.rows + 1, rowSha);
|
|
197
|
+
return row;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function appendGateLog(memoryRoot, input = {}) {
|
|
201
|
+
return appendChainedRow(gateLogPaths(memoryRoot), GATE_LOG_SCHEMA, input);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function appendLandLog(memoryRoot, input = {}) {
|
|
205
|
+
return appendChainedRow(landLogPaths(memoryRoot), LAND_LOG_SCHEMA, input);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function readRows(logFile) {
|
|
209
|
+
let text;
|
|
210
|
+
try {
|
|
211
|
+
text = fs.readFileSync(logFile, 'utf8');
|
|
212
|
+
} catch {
|
|
213
|
+
return [];
|
|
214
|
+
}
|
|
215
|
+
const rows = [];
|
|
216
|
+
for (const line of text.split(/\r?\n/)) {
|
|
217
|
+
if (line.trim() === '') continue;
|
|
218
|
+
try {
|
|
219
|
+
const parsed = JSON.parse(line);
|
|
220
|
+
if (parsed && typeof parsed === 'object') rows.push(parsed);
|
|
221
|
+
} catch {
|
|
222
|
+
/* 坏行忽略:verify 会按行数对不上报错 */
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return rows;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* 独立校验:逐行重算 sha、prevSha 链与 head 锚。返回 {ok, rows, head, errors}。
|
|
230
|
+
* 只读;不修文件。
|
|
231
|
+
*/
|
|
232
|
+
export function verifyChainedLogPaths(logFile, headFile) {
|
|
233
|
+
const rows = readRows(logFile);
|
|
234
|
+
const errors = [];
|
|
235
|
+
let previous = null;
|
|
236
|
+
for (let index = 0; index < rows.length; index += 1) {
|
|
237
|
+
const row = rows[index];
|
|
238
|
+
const expected = sha256(canonicalJson({
|
|
239
|
+
schema: row.schema,
|
|
240
|
+
at: row.at,
|
|
241
|
+
sessionId: row.sessionId ?? null,
|
|
242
|
+
turn: row.turn ?? null,
|
|
243
|
+
gate: row.gate,
|
|
244
|
+
decision: row.decision,
|
|
245
|
+
reason: row.reason,
|
|
246
|
+
evidence: Array.isArray(row.evidence) ? row.evidence : [],
|
|
247
|
+
...(typeof row.code === 'string' && row.code !== '' ? { code: row.code } : {}),
|
|
248
|
+
// 2.0.0 B3:重算域与 appendChainedRow 同口径(只补本行真的有的度量)。
|
|
249
|
+
...metricDomainFields(row),
|
|
250
|
+
}));
|
|
251
|
+
if (row.sha !== expected) errors.push(`row ${index + 1}: sha 不匹配`);
|
|
252
|
+
if (index === 0 ? row.prevSha !== null : row.prevSha !== previous) {
|
|
253
|
+
errors.push(`row ${index + 1}: prevSha 断裂`);
|
|
254
|
+
}
|
|
255
|
+
previous = row.sha;
|
|
256
|
+
}
|
|
257
|
+
let head = null;
|
|
258
|
+
try {
|
|
259
|
+
head = JSON.parse(fs.readFileSync(headFile, 'utf8'));
|
|
260
|
+
} catch {
|
|
261
|
+
errors.push('head 文件缺失或不可解析');
|
|
262
|
+
}
|
|
263
|
+
if (head) {
|
|
264
|
+
if (head.rows !== rows.length) errors.push(`head.rows=${head.rows} 与行数 ${rows.length} 不一致`);
|
|
265
|
+
if ((head.tailSha ?? null) !== (previous ?? null)) errors.push('head.tailSha 与末行 sha 不一致');
|
|
266
|
+
}
|
|
267
|
+
return { ok: errors.length === 0, rows, head, errors };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function verifyGateLog(memoryRoot) {
|
|
271
|
+
const paths = gateLogPaths(memoryRoot);
|
|
272
|
+
return verifyChainedLogPaths(paths.logFile, paths.headFile);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export function readGateLog(memoryRoot) {
|
|
276
|
+
const paths = gateLogPaths(memoryRoot);
|
|
277
|
+
return { ...paths, rows: readRows(paths.logFile) };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
export { hardgateError };
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// B3 已落 worktree · gate-log 机制补丁的纯函数层(2026-11-29 接线;供 brain 判决与 L3/L7 判据复用)
|
|
2
|
+
//
|
|
3
|
+
// 现状问题(实测 2026-11-29,memoryRoot 下两本日志):
|
|
4
|
+
// - gate-log 当日 16 行:3 行 reason 为空、0 行带 token、0 行带延迟;11 行 decision=skip
|
|
5
|
+
// (10 条 SUBAGENT + 1 条 hg.d12.skip),L2/L7 的 skip=0 判据必 FAIL。
|
|
6
|
+
// - recall-log 当日 293 行:227 条 outcome=gate-skip(安装前 legacy 链),按当天仍计 skip。
|
|
7
|
+
//
|
|
8
|
+
// 本模块提供:机制裁决所需的纯函数(M/L7 判据的重放)、gate 行度量字段的生成/校验、
|
|
9
|
+
// recall 日志行判据重放。写盘仍由 worktree 的 src/recall/gate-log.mjs(appendGateLog)负责,
|
|
10
|
+
// 补丁只在 appendChainedRow 的 sha 域里增加 GATE_METRIC_KEYS 三个可选字段并让 verify 同步比对。
|
|
11
|
+
|
|
12
|
+
export const GATE_LOG_SCHEMA = 'hardgate-gate-log/v1';
|
|
13
|
+
|
|
14
|
+
// L7 的字段解析顺序(与 checks/L7-budget-injection.mjs 保持一致)
|
|
15
|
+
export const GATE_REASON_KEYS = Object.freeze(['reason', 'reasonCode', 'reason_code', 'why', 'gateReason']);
|
|
16
|
+
export const GATE_TOKEN_KEYS = Object.freeze(['injectedTokens', 'tokens', 'estimatedTokens', 'inputTokens', 'hintTokens', 'injected_tokens']);
|
|
17
|
+
export const GATE_LATENCY_KEYS = Object.freeze(['elapsedMs', 'latencyMs', 'durationMs', 'tookMs', 'ms']);
|
|
18
|
+
|
|
19
|
+
// L7 的 skip 行判定:扫这些字段,或 skipped/blocked === true
|
|
20
|
+
export const GATE_SKIP_RE = /(gate-skip|blocked|dropped|skip|skip-policy|policy-skip)/i;
|
|
21
|
+
export const GATE_SKIP_FIELDS = Object.freeze(['outcome', 'why', 'decision', 'action', 'status', 'gate', 'reason', 'reasonCode']);
|
|
22
|
+
|
|
23
|
+
// B3 下召回注入行的判决空间:没有 skip;disabled/warn/fail 都带明确原因码。
|
|
24
|
+
export const GATE_RECALL_DECISIONS = Object.freeze(['ok', 'zero-hit', 'disabled', 'fail', 'warn']);
|
|
25
|
+
|
|
26
|
+
// 本补丁给 gate 行增加、并纳入 sha 域的三个度量字段。
|
|
27
|
+
export const GATE_METRIC_KEYS = Object.freeze(['injectedChars', 'injectedTokens', 'elapsedMs']);
|
|
28
|
+
|
|
29
|
+
function codedError(code, message, detail) {
|
|
30
|
+
const error = new Error(`${code} ${message}`);
|
|
31
|
+
error.code = code;
|
|
32
|
+
if (detail !== undefined) error.detail = detail;
|
|
33
|
+
return error;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function firstString(row, keys) {
|
|
37
|
+
for (const key of keys) {
|
|
38
|
+
const value = row?.[key];
|
|
39
|
+
if (typeof value === 'string' && value.trim() !== '') return value.trim();
|
|
40
|
+
}
|
|
41
|
+
return '';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function gateRowReason(row) {
|
|
45
|
+
return firstString(row, GATE_REASON_KEYS);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function gateRowToken(row) {
|
|
49
|
+
for (const key of GATE_TOKEN_KEYS) {
|
|
50
|
+
const value = Number(row?.[key]);
|
|
51
|
+
if (Number.isFinite(value) && value >= 0) return value;
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function gateRowLatency(row) {
|
|
57
|
+
for (const key of GATE_LATENCY_KEYS) {
|
|
58
|
+
const value = Number(row?.[key]);
|
|
59
|
+
if (Number.isFinite(value) && value >= 0) return value;
|
|
60
|
+
}
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function isSkipGateRow(row) {
|
|
65
|
+
if (row?.skipped === true || row?.blocked === true) return true;
|
|
66
|
+
for (const field of GATE_SKIP_FIELDS) {
|
|
67
|
+
const value = row?.[field];
|
|
68
|
+
if (typeof value === 'string' && GATE_SKIP_RE.test(value)) return true;
|
|
69
|
+
}
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function rowDayKey(row) {
|
|
74
|
+
for (const key of ['at', 'ts', 'time', 'timestamp', 'date']) {
|
|
75
|
+
const value = row?.[key];
|
|
76
|
+
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value)) return value.slice(0, 10);
|
|
77
|
+
if (value instanceof Date) return value.toISOString().slice(0, 10);
|
|
78
|
+
}
|
|
79
|
+
return '';
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function todayDayKey(now = new Date()) {
|
|
83
|
+
const date = now instanceof Date ? now : new Date(now);
|
|
84
|
+
const year = date.getFullYear();
|
|
85
|
+
const month = String(date.getMonth() + 1).padStart(2, '0');
|
|
86
|
+
const day = String(date.getDate()).padStart(2, '0');
|
|
87
|
+
return `${year}-${month}-${day}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// 由注入结果构造 gate/recall 共用度量:字符数、token 估算(2 字/token,与预算口径一致)、耗时。
|
|
91
|
+
export function buildGateMetrics(input = {}) {
|
|
92
|
+
const chars = Math.max(0, Math.floor(Number(input.injectedChars) || 0));
|
|
93
|
+
const elapsedMs = Math.max(0, Math.floor(Number(input.elapsedMs) || 0));
|
|
94
|
+
return { injectedChars: chars, injectedTokens: Math.ceil(chars / 2), elapsedMs };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function withGateMetrics(row, metrics) {
|
|
98
|
+
const base = { ...(row ?? {}) };
|
|
99
|
+
if (!metrics) return base;
|
|
100
|
+
const built = buildGateMetrics(metrics);
|
|
101
|
+
for (const key of GATE_METRIC_KEYS) base[key] = built[key];
|
|
102
|
+
return base;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function gateMetricFields(row) {
|
|
106
|
+
const out = {};
|
|
107
|
+
for (const key of GATE_METRIC_KEYS) {
|
|
108
|
+
const value = Number(row?.[key]);
|
|
109
|
+
if (Number.isFinite(value)) out[key] = value;
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// gate-log.mjs 的 appendChainedRow 补丁用:只把有限数值字段并入 sha 域。
|
|
115
|
+
export function applyGateMetricsToDomain(domain, metrics) {
|
|
116
|
+
const base = { ...(domain ?? {}) };
|
|
117
|
+
if (!metrics) return base;
|
|
118
|
+
const built = buildGateMetrics(metrics);
|
|
119
|
+
for (const key of GATE_METRIC_KEYS) base[key] = built[key];
|
|
120
|
+
return base;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function assertGateRow(row, options = {}) {
|
|
124
|
+
const requireReason = options.requireReason !== false;
|
|
125
|
+
const requireMetrics = options.requireMetrics === true;
|
|
126
|
+
if (requireReason && gateRowReason(row) === '') {
|
|
127
|
+
throw codedError('E_HG_GATE_ROW_REASON', 'gate 行必须有非空 reason', { row });
|
|
128
|
+
}
|
|
129
|
+
if (requireMetrics && (gateRowToken(row) === null || gateRowLatency(row) === null)) {
|
|
130
|
+
throw codedError('E_HG_GATE_ROW_METRICS', '召回注入 gate 行必须带 injectedTokens 与 elapsedMs', { row });
|
|
131
|
+
}
|
|
132
|
+
return row;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function gateLogRatio(rows) {
|
|
136
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
137
|
+
return {
|
|
138
|
+
rows: list.length,
|
|
139
|
+
withReason: list.filter((row) => gateRowReason(row) !== '').length,
|
|
140
|
+
withToken: list.filter((row) => gateRowToken(row) !== null).length,
|
|
141
|
+
withLatency: list.filter((row) => gateRowLatency(row) !== null).length,
|
|
142
|
+
skipRows: list.filter(isSkipGateRow).length,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// L7 判据 b 的纯函数重放(gate-log):当日行>0、每行有 reason、≥1 行带 token、≥1 行带延迟、skip=0。
|
|
147
|
+
export function l7GateLogVerdict(rows, options = {}) {
|
|
148
|
+
const day = String(options.day ?? todayDayKey());
|
|
149
|
+
const todayRows = (Array.isArray(rows) ? rows : []).filter((row) => rowDayKey(row) === day);
|
|
150
|
+
const skipRows = todayRows.filter(isSkipGateRow);
|
|
151
|
+
const reasonsMissing = todayRows.filter((row) => gateRowReason(row) === '').length;
|
|
152
|
+
const withToken = todayRows.filter((row) => gateRowToken(row) !== null).length;
|
|
153
|
+
const withLatency = todayRows.filter((row) => gateRowLatency(row) !== null).length;
|
|
154
|
+
return {
|
|
155
|
+
day,
|
|
156
|
+
todayRows: todayRows.length,
|
|
157
|
+
reasonsMissing,
|
|
158
|
+
withToken,
|
|
159
|
+
withLatency,
|
|
160
|
+
skipRows: skipRows.length,
|
|
161
|
+
skipReasons: skipRows.map((row) => ({ gate: row?.gate, decision: row?.decision, reason: gateRowReason(row) })),
|
|
162
|
+
pass: todayRows.length > 0 && reasonsMissing === 0 && withToken >= 1 && withLatency >= 1 && skipRows.length === 0,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// L7 判据 c 的纯函数重放(recall-log):当日行>0、skip=0、injected 行带 token、≥1 行带延迟。
|
|
167
|
+
export function l7RecallLogVerdict(rows, options = {}) {
|
|
168
|
+
const day = String(options.day ?? todayDayKey());
|
|
169
|
+
const todayRows = (Array.isArray(rows) ? rows : []).filter((row) => rowDayKey(row) === day);
|
|
170
|
+
const skipRows = todayRows.filter(isSkipGateRow);
|
|
171
|
+
const injectedRows = todayRows.filter((row) => Number(row?.injectedCount) > 0 || row?.injected === true);
|
|
172
|
+
const injectedMissingToken = injectedRows.filter((row) => gateRowToken(row) === null).length;
|
|
173
|
+
const withLatency = todayRows.filter((row) => gateRowLatency(row) !== null).length;
|
|
174
|
+
return {
|
|
175
|
+
day,
|
|
176
|
+
todayRows: todayRows.length,
|
|
177
|
+
injectedRows: injectedRows.length,
|
|
178
|
+
injectedMissingToken,
|
|
179
|
+
withLatency,
|
|
180
|
+
skipRows: skipRows.length,
|
|
181
|
+
pass: todayRows.length > 0 && skipRows.length === 0 && injectedMissingToken === 0 && withLatency >= 1,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function assertNoSkipRows(rows, label = 'gate-log') {
|
|
186
|
+
const skipRows = (Array.isArray(rows) ? rows : []).filter(isSkipGateRow);
|
|
187
|
+
if (skipRows.length > 0) {
|
|
188
|
+
throw codedError('E_HG_GATE_SKIP_ROWS', `${label} 出现 skip 行 ${skipRows.length} 条`, { skipRows });
|
|
189
|
+
}
|
|
190
|
+
return rows;
|
|
191
|
+
}
|