@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,569 @@
|
|
|
1
|
+
// R1 runtime adapter: judge memory-tool calls with the pure router and record
|
|
2
|
+
// the decision, without changing what the tool actually does.
|
|
3
|
+
//
|
|
4
|
+
// routerRuntime: 'off' -> not even imported into the hot path (no judgement)
|
|
5
|
+
// routerRuntime: 'shadow' -> judge + append one JSONL record, behaviour identical
|
|
6
|
+
// routerRuntime: 'on' -> additionally refuse high-risk WRITE calls
|
|
7
|
+
//
|
|
8
|
+
// Design notes (see DESIGN.md):
|
|
9
|
+
// * Shadow mode must be observationally invisible: same return value, same
|
|
10
|
+
// thrown error object, no added latency beyond one route() + one append.
|
|
11
|
+
// * On mode is deliberately narrow: reads (memory_recall) are never refused,
|
|
12
|
+
// and a dry-run memory_forget (no confirm:"FORGET") is not a delete.
|
|
13
|
+
// * Any failure here is contained: a broken router can never crash a tool. In
|
|
14
|
+
// shadow a failed judgement is recorded and the call proceeds unchanged; in
|
|
15
|
+
// on a failed judgement refuses write calls (fail-closed) but not reads.
|
|
16
|
+
//
|
|
17
|
+
// This module has no host dependency at all: it is imported by tools.js and by
|
|
18
|
+
// plain `node --test` suites, so everything is injected through options.
|
|
19
|
+
|
|
20
|
+
import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
21
|
+
import { dirname, join, resolve } from 'node:path';
|
|
22
|
+
import { route, ruleById } from './route.js';
|
|
23
|
+
import {
|
|
24
|
+
externalActionGroups,
|
|
25
|
+
externalLegacyToolNames,
|
|
26
|
+
externalWriteToolNames,
|
|
27
|
+
interceptedToolNames,
|
|
28
|
+
isExternalMemoryDeleteAction,
|
|
29
|
+
isExternalMemoryProfileEdit,
|
|
30
|
+
} from '../adapters/registry.js';
|
|
31
|
+
|
|
32
|
+
// Longlive Router 1.1.0 service seam. Product code (src/index.js) imports the
|
|
33
|
+
// Router only through this module, which keeps the R1 topology test's single
|
|
34
|
+
// seam (`src/index.js -> src/router/runtime.js`) intact.
|
|
35
|
+
export { createRouterService } from './service/service.mjs';
|
|
36
|
+
export { normalizeRouterConfig } from './service/config.mjs';
|
|
37
|
+
export { createRouterTools } from './service/tools.mjs';
|
|
38
|
+
|
|
39
|
+
export const RUNTIME_MODES = Object.freeze(['off', 'shadow', 'on']);
|
|
40
|
+
export const DEFAULT_RUNTIME_MODE = 'off';
|
|
41
|
+
export const STATE_FILE_NAME = 'router-runtime.jsonl';
|
|
42
|
+
export const MAX_RECORDS_DEFAULT = 1000;
|
|
43
|
+
export const ROUTE_REFUSED_CODE = 'E_ROUTE_REFUSED';
|
|
44
|
+
|
|
45
|
+
// Tools whose arguments R1 knows how to judge。第三方记忆工具(旧名 + 新名)由
|
|
46
|
+
// adapters/registry.js 提供,本插件注册的 core 工具名保持显式。
|
|
47
|
+
const CORE_INTERCEPTED_TOOLS = Object.freeze(['memory_recall', 'memory_consolidate', 'memory_forget']);
|
|
48
|
+
export const INTERCEPTED_TOOLS = Object.freeze([
|
|
49
|
+
...externalLegacyToolNames(),
|
|
50
|
+
...CORE_INTERCEPTED_TOOLS,
|
|
51
|
+
...interceptedToolNames().filter((name) => !externalLegacyToolNames().includes(name)),
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
// Only these can mutate the store; `memory_recall` is read-only and must never
|
|
55
|
+
// be refused, not even when the rule table is unreadable.
|
|
56
|
+
export const WRITE_TOOLS = Object.freeze([
|
|
57
|
+
...externalWriteToolNames(),
|
|
58
|
+
'memory_consolidate',
|
|
59
|
+
'memory_forget',
|
|
60
|
+
]);
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Coerce a config value into a known mode. Anything unrecognised falls back to
|
|
64
|
+
* `off` (never to `on`): a typo in the profile must not start refusing calls.
|
|
65
|
+
*/
|
|
66
|
+
export function normalizeMode(value) {
|
|
67
|
+
if (value === undefined || value === null || value === '') return DEFAULT_RUNTIME_MODE;
|
|
68
|
+
const mode = String(value).trim().toLowerCase();
|
|
69
|
+
return RUNTIME_MODES.includes(mode) ? mode : DEFAULT_RUNTIME_MODE;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Where the rolling record lives: explicit path wins, else
|
|
74
|
+
* `<memoryRoot>/.longlive/router-runtime.jsonl`.
|
|
75
|
+
*
|
|
76
|
+
* 1.2.0 moved the default under `.longlive/` so every passive audit artifact
|
|
77
|
+
* (filter decisions, guard records, live rows) shares one hidden root. The
|
|
78
|
+
* panel reads both the old top-level file and this one, so an upgraded host
|
|
79
|
+
* with an old file keeps working; new records always go to `.longlive/`.
|
|
80
|
+
*/
|
|
81
|
+
export function resolveStatePath(options = {}) {
|
|
82
|
+
if (typeof options.statePath === 'string' && options.statePath.trim()) return resolve(options.statePath);
|
|
83
|
+
const root = typeof options.memoryRoot === 'string' && options.memoryRoot.trim() ? options.memoryRoot : null;
|
|
84
|
+
return root ? resolve(join(root, '.longlive', STATE_FILE_NAME)) : null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function round3(value) {
|
|
88
|
+
return Math.round(value * 1000) / 1000;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function defaultNow() {
|
|
92
|
+
if (typeof performance !== 'undefined' && typeof performance.now === 'function') return performance.now();
|
|
93
|
+
return Date.now();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const FLAG_KEYS = new Set(['confirm', 'apply', 'action', 'name', 'slug', 'room', 'status', 'since', 'topK', 'dryRun']);
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Flatten the arguments into the single lowercase string `route()` reads. R1
|
|
100
|
+
* matches keywords (substring) over `text`, and none of the memory rules has a
|
|
101
|
+
* `match.tool` entry, so both the tool name and the values must be present.
|
|
102
|
+
*/
|
|
103
|
+
export function buildJudgeText(tool, args) {
|
|
104
|
+
const parts = [String(tool || '')];
|
|
105
|
+
const seen = new Set();
|
|
106
|
+
const push = (value, limit) => {
|
|
107
|
+
const text = String(value).replace(/\s+/g, ' ').trim();
|
|
108
|
+
if (!text || seen.has(text)) return;
|
|
109
|
+
seen.add(text);
|
|
110
|
+
parts.push(text.slice(0, limit));
|
|
111
|
+
};
|
|
112
|
+
const walk = (value, key, depth) => {
|
|
113
|
+
if (depth > 3 || value === null || value === undefined) return;
|
|
114
|
+
if (typeof value === 'string') {
|
|
115
|
+
// Flag values are recorded as `k=v` so a reader can tell "confirm=FORGET"
|
|
116
|
+
// from a stray word; the router only does substring matching either way.
|
|
117
|
+
if (FLAG_KEYS.has(key)) push(`${key}=${value}`, 160);
|
|
118
|
+
else push(value, 200);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (typeof value === 'number' || typeof value === 'boolean') {
|
|
122
|
+
if (FLAG_KEYS.has(key)) push(`${key}=${value}`, 80);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (Array.isArray(value)) {
|
|
126
|
+
for (const item of value.slice(0, 12)) walk(item, key, depth + 1);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (typeof value === 'object') {
|
|
130
|
+
for (const [childKey, childValue] of Object.entries(value).slice(0, 24)) walk(childValue, childKey, depth + 1);
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
walk(args, '', 0);
|
|
134
|
+
return parts.join(' ').toLowerCase().slice(0, 2000);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Keep the recorded arguments small and JSON-safe; never throw on odd shapes. */
|
|
138
|
+
export function summarizeArgs(args) {
|
|
139
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) return { value: String(args ?? null).slice(0, 120) };
|
|
140
|
+
const out = {};
|
|
141
|
+
for (const [key, value] of Object.entries(args).slice(0, 12)) {
|
|
142
|
+
if (typeof value === 'string') out[key] = value.length > 160 ? `${value.slice(0, 160)}…` : value;
|
|
143
|
+
else if (typeof value === 'number' || typeof value === 'boolean' || value === null) out[key] = value;
|
|
144
|
+
else if (Array.isArray(value)) out[key] = `[${value.length}]`;
|
|
145
|
+
else out[key] = '<object>';
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Which rule's action is the *deciding* one. `decisions[]` also carries the
|
|
152
|
+
* rule's `before` steps (e.g. R-MEM-DISTILL starts with an external search), so
|
|
153
|
+
* `decisions[0]` is not the verdict; the rule table is the source of truth.
|
|
154
|
+
*/
|
|
155
|
+
function primaryAction(result) {
|
|
156
|
+
const ruleId = result && typeof result.matchedRule === 'string' ? result.matchedRule : null;
|
|
157
|
+
if (ruleId) {
|
|
158
|
+
const rule = ruleById(ruleId);
|
|
159
|
+
if (rule && rule.decision && typeof rule.decision.action === 'string') return rule.decision.action;
|
|
160
|
+
}
|
|
161
|
+
const decisions = Array.isArray(result?.decisions) ? result.decisions : [];
|
|
162
|
+
const wanted = result?.decision?.tool ?? null;
|
|
163
|
+
const hit = decisions.find((entry) => entry && entry.ruleId === ruleId && (entry.tool ?? null) === wanted);
|
|
164
|
+
if (hit && typeof hit.action === 'string') return hit.action;
|
|
165
|
+
const fallback = decisions.find((entry) => entry && entry.ruleId === ruleId);
|
|
166
|
+
return fallback && typeof fallback.action === 'string' ? fallback.action : null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* High-risk classification for `on` mode. Only three families may be refused:
|
|
171
|
+
* deleting store content, changing identity, writing the real store.
|
|
172
|
+
*/
|
|
173
|
+
export function classifyRisk({ tool, args, matchedRule, action, failClosed = false }) {
|
|
174
|
+
const reasons = [];
|
|
175
|
+
if (failClosed) reasons.push('fail-closed');
|
|
176
|
+
if (matchedRule === 'R-GUARD-REAL' || action === 'guard.refuse') reasons.push('real-store');
|
|
177
|
+
if (
|
|
178
|
+
matchedRule === 'R-ID-CONSENT' ||
|
|
179
|
+
isExternalMemoryProfileEdit(action) ||
|
|
180
|
+
(typeof action === 'string' && action.startsWith('identity.'))
|
|
181
|
+
) {
|
|
182
|
+
reasons.push('identity');
|
|
183
|
+
}
|
|
184
|
+
// A memory_forget without confirm:"FORGET" only previews; it deletes nothing.
|
|
185
|
+
const confirm = args && typeof args === 'object' ? args.confirm : undefined;
|
|
186
|
+
const forgetDryRun = tool === 'memory_forget' && confirm !== 'FORGET';
|
|
187
|
+
if (!forgetDryRun) {
|
|
188
|
+
if (tool === 'memory_forget') reasons.push('delete');
|
|
189
|
+
else if (matchedRule === 'R-MEM-DISTILL') reasons.push('delete');
|
|
190
|
+
else if (typeof action === 'string' && (action === 'memory.delete' || isExternalMemoryDeleteAction(action))) reasons.push('delete');
|
|
191
|
+
}
|
|
192
|
+
const level = reasons.includes('real-store')
|
|
193
|
+
? 'real-store'
|
|
194
|
+
: reasons.includes('identity')
|
|
195
|
+
? 'identity'
|
|
196
|
+
: reasons.includes('delete')
|
|
197
|
+
? 'delete'
|
|
198
|
+
: reasons.includes('fail-closed')
|
|
199
|
+
? 'fail-closed'
|
|
200
|
+
: 'none';
|
|
201
|
+
return { level, reasons };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* The panel contract (§6) exposes `action` as allow|deny|ask, while the R1
|
|
206
|
+
* decision action is a semantic verb (`memory.distillPropose`, ...). Keep the
|
|
207
|
+
* verb in `decision.action` and put the contract value at the top level.
|
|
208
|
+
*/
|
|
209
|
+
function contractAction(described, guardVerdict) {
|
|
210
|
+
if (guardVerdict === 'deny' || described.action === 'guard.refuse') return 'deny';
|
|
211
|
+
if (described.needsHuman) return 'ask';
|
|
212
|
+
return 'allow';
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function contractFields(tool, described, guardVerdict, callText, outcome) {
|
|
216
|
+
return {
|
|
217
|
+
subject: tool,
|
|
218
|
+
action: contractAction(described, guardVerdict),
|
|
219
|
+
level: described.level,
|
|
220
|
+
matchedRule: described.ruleId,
|
|
221
|
+
confidence: described.confidence,
|
|
222
|
+
needsHuman: described.needsHuman,
|
|
223
|
+
callText,
|
|
224
|
+
status: outcome.status,
|
|
225
|
+
errors: described.errors,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function refusalMessage({ tool, ruleId, level, needsHuman, reasons = [] }) { const reason = reasons.length ? reasons.join('+') : 'high-risk';
|
|
230
|
+
return (
|
|
231
|
+
`${ROUTE_REFUSED_CODE}: ${tool} refused by the R1 router ` +
|
|
232
|
+
`(risk=${reason}, rule=${ruleId ?? 'none'}, level=${level ?? 'null'}, needsHuman=${needsHuman === true}). ` +
|
|
233
|
+
'The underlying tool was not called. Set routerRuntime to "shadow" to record without enforcing.'
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function routeRefusedError(details) {
|
|
238
|
+
const error = new Error(refusalMessage(details));
|
|
239
|
+
error.code = ROUTE_REFUSED_CODE;
|
|
240
|
+
error.details = details;
|
|
241
|
+
return error;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* One JSONL sink with a hard line cap. Rotation keeps the newest `maxRecords`
|
|
246
|
+
* lines and replaces the file atomically (tmp + rename), so a crash never
|
|
247
|
+
* leaves a half-written record set.
|
|
248
|
+
*/
|
|
249
|
+
function createRecordStore({ statePath, maxRecords, onError }) {
|
|
250
|
+
let count = null;
|
|
251
|
+
let appendsSinceCheck = 0;
|
|
252
|
+
|
|
253
|
+
function countLines() {
|
|
254
|
+
try {
|
|
255
|
+
const text = readFileSync(statePath, 'utf8');
|
|
256
|
+
return text ? text.split('\n').filter(Boolean).length : 0;
|
|
257
|
+
} catch (error) {
|
|
258
|
+
if (error && error.code === 'ENOENT') return 0;
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function rotationCheck() {
|
|
264
|
+
appendsSinceCheck += 1;
|
|
265
|
+
if (appendsSinceCheck < 64) return;
|
|
266
|
+
appendsSinceCheck = 0;
|
|
267
|
+
try {
|
|
268
|
+
// Bounds growth if another writer appended behind our back.
|
|
269
|
+
if (statSync(statePath).size > maxRecords * 4096) count = countLines();
|
|
270
|
+
} catch {
|
|
271
|
+
/* size probe is best effort */
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function rotate() {
|
|
276
|
+
const lines = readFileSync(statePath, 'utf8').split('\n').filter(Boolean);
|
|
277
|
+
const kept = lines.slice(-maxRecords);
|
|
278
|
+
const tmp = `${statePath}.tmp-${process.pid}`;
|
|
279
|
+
writeFileSync(tmp, `${kept.join('\n')}\n`, 'utf8');
|
|
280
|
+
renameSync(tmp, statePath);
|
|
281
|
+
count = kept.length;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function append(record) {
|
|
285
|
+
if (!statePath) return false;
|
|
286
|
+
try {
|
|
287
|
+
if (count === null) count = countLines();
|
|
288
|
+
mkdirSync(dirname(statePath), { recursive: true });
|
|
289
|
+
appendFileSync(statePath, `${JSON.stringify(record)}\n`, 'utf8');
|
|
290
|
+
count += 1;
|
|
291
|
+
if (count > maxRecords) rotate();
|
|
292
|
+
rotationCheck();
|
|
293
|
+
return true;
|
|
294
|
+
} catch (error) {
|
|
295
|
+
try {
|
|
296
|
+
onError?.(error);
|
|
297
|
+
} catch {
|
|
298
|
+
/* reporting a broken sink must not break the tool */
|
|
299
|
+
}
|
|
300
|
+
return false;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
return {
|
|
305
|
+
append,
|
|
306
|
+
get path() {
|
|
307
|
+
return statePath;
|
|
308
|
+
},
|
|
309
|
+
get lineCount() {
|
|
310
|
+
return count;
|
|
311
|
+
},
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Build the runtime adapter.
|
|
317
|
+
*
|
|
318
|
+
* @param {object} options
|
|
319
|
+
* @param {'off'|'shadow'|'on'} [options.mode='off']
|
|
320
|
+
* @param {string} [options.statePath] explicit JSONL path
|
|
321
|
+
* @param {string} [options.memoryRoot] used when `statePath` is absent
|
|
322
|
+
* @param {number} [options.maxRecords=1000]
|
|
323
|
+
* @param {string[]} [options.ownTools] names registered by this plugin (guard skips them)
|
|
324
|
+
* @param {boolean} [options.recordAllTools=false] shadow mode: also judge tools
|
|
325
|
+
* outside INTERCEPTED_TOOLS (still record-only — never refuse)
|
|
326
|
+
* @param {(error: Error) => void} [options.onError] record-sink failure reporter
|
|
327
|
+
* @param {Function} [options.routeImpl] test seam, defaults to the real router
|
|
328
|
+
* @param {Function} [options.now] test seam, monotonic milliseconds
|
|
329
|
+
*/
|
|
330
|
+
export function createRouterRuntime(options = {}) {
|
|
331
|
+
const requested = options.mode;
|
|
332
|
+
const mode = normalizeMode(requested);
|
|
333
|
+
const modeInvalid =
|
|
334
|
+
requested !== undefined && requested !== null && requested !== '' && String(requested).trim().toLowerCase() !== mode;
|
|
335
|
+
const maxRecords = Number.isInteger(options.maxRecords) && options.maxRecords > 0 ? options.maxRecords : MAX_RECORDS_DEFAULT;
|
|
336
|
+
const statePath = resolveStatePath(options);
|
|
337
|
+
const ownTools = new Set(Array.isArray(options.ownTools) ? options.ownTools.filter((name) => typeof name === 'string') : []);
|
|
338
|
+
const routeImpl = typeof options.routeImpl === 'function' ? options.routeImpl : route;
|
|
339
|
+
const now = typeof options.now === 'function' ? options.now : defaultNow;
|
|
340
|
+
const onError = options.onError;
|
|
341
|
+
const recordAllTools = options.recordAllTools === true;
|
|
342
|
+
|
|
343
|
+
const store = createRecordStore({ statePath, maxRecords, onError });
|
|
344
|
+
const stats = { judged: 0, recorded: 0, denied: 0, errors: 0, lastLatencyMs: null };
|
|
345
|
+
|
|
346
|
+
const enabled = mode !== 'off';
|
|
347
|
+
|
|
348
|
+
function judge(tool, args) {
|
|
349
|
+
const started = now();
|
|
350
|
+
try {
|
|
351
|
+
const result = routeImpl({ kind: 'memory', text: buildJudgeText(tool, args), candidates: [tool], ctx: {} });
|
|
352
|
+
return { ok: true, result, latencyMs: round3(now() - started) };
|
|
353
|
+
} catch (error) {
|
|
354
|
+
return { ok: false, error, latencyMs: round3(now() - started) };
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function write(record) {
|
|
359
|
+
const ok = store.append(record);
|
|
360
|
+
if (ok) stats.recorded += 1;
|
|
361
|
+
return ok;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function baseRecord(tool, args, judged) {
|
|
365
|
+
const result = judged.ok ? judged.result : null;
|
|
366
|
+
const ruleId = result && typeof result.matchedRule === 'string' ? result.matchedRule : null;
|
|
367
|
+
const failClosed = judged.ok ? result?.failClosed === true : true;
|
|
368
|
+
const action = judged.ok ? primaryAction(result) : 'guard.refuse';
|
|
369
|
+
const risk = classifyRisk({ tool, args, matchedRule: failClosed ? 'R-ROUTER-FAILCLOSED' : ruleId, action, failClosed });
|
|
370
|
+
return {
|
|
371
|
+
ruleId: failClosed ? 'R-ROUTER-FAILCLOSED' : ruleId,
|
|
372
|
+
action: judged.ok ? action : 'guard.refuse',
|
|
373
|
+
level: judged.ok ? (result?.level ?? null) : null,
|
|
374
|
+
needsHuman: judged.ok ? result?.needsHuman === true : true,
|
|
375
|
+
confidence: judged.ok ? (typeof result?.confidence === 'number' ? result.confidence : 0) : 0,
|
|
376
|
+
failClosed,
|
|
377
|
+
errors: judged.ok && Array.isArray(result?.errors) ? result.errors.map((e) => (e && e.code) || String(e)) : judged.ok ? [] : ['E_ROUTE_EXCEPTION'],
|
|
378
|
+
target: judged.ok ? (result?.target ?? null) : null,
|
|
379
|
+
decisionTool: judged.ok ? (result?.decision?.tool ?? null) : null,
|
|
380
|
+
risk,
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function shouldDeny(tool, described) {
|
|
385
|
+
if (mode !== 'on') return false;
|
|
386
|
+
if (!WRITE_TOOLS.includes(tool)) return false;
|
|
387
|
+
if (described.failClosed) return true;
|
|
388
|
+
return described.risk.level !== 'none';
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Wrap one tool invocation. Returns whatever the tool returns when the mode
|
|
393
|
+
* is off or the tool is not intercepted — synchronously, so `off` is a true
|
|
394
|
+
* no-op. In shadow/on it resolves to the tool's value or rejects with the
|
|
395
|
+
* tool's original error.
|
|
396
|
+
*/
|
|
397
|
+
function intercept(tool, args, run) {
|
|
398
|
+
if (!enabled) return run();
|
|
399
|
+
// Shadow mode is the passive observer: with recordAllTools it also sees
|
|
400
|
+
// the plugin's own session/memory surface. `on` keeps the narrow R1 scope
|
|
401
|
+
// so enabling enforcement cannot start refusing unrelated tools.
|
|
402
|
+
const inScope = INTERCEPTED_TOOLS.includes(tool) || (mode === 'shadow' && recordAllTools);
|
|
403
|
+
if (!inScope) return run();
|
|
404
|
+
const startedAt = now();
|
|
405
|
+
const judged = judge(tool, args);
|
|
406
|
+
const described = baseRecord(tool, args, judged);
|
|
407
|
+
const deny = shouldDeny(tool, described);
|
|
408
|
+
const ts = new Date().toISOString();
|
|
409
|
+
const callText = buildJudgeText(tool, args);
|
|
410
|
+
stats.judged += 1;
|
|
411
|
+
stats.lastLatencyMs = judged.latencyMs;
|
|
412
|
+
|
|
413
|
+
if (deny) {
|
|
414
|
+
stats.denied += 1;
|
|
415
|
+
const details = {
|
|
416
|
+
tool,
|
|
417
|
+
ruleId: described.ruleId,
|
|
418
|
+
level: described.level,
|
|
419
|
+
needsHuman: described.needsHuman,
|
|
420
|
+
risk: described.risk.level,
|
|
421
|
+
reasons: described.risk.reasons,
|
|
422
|
+
latencyMs: judged.latencyMs,
|
|
423
|
+
};
|
|
424
|
+
write({
|
|
425
|
+
ts,
|
|
426
|
+
mode,
|
|
427
|
+
tool,
|
|
428
|
+
...contractFields(tool, described, 'deny', buildJudgeText(tool, args), { status: 'denied' }),
|
|
429
|
+
call: { text: buildJudgeText(tool, args), args: summarizeArgs(args) },
|
|
430
|
+
decision: {
|
|
431
|
+
matchedRule: described.ruleId,
|
|
432
|
+
ruleId: described.ruleId,
|
|
433
|
+
action: described.action,
|
|
434
|
+
level: described.level,
|
|
435
|
+
target: described.target,
|
|
436
|
+
tool: described.decisionTool,
|
|
437
|
+
needsHuman: described.needsHuman,
|
|
438
|
+
confidence: described.confidence,
|
|
439
|
+
failClosed: described.failClosed,
|
|
440
|
+
errors: described.errors,
|
|
441
|
+
},
|
|
442
|
+
risk: described.risk,
|
|
443
|
+
guard: { verdict: 'deny', reason: refusalMessage(details) },
|
|
444
|
+
outcome: { status: 'denied', ms: 0 },
|
|
445
|
+
latencyMs: judged.latencyMs,
|
|
446
|
+
totalMs: round3(now() - startedAt),
|
|
447
|
+
});
|
|
448
|
+
return Promise.reject(routeRefusedError(details));
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
return (async () => {
|
|
452
|
+
let result;
|
|
453
|
+
let failure = null;
|
|
454
|
+
try {
|
|
455
|
+
result = await run();
|
|
456
|
+
} catch (error) {
|
|
457
|
+
failure = error;
|
|
458
|
+
}
|
|
459
|
+
const totalMs = round3(now() - startedAt);
|
|
460
|
+
write({
|
|
461
|
+
ts,
|
|
462
|
+
mode,
|
|
463
|
+
tool,
|
|
464
|
+
...contractFields(tool, described, 'allow', buildJudgeText(tool, args), { status: failure ? 'error' : 'ok' }),
|
|
465
|
+
call: { text: buildJudgeText(tool, args), args: summarizeArgs(args) },
|
|
466
|
+
decision: {
|
|
467
|
+
matchedRule: described.ruleId,
|
|
468
|
+
ruleId: described.ruleId,
|
|
469
|
+
action: described.action,
|
|
470
|
+
level: described.level,
|
|
471
|
+
target: described.target,
|
|
472
|
+
tool: described.decisionTool,
|
|
473
|
+
needsHuman: described.needsHuman,
|
|
474
|
+
confidence: described.confidence,
|
|
475
|
+
failClosed: described.failClosed,
|
|
476
|
+
errors: described.errors,
|
|
477
|
+
},
|
|
478
|
+
risk: described.risk,
|
|
479
|
+
guard: { verdict: 'allow', reason: null },
|
|
480
|
+
outcome: failure
|
|
481
|
+
? { status: 'error', code: (failure && failure.code) || (failure && failure.name) || 'Error', ms: totalMs }
|
|
482
|
+
: { status: 'ok', ms: totalMs },
|
|
483
|
+
latencyMs: judged.latencyMs,
|
|
484
|
+
totalMs,
|
|
485
|
+
});
|
|
486
|
+
if (failure) throw failure;
|
|
487
|
+
return result;
|
|
488
|
+
})();
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Host `tools.guard` adapter for intercepted tools this plugin does NOT
|
|
493
|
+
* register (currently an external memory tool). Synchronous by contract; the
|
|
494
|
+
* guard returns a reason string to deny and `undefined` to allow. It never
|
|
495
|
+
* throws: an exception here would fail the whole tool surface.
|
|
496
|
+
*/
|
|
497
|
+
function guard(tool, args) {
|
|
498
|
+
if (!enabled || !INTERCEPTED_TOOLS.includes(tool) || ownTools.has(tool)) return undefined;
|
|
499
|
+
try {
|
|
500
|
+
const judged = judge(tool, args);
|
|
501
|
+
const described = baseRecord(tool, args, judged);
|
|
502
|
+
const deny = shouldDeny(tool, described);
|
|
503
|
+
stats.judged += 1;
|
|
504
|
+
stats.lastLatencyMs = judged.latencyMs;
|
|
505
|
+
const details = {
|
|
506
|
+
tool,
|
|
507
|
+
ruleId: described.ruleId,
|
|
508
|
+
level: described.level,
|
|
509
|
+
needsHuman: described.needsHuman,
|
|
510
|
+
risk: described.risk.level,
|
|
511
|
+
reasons: described.risk.reasons,
|
|
512
|
+
latencyMs: judged.latencyMs,
|
|
513
|
+
};
|
|
514
|
+
if (deny) stats.denied += 1;
|
|
515
|
+
write({
|
|
516
|
+
ts: new Date().toISOString(),
|
|
517
|
+
mode,
|
|
518
|
+
tool,
|
|
519
|
+
source: 'guard',
|
|
520
|
+
...contractFields(tool, described, deny ? 'deny' : 'allow', buildJudgeText(tool, args), { status: deny ? 'denied' : 'pre-only' }),
|
|
521
|
+
call: { text: buildJudgeText(tool, args), args: summarizeArgs(args) },
|
|
522
|
+
decision: {
|
|
523
|
+
matchedRule: described.ruleId,
|
|
524
|
+
ruleId: described.ruleId,
|
|
525
|
+
action: described.action,
|
|
526
|
+
level: described.level,
|
|
527
|
+
target: described.target,
|
|
528
|
+
tool: described.decisionTool,
|
|
529
|
+
needsHuman: described.needsHuman,
|
|
530
|
+
confidence: described.confidence,
|
|
531
|
+
failClosed: described.failClosed,
|
|
532
|
+
errors: described.errors,
|
|
533
|
+
},
|
|
534
|
+
risk: described.risk,
|
|
535
|
+
guard: { verdict: deny ? 'deny' : 'allow', reason: deny ? refusalMessage(details) : null },
|
|
536
|
+
outcome: { status: deny ? 'denied' : 'pre-only', ms: 0 },
|
|
537
|
+
latencyMs: judged.latencyMs,
|
|
538
|
+
totalMs: judged.latencyMs,
|
|
539
|
+
});
|
|
540
|
+
return deny ? refusalMessage(details) : undefined;
|
|
541
|
+
} catch {
|
|
542
|
+
// Fail closed for writes only; a read must never be blocked by our bug.
|
|
543
|
+
if (mode === 'on' && WRITE_TOOLS.includes(tool)) {
|
|
544
|
+
return `${ROUTE_REFUSED_CODE}: ${tool} refused because the router failed to judge the call.`;
|
|
545
|
+
}
|
|
546
|
+
return undefined;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** True when the host guard should own this name (not registered by us). */
|
|
551
|
+
function handles(name) {
|
|
552
|
+
return enabled && INTERCEPTED_TOOLS.includes(name) && !ownTools.has(name);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
return {
|
|
556
|
+
mode,
|
|
557
|
+
modeInvalid,
|
|
558
|
+
maxRecords,
|
|
559
|
+
enabled,
|
|
560
|
+
statePath,
|
|
561
|
+
ownTools: [...ownTools],
|
|
562
|
+
intercept,
|
|
563
|
+
guard,
|
|
564
|
+
handles,
|
|
565
|
+
stats: () => ({ ...stats, mode, statePath }),
|
|
566
|
+
/** Test/diagnostic helper: the record a judge would produce, without IO. */
|
|
567
|
+
describe: (tool, args) => baseRecord(tool, args, judge(tool, args)),
|
|
568
|
+
};
|
|
569
|
+
}
|