@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,191 @@
|
|
|
1
|
+
// src/role/activation.js — 角色内核运行期激活探针(任务「功能没跑起来就等于没实现」)
|
|
2
|
+
//
|
|
3
|
+
// 这不是单测替身:它按宿主真实装配路径跑一遍 ——
|
|
4
|
+
// 1) Config schema 默认值(role.enabled=true)经 registerRole 注册;
|
|
5
|
+
// 2) 用真实 `(session, event)` 形态驱动已注册的 session/event hook(不是直接调 readers);
|
|
6
|
+
// 3) 让宿主注入回调 `systemPrompt.section().text()` 真实取一次语气投影;
|
|
7
|
+
// 4) 然后才读回落盘数据,断言 attention/relationships/personality/channels 都有运行期证据。
|
|
8
|
+
//
|
|
9
|
+
// 供 `scripts/verify-activation.mjs`(acceptance-harness 的激活门禁)调用:
|
|
10
|
+
// 入口:`src/role/activation.js` 的 `probeRoleActivation`(供 verify-activation.mjs 调用)
|
|
11
|
+
// const role = probeRoleActivation({ memoryRoot: <隔离目录> });
|
|
12
|
+
// if (!role.ok) failure('role kernel', role);
|
|
13
|
+
//
|
|
14
|
+
// 纯本地、不联网、不碰真 memoryRoot(memoryRoot 缺省用 OS 临时目录并在结束时清理)。
|
|
15
|
+
// kill switch 探针:`probeRoleActivation({ killSwitch: true })` 应返回 enabled:false 且零文件。
|
|
16
|
+
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import os from 'node:os';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
|
|
21
|
+
import { registerRole } from './index.js';
|
|
22
|
+
import { updateRelationship } from './relationships.js';
|
|
23
|
+
|
|
24
|
+
export const ROLE_ACTIVATION_SCHEMA = 'role-activation/v1';
|
|
25
|
+
export const ROLE_ACTIVATION_CHECKS = Object.freeze([
|
|
26
|
+
'enabled',
|
|
27
|
+
'hooksRegistered',
|
|
28
|
+
'eventsSeen',
|
|
29
|
+
'attentionIngested',
|
|
30
|
+
'relationshipRead',
|
|
31
|
+
'channelTouched',
|
|
32
|
+
'personalityProjected',
|
|
33
|
+
'attentionFilePresent',
|
|
34
|
+
'channelsFilePresent',
|
|
35
|
+
'personalityFilePresent',
|
|
36
|
+
'toneSectionInjected',
|
|
37
|
+
'auditFilePresent',
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
function makeFakeHost() {
|
|
41
|
+
const listeners = new Map();
|
|
42
|
+
const sections = [];
|
|
43
|
+
const ctx = {
|
|
44
|
+
on(name, handler) {
|
|
45
|
+
const list = listeners.get(name) ?? [];
|
|
46
|
+
list.push(handler);
|
|
47
|
+
listeners.set(name, list);
|
|
48
|
+
return () => {
|
|
49
|
+
const index = list.indexOf(handler);
|
|
50
|
+
if (index >= 0) list.splice(index, 1);
|
|
51
|
+
};
|
|
52
|
+
},
|
|
53
|
+
effect(fn) {
|
|
54
|
+
try {
|
|
55
|
+
const dispose = fn();
|
|
56
|
+
return typeof dispose === 'function' ? dispose : () => {};
|
|
57
|
+
} catch {
|
|
58
|
+
return () => {};
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
logger: () => ({ info() {}, warn() {}, debug() {}, error() {} }),
|
|
62
|
+
systemPrompt: {
|
|
63
|
+
section(spec) {
|
|
64
|
+
sections.push(spec);
|
|
65
|
+
return () => {};
|
|
66
|
+
},
|
|
67
|
+
getSectionOrder: () => 100,
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
return {
|
|
71
|
+
ctx,
|
|
72
|
+
sections,
|
|
73
|
+
fire(name, ...args) {
|
|
74
|
+
for (const handler of [...(listeners.get(name) ?? [])]) handler(...args);
|
|
75
|
+
},
|
|
76
|
+
handlersOf: (name) => [...(listeners.get(name) ?? [])],
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Run the real host-shaped activation probe.
|
|
82
|
+
*
|
|
83
|
+
* @param {{memoryRoot?:string, now?:()=>Date, killSwitch?:boolean, keep?:boolean, writeProfile?:boolean}} [options]
|
|
84
|
+
* @returns {object} {ok, schema, enabled, checks[], counters, probe, sectionText, files, memoryRoot}
|
|
85
|
+
*/
|
|
86
|
+
export function probeRoleActivation(options = {}) {
|
|
87
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date('2026-11-07T04:00:00.000Z');
|
|
88
|
+
const ownsRoot = typeof options.memoryRoot !== 'string' || options.memoryRoot.trim() === '';
|
|
89
|
+
const memoryRoot = ownsRoot
|
|
90
|
+
? fs.mkdtempSync(path.join(os.tmpdir(), 'longlive-role-activation-'))
|
|
91
|
+
: path.resolve(options.memoryRoot.trim());
|
|
92
|
+
const keep = options.keep === true || !ownsRoot;
|
|
93
|
+
const checks = [];
|
|
94
|
+
const push = (name, ok, detail = null) => checks.push({ name, ok: ok === true, detail });
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
fs.mkdirSync(memoryRoot, { recursive: true });
|
|
98
|
+
if (options.writeProfile !== false) {
|
|
99
|
+
fs.writeFileSync(
|
|
100
|
+
path.join(memoryRoot, 'profile.md'),
|
|
101
|
+
'我们之间要有人情味,话可以长,不许骗我;决定和铁律要记住,方法流程要保留。\n',
|
|
102
|
+
'utf8',
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
// 真实数据源:宿主写一条关系等级(walk 写路径,不是 mock)。
|
|
106
|
+
updateRelationship({
|
|
107
|
+
memoryRoot,
|
|
108
|
+
personId: 'user:jinhaiheng',
|
|
109
|
+
tier: 'trusted',
|
|
110
|
+
reason: '激活探针:宿主写入关系等级,用于验证运行期真实读取。',
|
|
111
|
+
expectedVersion: 0,
|
|
112
|
+
now,
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
const host = makeFakeHost();
|
|
116
|
+
const config = options.killSwitch === true ? { role: { enabled: false } } : {};
|
|
117
|
+
const kernel = registerRole(host.ctx, config, { memoryRoot, now });
|
|
118
|
+
push('enabled', kernel.enabled === true, kernel.reason ?? null);
|
|
119
|
+
|
|
120
|
+
if (kernel.enabled !== true) {
|
|
121
|
+
// kill switch 分支:必须零 hook、零 role 新增文件(关系图是探针预写的数据源,不计入)。
|
|
122
|
+
push('hooksRegistered', host.handlersOf('session/event').length === 0);
|
|
123
|
+
push('eventsSeen', true);
|
|
124
|
+
push('attentionIngested', true);
|
|
125
|
+
push('relationshipRead', true);
|
|
126
|
+
push('channelTouched', true);
|
|
127
|
+
push('personalityProjected', true);
|
|
128
|
+
push('attentionFilePresent', !fs.existsSync(path.join(memoryRoot, '.longlive', 'role', 'attention.jsonl')));
|
|
129
|
+
push('channelsFilePresent', !fs.existsSync(path.join(memoryRoot, '.longlive', 'role', 'channels.json')));
|
|
130
|
+
push('personalityFilePresent', !fs.existsSync(path.join(memoryRoot, '.longlive', 'role', 'personality.json')));
|
|
131
|
+
push('toneSectionInjected', host.sections.length === 0);
|
|
132
|
+
push('auditFilePresent', true);
|
|
133
|
+
return {
|
|
134
|
+
schema: ROLE_ACTIVATION_SCHEMA,
|
|
135
|
+
ok: false,
|
|
136
|
+
enabled: false,
|
|
137
|
+
killSwitch: true,
|
|
138
|
+
checks,
|
|
139
|
+
counters: null,
|
|
140
|
+
probe: null,
|
|
141
|
+
sectionText: '',
|
|
142
|
+
files: {},
|
|
143
|
+
memoryRoot,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// 真实 host 形态事件:two-arg (session, event),带宿主身份。
|
|
148
|
+
const session = {
|
|
149
|
+
id: 'sess-activation-1',
|
|
150
|
+
header: { id: 'sess-activation-1', userId: 'user:jinhaiheng', origin: 'main' },
|
|
151
|
+
};
|
|
152
|
+
host.fire('session/event', session, { type: 'user/message', data: { turn: 1 } });
|
|
153
|
+
host.fire('session/event', session, { type: 'tool/result', data: { turn: 1, name: 'pwsh', message: { isError: true } } });
|
|
154
|
+
host.fire('session/event', session, { type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } });
|
|
155
|
+
|
|
156
|
+
// 宿主真实取一次注入的 section 文本(执行 text(),不是只看注册表)。
|
|
157
|
+
const toneSection = host.sections.find((section) => section?.name === 'role:tone') ?? null;
|
|
158
|
+
const sectionText = toneSection && typeof toneSection.text === 'function' ? String(toneSection.text() ?? '') : '';
|
|
159
|
+
|
|
160
|
+
const probe = kernel.probe();
|
|
161
|
+
push('hooksRegistered', kernel.hooks.length > 0 && host.handlersOf('session/event').length === 1, kernel.hooks);
|
|
162
|
+
push('eventsSeen', probe.counters.eventsSeen >= 3, probe.counters.eventsSeen);
|
|
163
|
+
push('attentionIngested', probe.counters.attentionEnqueued >= 3, probe.counters.attentionEnqueued);
|
|
164
|
+
push('relationshipRead', probe.counters.relationshipLookups >= 1, probe.counters.lastRelationship);
|
|
165
|
+
push('channelTouched', probe.counters.channelTouches >= 1, probe.counters.channelTouches);
|
|
166
|
+
push('personalityProjected', probe.counters.personalityProjections >= 1, probe.counters.personalityProjections);
|
|
167
|
+
push('attentionFilePresent', probe.files.attention === true && probe.attention?.count > 0, probe.attention);
|
|
168
|
+
push('channelsFilePresent', probe.files.channels === true && probe.channels?.count > 0, probe.channels);
|
|
169
|
+
push('personalityFilePresent', probe.files.personality === true && probe.personality?.version >= 1, probe.personality);
|
|
170
|
+
push('toneSectionInjected', toneSection !== null && sectionText.trim() !== '', sectionText.slice(0, 80));
|
|
171
|
+
push('auditFilePresent', probe.files.audit === true);
|
|
172
|
+
|
|
173
|
+
const ok = checks.every((check) => check.ok === true);
|
|
174
|
+
return {
|
|
175
|
+
schema: ROLE_ACTIVATION_SCHEMA,
|
|
176
|
+
ok,
|
|
177
|
+
enabled: true,
|
|
178
|
+
killSwitch: false,
|
|
179
|
+
checks,
|
|
180
|
+
counters: probe.counters,
|
|
181
|
+
probe,
|
|
182
|
+
sectionText,
|
|
183
|
+
files: probe.files,
|
|
184
|
+
memoryRoot,
|
|
185
|
+
};
|
|
186
|
+
} finally {
|
|
187
|
+
if (!keep) {
|
|
188
|
+
try { fs.rmSync(memoryRoot, { recursive: true, force: true }); } catch { /* temp */ }
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
// src/role/attention.js — 角色内核 · attention queue(v2.8 §16.3 ①)
|
|
2
|
+
//
|
|
3
|
+
// 设计口径(§16.3):
|
|
4
|
+
// - 数据:`.longlive/role/attention.jsonl`,append-only,行
|
|
5
|
+
// `{id, priority:P0|P1|P2, kind:ops, subject, at, source}`;
|
|
6
|
+
// - pre-step 按 priority 决定事件注入顺序(P0 先);**不改变召回内容,只排序**;
|
|
7
|
+
// 与 recall 冲突时记忆事实优先(facts 由调用方排在最前,本模块只排 ops 项);
|
|
8
|
+
// - 接口:`attention → kind=ops 优先级`(导出 orderOpsItems / attentionPriorityOf)。
|
|
9
|
+
//
|
|
10
|
+
// 本文件补齐任务书要求的三件事:
|
|
11
|
+
// 1. 事件优先级权重:kind -> 基础 priority(ops/user→P1、tool/session→P2、error→P0),
|
|
12
|
+
// 显式 priority 优先;P0 抢占 = 排序时永远排在最前,与到达先后无关;
|
|
13
|
+
// 2. 队列容量:默认 50 行(`maxItems`),超出后压缩保留最新 50 行;
|
|
14
|
+
// 3. 老化:超过 `agingMs`(默认 30min)未消费的条目按 `demoteSteps` 降级
|
|
15
|
+
// (P0→P1→P2,最低 P2),排序时同优先级内老化项排在新鲜项之后。
|
|
16
|
+
//
|
|
17
|
+
// 纯本地、失败静默:写失败由调用方吞掉;读坏行只计数不抛。
|
|
18
|
+
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import crypto from 'node:crypto';
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
RoleError, ROLE_CODES, appendJsonl, ensureRoleDir, iso, nowMs, readJsonlSafe, rolePaths, writeJsonAtomic,
|
|
24
|
+
} from './store.js';
|
|
25
|
+
import { writeProtectedFile } from './writeprotect.js';
|
|
26
|
+
|
|
27
|
+
export const ATTENTION_SCHEMA = 'attention/v1';
|
|
28
|
+
export const ATTENTION_PRIORITIES = Object.freeze(['P0', 'P1', 'P2']);
|
|
29
|
+
export const ATTENTION_KINDS = Object.freeze(['ops', 'user', 'tool', 'session', 'error']);
|
|
30
|
+
/** 事件种类的基础优先级(显式 priority 覆盖它)。 */
|
|
31
|
+
export const KIND_BASE_PRIORITY = Object.freeze({
|
|
32
|
+
error: 'P0',
|
|
33
|
+
ops: 'P1',
|
|
34
|
+
user: 'P1',
|
|
35
|
+
tool: 'P2',
|
|
36
|
+
session: 'P2',
|
|
37
|
+
});
|
|
38
|
+
export const ATTENTION_DEFAULTS = Object.freeze({
|
|
39
|
+
maxItems: 50,
|
|
40
|
+
agingMs: 30 * 60 * 1000,
|
|
41
|
+
demoteSteps: 1,
|
|
42
|
+
injectMaxItems: 3,
|
|
43
|
+
});
|
|
44
|
+
const PRIORITY_INDEX = Object.freeze({ P0: 0, P1: 1, P2: 2 });
|
|
45
|
+
|
|
46
|
+
function clampInt(value, fallback, min, max) {
|
|
47
|
+
const number = Number(value);
|
|
48
|
+
if (!Number.isFinite(number)) return fallback;
|
|
49
|
+
return Math.min(max, Math.max(min, Math.floor(number)));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function normalizeAttentionConfig(input = {}) {
|
|
53
|
+
const cfg = input && typeof input === 'object' ? input : {};
|
|
54
|
+
return {
|
|
55
|
+
maxItems: clampInt(cfg.maxItems, ATTENTION_DEFAULTS.maxItems, 1, 500),
|
|
56
|
+
agingMs: clampInt(cfg.agingMs, ATTENTION_DEFAULTS.agingMs, 0, 7 * 24 * 60 * 60 * 1000),
|
|
57
|
+
demoteSteps: clampInt(cfg.demoteSteps, ATTENTION_DEFAULTS.demoteSteps, 0, 2),
|
|
58
|
+
injectMaxItems: clampInt(cfg.injectMaxItems, ATTENTION_DEFAULTS.injectMaxItems, 1, 20),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function isAttentionPriority(value) {
|
|
63
|
+
return ATTENTION_PRIORITIES.includes(value);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Priority for one event kind; unknown kinds fall back to P2 (never crash). */
|
|
67
|
+
export function attentionPriorityOfKind(kind) {
|
|
68
|
+
return KIND_BASE_PRIORITY[String(kind ?? '')] ?? 'P2';
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function newAttentionId(nowMsValue = Date.now()) {
|
|
72
|
+
return `att_${nowMsValue.toString(36)}_${crypto.randomBytes(4).toString('hex')}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Validate/normalize one stored row; returns null when it cannot be trusted. */
|
|
76
|
+
export function normalizeAttentionRow(raw) {
|
|
77
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
78
|
+
const id = typeof raw.id === 'string' && raw.id.trim() !== '' ? raw.id.trim() : null;
|
|
79
|
+
if (id === null) return null;
|
|
80
|
+
const priority = isAttentionPriority(raw.priority) ? raw.priority : null;
|
|
81
|
+
if (priority === null) return null;
|
|
82
|
+
const subject = typeof raw.subject === 'string' ? raw.subject : '';
|
|
83
|
+
const at = typeof raw.at === 'string' && Number.isFinite(Date.parse(raw.at)) ? raw.at : null;
|
|
84
|
+
if (at === null) return null;
|
|
85
|
+
return {
|
|
86
|
+
id,
|
|
87
|
+
priority,
|
|
88
|
+
kind: typeof raw.kind === 'string' && raw.kind !== '' ? raw.kind : 'ops',
|
|
89
|
+
subject,
|
|
90
|
+
at,
|
|
91
|
+
source: typeof raw.source === 'string' ? raw.source : 'role.attention',
|
|
92
|
+
seq: Number.isInteger(raw.seq) && raw.seq >= 0 ? raw.seq : 0,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Pure aging/demotion of one row; never mutates the stored row. */
|
|
97
|
+
export function ageAttentionRow(row, { now = Date.now(), agingMs = ATTENTION_DEFAULTS.agingMs, demoteSteps = ATTENTION_DEFAULTS.demoteSteps } = {}) {
|
|
98
|
+
const atMs = Date.parse(row.at);
|
|
99
|
+
const ageMs = Number.isFinite(atMs) ? Math.max(0, nowMs(now) - atMs) : 0;
|
|
100
|
+
const aged = agingMs > 0 && ageMs > agingMs;
|
|
101
|
+
const seed = PRIORITY_INDEX[row.priority] ?? PRIORITY_INDEX.P2;
|
|
102
|
+
const index = aged ? Math.min(PRIORITY_INDEX.P2, seed + demoteSteps) : seed;
|
|
103
|
+
return {
|
|
104
|
+
...row,
|
|
105
|
+
ageMs,
|
|
106
|
+
aged,
|
|
107
|
+
effectivePriority: ATTENTION_PRIORITIES[index],
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Stable injection order: effective priority first (P0 preempts), then fresh
|
|
113
|
+
* before aged, then arrival order (`at` asc, `seq` asc). Pure: no IO.
|
|
114
|
+
*/
|
|
115
|
+
export function orderAttentionRows(rows, options = {}) {
|
|
116
|
+
const cfg = normalizeAttentionConfig(options.config ?? options);
|
|
117
|
+
const now = options.now ?? Date.now();
|
|
118
|
+
const decorated = (Array.isArray(rows) ? rows : [])
|
|
119
|
+
.map((row) => normalizeAttentionRow(row))
|
|
120
|
+
.filter(Boolean)
|
|
121
|
+
.map((row) => ageAttentionRow(row, { now, agingMs: cfg.agingMs, demoteSteps: cfg.demoteSteps }));
|
|
122
|
+
decorated.sort((left, right) => {
|
|
123
|
+
const byPriority = (PRIORITY_INDEX[left.effectivePriority] ?? 2) - (PRIORITY_INDEX[right.effectivePriority] ?? 2);
|
|
124
|
+
if (byPriority !== 0) return byPriority;
|
|
125
|
+
if (left.aged !== right.aged) return left.aged ? 1 : -1;
|
|
126
|
+
const byAt = String(left.at).localeCompare(String(right.at));
|
|
127
|
+
if (byAt !== 0) return byAt;
|
|
128
|
+
return (left.seq ?? 0) - (right.seq ?? 0) || left.id.localeCompare(right.id);
|
|
129
|
+
});
|
|
130
|
+
return decorated;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The `attention → kind=ops` interface (pure): reorder ops items by their
|
|
135
|
+
* attention priority. Facts are NOT handled here — the caller keeps memory
|
|
136
|
+
* facts ahead of ops items (与 recall 冲突时记忆事实优先).
|
|
137
|
+
* @param {Array<object>} opsItems items with `subject`/`id` matching attention rows
|
|
138
|
+
* @param {Array<object>} attentionRows rows from the queue
|
|
139
|
+
*/
|
|
140
|
+
export function orderOpsItems(opsItems, attentionRows, options = {}) {
|
|
141
|
+
const items = Array.isArray(opsItems) ? opsItems : [];
|
|
142
|
+
const orderedRows = orderAttentionRows(attentionRows, options);
|
|
143
|
+
const priorityBySubject = new Map();
|
|
144
|
+
for (const row of orderedRows) {
|
|
145
|
+
const key = row.subject !== '' ? row.subject : row.id;
|
|
146
|
+
if (!priorityBySubject.has(key)) priorityBySubject.set(key, row.effectivePriority);
|
|
147
|
+
}
|
|
148
|
+
const decorated = items.map((item, index) => {
|
|
149
|
+
const key = typeof item?.subject === 'string' && item.subject !== ''
|
|
150
|
+
? item.subject
|
|
151
|
+
: (typeof item?.id === 'string' ? item.id : '');
|
|
152
|
+
const explicit = isAttentionPriority(item?.attentionPriority) ? item.attentionPriority : null;
|
|
153
|
+
const priority = explicit ?? priorityBySubject.get(key) ?? 'P2';
|
|
154
|
+
return { item, index, priority, priorityIndex: PRIORITY_INDEX[priority] ?? 2 };
|
|
155
|
+
});
|
|
156
|
+
decorated.sort((left, right) => left.priorityIndex - right.priorityIndex || left.index - right.index);
|
|
157
|
+
return {
|
|
158
|
+
items: decorated.map((entry) => entry.item),
|
|
159
|
+
priorities: decorated.map((entry) => entry.priority),
|
|
160
|
+
unmatched: decorated.filter((entry) => !priorityBySubject.has(
|
|
161
|
+
typeof entry.item?.subject === 'string' && entry.item.subject !== ''
|
|
162
|
+
? entry.item.subject
|
|
163
|
+
: (typeof entry.item?.id === 'string' ? entry.item.id : ''),
|
|
164
|
+
)).length,
|
|
165
|
+
source: 'attention',
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Append-only attention queue. Writing is best effort at the call site; the
|
|
171
|
+
* queue itself validates arguments and throws RoleError on bad input (the
|
|
172
|
+
* feature wiring swallows that, tests assert it).
|
|
173
|
+
*/
|
|
174
|
+
export function createAttentionQueue({ memoryRoot, now = () => new Date(), config = {}, auditKey = null, actorKind = 'host' } = {}) {
|
|
175
|
+
const cfg = normalizeAttentionConfig(config);
|
|
176
|
+
const root = memoryRoot;
|
|
177
|
+
const paths = rolePaths(root);
|
|
178
|
+
|
|
179
|
+
function readRows({ limit = 10_000 } = {}) {
|
|
180
|
+
const read = readJsonlSafe(paths.attention, { limit, memoryRoot: root, auditKey });
|
|
181
|
+
if (read.tampered === true) {
|
|
182
|
+
return { present: true, rows: [], bad: 0, total: 0, tampered: true, code: read.code ?? ROLE_CODES.TAMPER };
|
|
183
|
+
}
|
|
184
|
+
const rows = [];
|
|
185
|
+
for (const raw of read.rows) {
|
|
186
|
+
const row = normalizeAttentionRow(raw);
|
|
187
|
+
if (row) rows.push(row);
|
|
188
|
+
}
|
|
189
|
+
return { present: read.present, rows, bad: read.bad, total: read.total ?? rows.length, tampered: false };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function nextSeq(rows) {
|
|
193
|
+
let max = 0;
|
|
194
|
+
for (const row of rows) if (Number.isInteger(row.seq) && row.seq > max) max = row.seq;
|
|
195
|
+
return max + 1;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function compact(rows) {
|
|
199
|
+
if (rows.length <= cfg.maxItems) return { compacted: false, kept: rows.length };
|
|
200
|
+
const keptRows = orderAttentionRows(rows, { now: now(), config: cfg })
|
|
201
|
+
.sort((left, right) => (left.seq ?? 0) - (right.seq ?? 0))
|
|
202
|
+
.slice(-cfg.maxItems);
|
|
203
|
+
const text = `${keptRows.map((row) => JSON.stringify({
|
|
204
|
+
id: row.id,
|
|
205
|
+
priority: row.priority,
|
|
206
|
+
kind: row.kind,
|
|
207
|
+
subject: row.subject,
|
|
208
|
+
at: row.at,
|
|
209
|
+
source: row.source,
|
|
210
|
+
seq: row.seq,
|
|
211
|
+
})).join('\n')}\n`;
|
|
212
|
+
writeProtectedFile({ memoryRoot: root, file: paths.attention, text, auditKey, actorKind });
|
|
213
|
+
return { compacted: true, kept: keptRows.length };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Record one event. `priority` wins over the kind table; `kind` defaults to
|
|
218
|
+
* 'ops' (the v2.8 row schema names kind=ops explicitly).
|
|
219
|
+
*/
|
|
220
|
+
function enqueue({
|
|
221
|
+
priority = undefined,
|
|
222
|
+
kind = 'ops',
|
|
223
|
+
subject = '',
|
|
224
|
+
source = 'role.attention',
|
|
225
|
+
at = undefined,
|
|
226
|
+
} = {}) {
|
|
227
|
+
const resolvedKind = ATTENTION_KINDS.includes(String(kind)) ? String(kind) : 'ops';
|
|
228
|
+
const resolvedPriority = priority === undefined ? attentionPriorityOfKind(resolvedKind) : priority;
|
|
229
|
+
if (!isAttentionPriority(resolvedPriority)) {
|
|
230
|
+
throw new RoleError(ROLE_CODES.PARAMS, `attention priority 非法:${JSON.stringify(priority)}(允许 ${ATTENTION_PRIORITIES.join('|')})`);
|
|
231
|
+
}
|
|
232
|
+
if (typeof subject === 'string' && Array.from(subject).length > 200) {
|
|
233
|
+
throw new RoleError(ROLE_CODES.PARAMS, 'attention subject 超过 200 字符');
|
|
234
|
+
}
|
|
235
|
+
const atMs = at === undefined
|
|
236
|
+
? nowMs(now())
|
|
237
|
+
: (at instanceof Date ? at.getTime() : (typeof at === 'number' ? at : Date.parse(String(at))));
|
|
238
|
+
if (!Number.isFinite(atMs)) throw new RoleError(ROLE_CODES.PARAMS, 'attention.at 不是可解析的时间');
|
|
239
|
+
ensureRoleDir(root);
|
|
240
|
+
const existing = readRows();
|
|
241
|
+
const row = {
|
|
242
|
+
id: newAttentionId(atMs),
|
|
243
|
+
priority: resolvedPriority,
|
|
244
|
+
kind: resolvedKind,
|
|
245
|
+
subject: typeof subject === 'string' ? subject : '',
|
|
246
|
+
at: iso(atMs),
|
|
247
|
+
source: typeof source === 'string' && source !== '' ? source : 'role.attention',
|
|
248
|
+
seq: nextSeq(existing.rows),
|
|
249
|
+
};
|
|
250
|
+
appendJsonl(paths.attention, row, { memoryRoot: root, auditKey, actorKind });
|
|
251
|
+
const total = existing.rows.length + 1;
|
|
252
|
+
const compaction = total > cfg.maxItems ? compact([...existing.rows, row]) : { compacted: false, kept: total };
|
|
253
|
+
return { ok: true, row, seq: row.seq, compaction };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Rows in injection order (aged items demoted, P0 first). */
|
|
257
|
+
function pending({ limit = cfg.maxItems, now: nowValue = undefined } = {}) {
|
|
258
|
+
const read = readRows();
|
|
259
|
+
const ordered = orderAttentionRows(read.rows, { now: nowValue ?? now(), config: cfg });
|
|
260
|
+
return {
|
|
261
|
+
ok: read.tampered !== true,
|
|
262
|
+
items: ordered.slice(0, limit),
|
|
263
|
+
total: read.rows.length,
|
|
264
|
+
bad: read.bad,
|
|
265
|
+
present: read.present,
|
|
266
|
+
tampered: read.tampered === true,
|
|
267
|
+
code: read.tampered === true ? (read.code ?? ROLE_CODES.TAMPER) : null,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Read-only panel/route view (`attention/v1`). */
|
|
272
|
+
function view({ limit = cfg.maxItems, now: nowValue = undefined } = {}) {
|
|
273
|
+
const pendingItems = pending({ limit, now: nowValue });
|
|
274
|
+
return {
|
|
275
|
+
schema: ATTENTION_SCHEMA,
|
|
276
|
+
present: pendingItems.present,
|
|
277
|
+
count: pendingItems.items.length,
|
|
278
|
+
total: pendingItems.total,
|
|
279
|
+
bad: pendingItems.bad,
|
|
280
|
+
tampered: pendingItems.tampered === true,
|
|
281
|
+
degraded: pendingItems.tampered === true || pendingItems.bad > 0 || pendingItems.present === false,
|
|
282
|
+
items: pendingItems.items.map((row) => ({
|
|
283
|
+
id: row.id,
|
|
284
|
+
priority: row.priority,
|
|
285
|
+
kind: row.kind,
|
|
286
|
+
subject: row.subject,
|
|
287
|
+
at: row.at,
|
|
288
|
+
source: row.source,
|
|
289
|
+
effectivePriority: row.effectivePriority,
|
|
290
|
+
aged: row.aged,
|
|
291
|
+
})),
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Highest effective priority matching a subject (null when unknown). */
|
|
296
|
+
function priorityFor(subject, { now: nowValue = undefined } = {}) {
|
|
297
|
+
const pendingItems = pending({ limit: cfg.maxItems, now: nowValue });
|
|
298
|
+
for (const row of pendingItems.items) if (row.subject === String(subject ?? '')) return row.effectivePriority;
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** The ops ordering interface bound to this queue (pure result). */
|
|
303
|
+
function orderOps(items, options = {}) {
|
|
304
|
+
const read = readRows();
|
|
305
|
+
return orderOpsItems(items, read.rows, { now: options.now ?? now(), config: cfg });
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
return {
|
|
309
|
+
enqueue,
|
|
310
|
+
pending,
|
|
311
|
+
view,
|
|
312
|
+
priorityFor,
|
|
313
|
+
orderOps,
|
|
314
|
+
config: cfg,
|
|
315
|
+
paths,
|
|
316
|
+
read: readRows,
|
|
317
|
+
};
|
|
318
|
+
}
|
package/src/role/base.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// src/role/base.js — 角色内核基础类型(避免 store <-> writeprotect 循环依赖)
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
|
|
4
|
+
/** 角色层错误码(写路径抛 RoleError,读路径降级不抛)。 */
|
|
5
|
+
export const ROLE_CODES = Object.freeze({
|
|
6
|
+
PARAMS: 'E_ROLE_PARAMS',
|
|
7
|
+
DISABLED: 'E_ROLE_DISABLED',
|
|
8
|
+
CAS_CONFLICT: 'E_ROLE_CAS_CONFLICT',
|
|
9
|
+
CORRUPT: 'E_ROLE_CORRUPT',
|
|
10
|
+
PATH_OUTSIDE_ROOT: 'E_PROFILE_OUTSIDE_ROOT',
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
export class RoleError extends Error {
|
|
14
|
+
constructor(code, message, details = undefined) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = 'RoleError';
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.status = code === ROLE_CODES.CAS_CONFLICT ? 409 : 422;
|
|
19
|
+
if (details !== undefined) this.details = details;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function nowMs(now) {
|
|
24
|
+
const value = typeof now === 'function' ? now() : now;
|
|
25
|
+
if (value instanceof Date) return value.getTime();
|
|
26
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
|
27
|
+
return Date.now();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function iso(ms) {
|
|
31
|
+
return new Date(ms).toISOString();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function sha256Hex(text) {
|
|
35
|
+
return crypto.createHash('sha256').update(String(text ?? ''), 'utf8').digest('hex');
|
|
36
|
+
}
|