@jjh32456/dsh-longlive 1.6.7 → 1.8.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 +70 -1508
- package/LICENSE +1 -1
- package/QUICKSTART.md +34 -13
- package/README.en.md +18 -7
- package/README.md +34 -9
- package/SPEC.md +5 -5
- package/cordis.patch.yml +23 -9
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +4 -3
- package/docs/AUTO-RECALL-WIRING.md +1 -1
- package/docs/AUTO-RECALL.md +15 -9
- package/docs/CONFIG.md +168 -35
- package/docs/ERRORS.md +17 -5
- package/docs/FAQ.md +7 -7
- package/docs/FEATURES.md +96 -28
- package/docs/MIGRATION-1.6.0.md +2 -2
- package/docs/OPERATIONS.md +6 -6
- package/docs/PANEL-INTEGRATION.md +6 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +5 -5
- package/docs/README.en.md +4 -2
- package/docs/RESIDENT-WATCHER.md +1 -1
- package/docs/SESSION-WATCH.md +6 -6
- package/docs/TROUBLESHOOTING.md +4 -4
- package/package.json +47 -117
- package/runbook.md +2 -2
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/install-surgery-task.ps1 +5 -2
- package/scripts/lib/session-watch-fixture.mjs +1 -1
- package/scripts/longlive-doctor.mjs +6 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/session-watch-drill.mjs +1 -1
- package/scripts/surgery-run.cmd +1 -1
- package/scripts/unattended-surgery.ps1 +5 -2
- package/scripts/verify-card-anchors.mjs +138 -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 +760 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +644 -0
- package/src/activity/thinking.js +176 -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 +235 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +193 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1067 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate.js +1 -1
- package/src/config.js +171 -47
- package/src/deps.js +6 -4
- package/src/features.js +182 -6
- package/src/heartbeat.js +156 -23
- package/src/identity/handover.js +52 -1
- package/src/identity/index.js +13 -5
- package/src/identity/inject-position.js +2 -2
- package/src/index.js +97 -7
- package/src/lifecycle/gap-clocks.js +328 -0
- package/src/lifecycle/index.js +269 -0
- package/src/live.js +22 -2
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +401 -0
- package/src/memory/capture.js +442 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/conflicts.js +106 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +471 -0
- package/src/memory/event-index.js +917 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +145 -0
- package/src/memory/filter-runner.js +1 -1
- package/src/memory/filter.js +5 -1
- package/src/memory/forget-v2.js +410 -0
- package/src/memory/forget.js +71 -0
- package/src/memory/frames-activation.js +247 -0
- package/src/memory/fts-query.js +174 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index.js +1 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/recall-v2.js +223 -0
- package/src/memory/recall.js +65 -2
- package/src/memory/records.js +425 -0
- package/src/memory/retention.js +128 -0
- package/src/memory/review.js +124 -0
- package/src/memory/trust.js +88 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +516 -0
- package/src/metrics/classify.mjs +5 -3
- package/src/metrics/index.mjs +21 -1
- package/src/metrics/prestep-latency.mjs +300 -0
- package/src/metrics/store.mjs +25 -0
- package/src/policy-profile.js +18 -3
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/cards.mjs +7 -0
- package/src/recall/embedding.mjs +8 -8
- package/src/recall/entities.mjs +112 -0
- package/src/recall/index.js +235 -19
- package/src/recall/inject-order.mjs +10 -8
- package/src/recall/privacy.mjs +105 -16
- package/src/recall/recall-core.mjs +116 -10
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -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 +176 -25
- package/src/router/background/agent-runner.mjs +1 -1
- package/src/router/background/anchor.mjs +1 -1
- package/src/router/background/audit.mjs +2 -2
- package/src/router/background/budget-ledger.mjs +2 -2
- package/src/router/background/host-sim.mjs +1 -1
- package/src/router/background/memory.mjs +4 -4
- package/src/router/background/queue.mjs +1 -1
- package/src/router/background/retry.mjs +1 -1
- package/src/router/background/router.mjs +1 -1
- package/src/router/background/stream.mjs +1 -1
- package/src/router/background/tool-policy.mjs +1 -1
- package/src/router/design-headings.json +5 -5
- package/src/router/face/config.mjs +1 -1
- package/src/router/face/identity.mjs +3 -3
- package/src/router/judge.mjs +8 -7
- package/src/router/policies/generic.json +21 -4
- package/src/router/route.js +109 -22
- package/src/router/router.mjs +10 -6
- package/src/router/routing-rules.json +260 -445
- package/src/router/run-sim.mjs +8 -8
- package/src/router/runtime.js +23 -12
- package/src/router/service/board.mjs +95 -15
- package/src/router/service/config.mjs +5 -5
- package/src/router/service/context.mjs +1 -1
- package/src/router/service/hint.mjs +14 -0
- package/src/router/service/queue.mjs +1 -1
- package/src/router/service/service.mjs +27 -11
- package/src/router/shadow.mjs +4 -3
- package/src/surgery-recovery.js +2 -2
- package/src/tool-output.js +2 -2
- package/src/tools.js +39 -7
- package/src/truncate-visible.js +2 -2
- package/src/ui/actions.js +1312 -0
- package/src/ui/panel-api.js +367 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +695 -0
- package/src/ui/routes.js +3 -0
- package/docs/DEV.md +0 -279
- package/docs/PRESENCE-BUS-WIRING.md +0 -491
- package/docs/PRESENCE-BUS.md +0 -694
- package/docs/SURGERY.md +0 -186
- package/scripts/mark-core-cards.mjs +0 -289
- package/scripts/pack.mjs +0 -392
- package/scripts/router-proposals.mjs +0 -386
- package/src/router/fixtures/M1.json +0 -16
- package/src/router/fixtures/M2.json +0 -16
- package/src/router/fixtures/M3.json +0 -20
- package/src/router/fixtures/M4.json +0 -20
- package/src/router/fixtures/M5.json +0 -45
- package/src/router/fixtures/M6.json +0 -53
- package/src/router/fixtures/M7.json +0 -46
- package/src/router/fixtures/S1.json +0 -20
- package/src/router/fixtures/S2.json +0 -23
- package/src/router/fixtures/S3.json +0 -20
- package/src/router/fixtures/S4.json +0 -34
- package/src/router/fixtures/S5.json +0 -43
- package/src/router/fixtures/S6.json +0 -47
- package/src/router/fixtures/T1.json +0 -23
- package/src/router/fixtures/T2.json +0 -16
- package/src/router/fixtures/T3.json +0 -19
- package/src/router/fixtures/T4.json +0 -16
- package/src/router/fixtures/X1.json +0 -17
- package/src/router/fixtures/X2.json +0 -20
- package/src/router/gen-design-headings.mjs +0 -107
- package/src/router/policies/owner-rulings-2026-11-03.json +0 -62
- package/test/auto-recall.test.mjs +0 -474
- package/test/auto-truncate.test.mjs +0 -931
- package/test/autobind.test.mjs +0 -385
- package/test/bus.test.mjs +0 -1572
- package/test/cli-guard.test.mjs +0 -198
- package/test/conclusion.test.mjs +0 -408
- package/test/config-schema.test.mjs +0 -204
- package/test/d6-output.test.mjs +0 -194
- package/test/d6.test.mjs +0 -395
- package/test/deps.test.mjs +0 -342
- package/test/doctor-setup.test.mjs +0 -297
- package/test/embedding-recall.test.mjs +0 -347
- package/test/feature-flags.test.mjs +0 -568
- package/test/filter-shadow.test.mjs +0 -170
- package/test/fixtures/baseline-0.8.0-registration.json +0 -556
- package/test/fixtures/d6-header-tools.json +0 -1
- package/test/fixtures/lock-child.mjs +0 -67
- package/test/fixtures/pre-step-container.mjs +0 -100
- package/test/fixtures/privacy-memory/topics/pii-unmarked.md +0 -9
- package/test/fixtures/privacy-memory/topics/secret-local-only.md +0 -11
- package/test/fixtures/profile-session-longlive-config.json +0 -20
- package/test/fixtures/proposal-cas-child.mjs +0 -66
- package/test/host-engine-status.test.mjs +0 -307
- package/test/hot-truncate.test.mjs +0 -1349
- package/test/identity-card-marker.test.mjs +0 -307
- package/test/identity-router/run.mjs +0 -721
- package/test/integration-pre-step.test.mjs +0 -553
- package/test/live.test.mjs +0 -1020
- package/test/maintenance-schedule.test.mjs +0 -538
- package/test/memory.test.mjs +0 -2828
- package/test/metrics.test.mjs +0 -478
- package/test/orchestrator.test.mjs +0 -266
- package/test/p1_probe.mjs +0 -97
- package/test/packaging.test.mjs +0 -182
- package/test/portability.test.mjs +0 -343
- package/test/rc4-regressions.test.mjs +0 -562
- package/test/rc5-regressions.test.mjs +0 -197
- package/test/rc6-chinese.test.mjs +0 -394
- package/test/router-1100/apply-off.test.mjs +0 -175
- package/test/router-1100/budget-reconcile.test.mjs +0 -215
- package/test/router-1100/config-context.test.mjs +0 -211
- package/test/router-1100/helpers.mjs +0 -129
- package/test/router-1100/hint-envelope.test.mjs +0 -150
- package/test/router-1100/lock-crossproc.test.mjs +0 -206
- package/test/router-1100/proposal-cas-crossproc.test.mjs +0 -184
- package/test/router-1100/router-apply.test.mjs +0 -372
- package/test/router-1100/router-fixb.test.mjs +0 -602
- package/test/router-1100/router-proposals.test.mjs +0 -405
- package/test/router-1100/router-queue-lease-wal.test.mjs +0 -355
- package/test/router-1100/router-security-cr.test.mjs +0 -333
- package/test/router-1100/service-lifecycle.test.mjs +0 -220
- package/test/router-1100/tools-contract.test.mjs +0 -164
- package/test/router-1100/turn-reflect-tick.test.mjs +0 -89
- package/test/router-1100/v6-contract.test.mjs +0 -158
- package/test/router-1100/v6b-contract.test.mjs +0 -293
- package/test/router-1100/v6c-contract.test.mjs +0 -249
- package/test/router-1100/wal-rotation.test.mjs +0 -375
- package/test/router-1100/wp1-config.test.mjs +0 -170
- package/test/router-1100/wp1-default-off.test.mjs +0 -77
- package/test/router-1100/wp1-model-status.test.mjs +0 -90
- package/test/router-1100/wp1-status.test.mjs +0 -220
- package/test/router-1100/wp1-tools.test.mjs +0 -146
- package/test/router-1100/wp5-cli.test.mjs +0 -240
- package/test/router-1100/wp5-model-auto.test.mjs +0 -418
- package/test/router-1100/wp6-merge.test.mjs +0 -386
- package/test/router-1100/wp6-wake.test.mjs +0 -502
- package/test/router-background/audit.test.mjs +0 -37
- package/test/router-background/budget-ledger.test.mjs +0 -330
- package/test/router-background/cross-process.test.mjs +0 -222
- package/test/router-background/fixtures/cross-child.mjs +0 -85
- package/test/router-background/fixtures/real-shapes.mjs +0 -239
- package/test/router-background/router.test.mjs +0 -1044
- package/test/router-background/stream-retry.test.mjs +0 -358
- package/test/router-background/tool-agent.test.mjs +0 -384
- package/test/router-face/bridge.test.mjs +0 -169
- package/test/router-face/face.test.mjs +0 -316
- package/test/router-failclosed.test.mjs +0 -466
- package/test/router-identity.test.mjs +0 -384
- package/test/router-l1-l2.contract.test.mjs +0 -1075
- package/test/router-memory-tools.test.mjs +0 -262
- package/test/router-policy.test.mjs +0 -225
- package/test/router-runtime.test.mjs +0 -438
- package/test/router-shadow.test.mjs +0 -287
- package/test/router.test.mjs +0 -903
- package/test/run-rc.mjs +0 -299
- package/test/run.mjs +0 -2469
- package/test/safety-defaults.test.mjs +0 -179
- package/test/seeded-load.test.mjs +0 -436
- package/test/session-original.test.mjs +0 -338
- package/test/surgery-recovery.test.mjs +0 -936
- package/test/t7_drive.mjs +0 -151
- package/test/tool-output.test.mjs +0 -393
- package/test/tool-schema.test.mjs +0 -177
- package/test/tools_contract.test.mjs +0 -716
- package/test/truncate-visible.test.mjs +0 -1150
- package/test/ui-flags.test.mjs +0 -477
- package/test/v4-hardening.test.mjs +0 -427
package/src/features.js
CHANGED
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
// identityCard.enabled -> agent/pre-step (open card, prepend:true)
|
|
10
10
|
// autoRecall.enabled -> agent/pre-step (recall, prepend:false) + session/event
|
|
11
11
|
// presenceBus.enabled -> session/event (drain this session's bus inbox)
|
|
12
|
+
// sharedBrain.activity.enabled -> session/event (write this turn's activity)
|
|
13
|
+
// + agent/pre-step (inject other sessions' new rows)
|
|
12
14
|
// autoMaintenance.enabled -> one unref'd timer to the next local midnight
|
|
13
15
|
// (consolidate report + forget dry-run pending list;
|
|
14
16
|
// no turn hook, so a failure cannot affect a turn)
|
|
@@ -37,9 +39,18 @@ import {
|
|
|
37
39
|
placeAfterFirstHuman,
|
|
38
40
|
sameMessageOrder,
|
|
39
41
|
} from './identity/inject-position.js';
|
|
42
|
+
import {
|
|
43
|
+
composePreStepBlocks,
|
|
44
|
+
createWorkingFrameStore,
|
|
45
|
+
insertWorkingMessage,
|
|
46
|
+
updateFrameFromMessages,
|
|
47
|
+
} from './memory/working-frame.js';
|
|
40
48
|
import { apply as applyAutoRecall } from './recall/index.js';
|
|
49
|
+
import { startPrestepPhase } from './metrics/prestep-latency.mjs';
|
|
41
50
|
import { createBus, normalizeSessionId, shouldAckOnTurnEnd } from './bus/bus.mjs';
|
|
42
51
|
import { createMaintenanceScheduler } from './memory/maintenance.js';
|
|
52
|
+
import { normalizeActivityConfig, registerActivityStream } from './activity/index.js';
|
|
53
|
+
import { registerRole } from './role/index.js';
|
|
43
54
|
import {
|
|
44
55
|
claimFallbackInjection,
|
|
45
56
|
markReceiptFallbackInjected,
|
|
@@ -49,11 +60,15 @@ import {
|
|
|
49
60
|
} from './surgery-recovery.js';
|
|
50
61
|
|
|
51
62
|
export const FEATURE_DEFAULTS = Object.freeze({
|
|
52
|
-
autoRecall: Object.freeze({ enabled:
|
|
53
|
-
identityCard: Object.freeze({ enabled:
|
|
54
|
-
presenceBus: Object.freeze({ enabled:
|
|
63
|
+
autoRecall: Object.freeze({ enabled: true, topK: 3, budgetTokens: 2000, everyNTurns: 6 }),
|
|
64
|
+
identityCard: Object.freeze({ enabled: true, path: '<memoryRoot>/STATE.md', maxChars: 800 }),
|
|
65
|
+
presenceBus: Object.freeze({ enabled: true, pollMs: 3000 }),
|
|
66
|
+
sharedBrain: Object.freeze({
|
|
67
|
+
activity: Object.freeze({ enabled: true, injectMaxChars: 300, maxItems: 5 }),
|
|
68
|
+
thinkingInjection: true,
|
|
69
|
+
}),
|
|
55
70
|
autoMaintenance: Object.freeze({
|
|
56
|
-
enabled:
|
|
71
|
+
enabled: true,
|
|
57
72
|
consolidate: true,
|
|
58
73
|
forget: true,
|
|
59
74
|
runOnStart: true,
|
|
@@ -68,7 +83,7 @@ function clampInt(value, fallback, min, max) {
|
|
|
68
83
|
}
|
|
69
84
|
|
|
70
85
|
function bool(value) {
|
|
71
|
-
return value
|
|
86
|
+
return value !== false;
|
|
72
87
|
}
|
|
73
88
|
|
|
74
89
|
function text(value) {
|
|
@@ -81,6 +96,8 @@ export function normalizeFeatureConfig(config = {}) {
|
|
|
81
96
|
const auto = value.autoRecall && typeof value.autoRecall === 'object' ? value.autoRecall : {};
|
|
82
97
|
const identity = value.identityCard && typeof value.identityCard === 'object' ? value.identityCard : {};
|
|
83
98
|
const bus = value.presenceBus && typeof value.presenceBus === 'object' ? value.presenceBus : {};
|
|
99
|
+
const sharedBrain = value.sharedBrain && typeof value.sharedBrain === 'object' ? value.sharedBrain : {};
|
|
100
|
+
const activity = sharedBrain.activity && typeof sharedBrain.activity === 'object' ? sharedBrain.activity : {};
|
|
84
101
|
const maintenance = value.autoMaintenance && typeof value.autoMaintenance === 'object'
|
|
85
102
|
? value.autoMaintenance
|
|
86
103
|
: {};
|
|
@@ -105,6 +122,10 @@ export function normalizeFeatureConfig(config = {}) {
|
|
|
105
122
|
pollMs: clampInt(bus.pollMs, FEATURE_DEFAULTS.presenceBus.pollMs, 0, 3600000),
|
|
106
123
|
root: text(bus.root),
|
|
107
124
|
},
|
|
125
|
+
sharedBrain: {
|
|
126
|
+
activity: normalizeActivityConfig(activity),
|
|
127
|
+
thinkingInjection: bool(sharedBrain.thinkingInjection),
|
|
128
|
+
},
|
|
108
129
|
autoMaintenance: {
|
|
109
130
|
enabled: bool(maintenance.enabled),
|
|
110
131
|
consolidate: maintenance.consolidate !== false,
|
|
@@ -129,7 +150,7 @@ export function resolveCardPath(rawPath, memoryRoot) {
|
|
|
129
150
|
? path.resolve(raw.replaceAll('<memoryRoot>', root))
|
|
130
151
|
: path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(root ?? process.cwd(), raw);
|
|
131
152
|
if (!root) return resolved;
|
|
132
|
-
//
|
|
153
|
+
// 评审 M2:`../`、根外绝对路径、盘符跳转一律 E_PATH_OUTSIDE_ROOT。
|
|
133
154
|
// 只做词法判定、不读盘:越界路径在读任何文件之前就被拒绝。
|
|
134
155
|
if (!isInsideRoot(root, resolved)) {
|
|
135
156
|
throw memoryError(
|
|
@@ -522,6 +543,99 @@ function registerSurgeryReceipt(ctx, receipt, warn, { memoryRoot = null } = {})
|
|
|
522
543
|
* Register the opt-in features. Returns `{ enabled: string[] }` for tests and
|
|
523
544
|
* for a single startup log line; with every flag off it touches nothing.
|
|
524
545
|
*/
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* v2.6.4 §14.2 连续性:pre-step 注入未过期的 working-frame(≤300 字)。
|
|
549
|
+
* 注入顺序由 handler 注册顺序保证:[boot, shared, working, recall];本函数在
|
|
550
|
+
* autoRecall 之前注册(同一 append 语义),working 块因此出现在 recall 之前。
|
|
551
|
+
* 过期帧不注入(标 stale,不删);时钟回拨 fail closed 后静默跳过。
|
|
552
|
+
*/
|
|
553
|
+
function registerWorkingFrame(ctx, options = {}) {
|
|
554
|
+
const memoryRoot = options.memoryRoot ?? null;
|
|
555
|
+
const warn = typeof options.warn === 'function' ? options.warn : () => {};
|
|
556
|
+
if (!memoryRoot) return false;
|
|
557
|
+
let store = null;
|
|
558
|
+
try {
|
|
559
|
+
store = createWorkingFrameStore({
|
|
560
|
+
memoryRoot,
|
|
561
|
+
now: options.now,
|
|
562
|
+
monoNow: options.monoNow,
|
|
563
|
+
});
|
|
564
|
+
} catch (error) {
|
|
565
|
+
warn(`[working-frame] 初始化失败(${error?.code ?? error?.message ?? error}),跳过注入。`);
|
|
566
|
+
return false;
|
|
567
|
+
}
|
|
568
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
569
|
+
if (Number(payload?.step) !== 1) return next();
|
|
570
|
+
if (isSubagent(payload?.agent)) return next();
|
|
571
|
+
const decision = await next();
|
|
572
|
+
if (!decision || decision.kind === 'reject' || !Array.isArray(decision.messages)) return decision;
|
|
573
|
+
const sessionId = keyOf(payload.agent);
|
|
574
|
+
const turn = Number.isInteger(payload?.turn) ? payload.turn : 0;
|
|
575
|
+
// B3: working phase = frame lookup + injection + next-turn focus update (timing only).
|
|
576
|
+
const workPhase = startPrestepPhase(sessionId, turn, 'working');
|
|
577
|
+
try {
|
|
578
|
+
let block = null;
|
|
579
|
+
try {
|
|
580
|
+
block = store.frameForInjection({ sessionId });
|
|
581
|
+
} catch (error) {
|
|
582
|
+
warn(`[working-frame] 注入判定失败(${error?.code ?? error?.message ?? error})。`);
|
|
583
|
+
return decision;
|
|
584
|
+
}
|
|
585
|
+
let message = null;
|
|
586
|
+
if (block && block.inject === true && typeof block.text === 'string' && block.text.trim() !== '') {
|
|
587
|
+
try {
|
|
588
|
+
// 任务: composePreStepBlocks has a REAL production call point (order [boot, shared, working, recall]).
|
|
589
|
+
const composed = composePreStepBlocks([{ kind: 'working', text: block.text }]);
|
|
590
|
+
const workingText = composed[0]?.text ?? block.text;
|
|
591
|
+
message = assertInjectionSource({
|
|
592
|
+
id: `working-frame-${randomUUID()}`,
|
|
593
|
+
role: 'user',
|
|
594
|
+
content: [{ type: 'text', text: workingText }],
|
|
595
|
+
source: injectionSource(),
|
|
596
|
+
});
|
|
597
|
+
} catch (error) {
|
|
598
|
+
warn(`[working-frame] 注入消息被拒绝(${error?.code ?? error?.message ?? error})。`);
|
|
599
|
+
message = null;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
// EA-05: this turn's focus is recorded for the NEXT turn (real caller, always runs).
|
|
603
|
+
try {
|
|
604
|
+
updateFrameFromMessages({
|
|
605
|
+
store,
|
|
606
|
+
sessionId,
|
|
607
|
+
messages: Array.isArray(decision.messages) ? decision.messages : (payload?.messages ?? []),
|
|
608
|
+
turn,
|
|
609
|
+
});
|
|
610
|
+
} catch (error) {
|
|
611
|
+
warn(`[working-frame] 焦点更新失败(${error?.code ?? error?.message ?? error})。`);
|
|
612
|
+
}
|
|
613
|
+
// EA-04: real order [boot, shared, working, recall].
|
|
614
|
+
return message === null ? decision : { ...decision, messages: insertWorkingMessage(decision.messages, message) };
|
|
615
|
+
} finally {
|
|
616
|
+
try { workPhase.end(); } catch { /* timing only */ }
|
|
617
|
+
}
|
|
618
|
+
});
|
|
619
|
+
return true;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/** Pure activation switch resolver (任务 A1): default ON, explicit false / env = kill switch. */
|
|
623
|
+
export function resolveActivationSwitches(config = {}, options = {}, env = process.env) {
|
|
624
|
+
const killed = (name) => env?.[name] === '1' || env?.[name] === 'true';
|
|
625
|
+
// Release default is carried by the Config schema (memoryV2.enabled=true); this runtime
|
|
626
|
+
// gate honours the resolved config value so partial/legacy configs stay explicit-off.
|
|
627
|
+
const memoryV2Enabled = options.memoryV2Enabled !== false
|
|
628
|
+
&& config?.memoryV2?.enabled === true
|
|
629
|
+
&& !killed('DSH_LONGLIVE_DISABLE_MEMORY_V2');
|
|
630
|
+
const roleEnabled = options.roleEnabled !== false
|
|
631
|
+
&& config?.role?.enabled === true
|
|
632
|
+
&& !killed('DSH_LONGLIVE_DISABLE_ROLE');
|
|
633
|
+
const answerGuardEnabled = options.answerGuardEnabled !== false
|
|
634
|
+
&& config?.answerGuard?.enabled === true
|
|
635
|
+
&& !killed('DSH_LONGLIVE_DISABLE_ANSWER_GUARD');
|
|
636
|
+
return { memoryV2Enabled, roleEnabled, answerGuardEnabled };
|
|
637
|
+
}
|
|
638
|
+
|
|
525
639
|
export function registerFeatures(ctx, config = {}, options = {}) {
|
|
526
640
|
const cfg = normalizeFeatureConfig(config);
|
|
527
641
|
const memoryRoot = options.memoryRoot ?? null;
|
|
@@ -530,6 +644,15 @@ export function registerFeatures(ctx, config = {}, options = {}) {
|
|
|
530
644
|
if (logger) logger.warn(message);
|
|
531
645
|
};
|
|
532
646
|
const enabled = [];
|
|
647
|
+
const killSwitch = (name) => process.env[name] === '1' || process.env[name] === 'true';
|
|
648
|
+
// 任务 activation: default ON, independent kill switch per subsystem.
|
|
649
|
+
// Config schema (src/config.js) defaults memoryV2.enabled / role.enabled = true, so a real host
|
|
650
|
+
// config arrives with enabled:true. For role the wiring is default-ON even when a caller passes a
|
|
651
|
+
// bare config without the role block (A1: "功能没跑起来就等于没实现"); only an explicit
|
|
652
|
+
// `role.enabled: false` (or DSH_LONGLIVE_DISABLE_ROLE=1) kills it.
|
|
653
|
+
const activation = resolveActivationSwitches(config, options);
|
|
654
|
+
const memoryV2On = activation.memoryV2Enabled;
|
|
655
|
+
const roleOn = options.roleEnabled !== false && config?.role?.enabled !== false && !killSwitch('DSH_LONGLIVE_DISABLE_ROLE');
|
|
533
656
|
|
|
534
657
|
// Not an opt-in feature: this is the operator-facing receipt required after
|
|
535
658
|
// every surgery. `index.js` passes text only when a state exists and its
|
|
@@ -543,6 +666,18 @@ export function registerFeatures(ctx, config = {}, options = {}) {
|
|
|
543
666
|
enabled.push('identityCard');
|
|
544
667
|
}
|
|
545
668
|
|
|
669
|
+
// v2.6.4 连续性最小集:working-frame 只随 memoryV2 开启(默认 off);
|
|
670
|
+
// 注册顺序在 identityCard 之后、autoRecall 之前 => 注入顺序 [boot, shared, working, recall]。
|
|
671
|
+
if (memoryV2On && options.workingFrame !== false) {
|
|
672
|
+
try {
|
|
673
|
+
if (registerWorkingFrame(ctx, { memoryRoot, warn, now: options.now, monoNow: options.monoNow })) {
|
|
674
|
+
enabled.push('workingFrame');
|
|
675
|
+
}
|
|
676
|
+
} catch (error) {
|
|
677
|
+
warn(`[working-frame] 注册失败(${error?.code ?? error?.message ?? error})`);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
|
|
546
681
|
if (cfg.autoRecall.enabled) {
|
|
547
682
|
const recallConfig = {
|
|
548
683
|
autoRecall: true,
|
|
@@ -566,6 +701,27 @@ export function registerFeatures(ctx, config = {}, options = {}) {
|
|
|
566
701
|
enabled.push('presenceBus');
|
|
567
702
|
}
|
|
568
703
|
|
|
704
|
+
if (cfg.sharedBrain.thinkingInjection && !cfg.sharedBrain.activity.enabled) {
|
|
705
|
+
warn('[longlive] sharedBrain.thinkingInjection 已开启但 sharedBrain.activity.enabled=false — thinking 摘要需要活动流开启,已跳过');
|
|
706
|
+
}
|
|
707
|
+
if (cfg.sharedBrain.activity.enabled) {
|
|
708
|
+
if (!memoryRoot) {
|
|
709
|
+
warn('[longlive] sharedBrain.activity 已开启但没有可解析的 memoryRoot — 已跳过');
|
|
710
|
+
} else {
|
|
711
|
+
const stream = registerActivityStream(ctx, {
|
|
712
|
+
...cfg.sharedBrain.activity,
|
|
713
|
+
thinkingInjection: cfg.sharedBrain.thinkingInjection,
|
|
714
|
+
}, {
|
|
715
|
+
memoryRoot,
|
|
716
|
+
// Test seam only; the host config never carries these.
|
|
717
|
+
now: config.now,
|
|
718
|
+
privacyScan: typeof config.activityPrivacyScan === 'function' ? config.activityPrivacyScan : undefined,
|
|
719
|
+
logger: warn,
|
|
720
|
+
});
|
|
721
|
+
if (stream.enabled) enabled.push('sharedBrain.activity');
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
569
725
|
if (cfg.autoMaintenance.enabled) {
|
|
570
726
|
if (!memoryRoot) {
|
|
571
727
|
warn('[longlive] autoMaintenance 已开启但没有可解析的 memoryRoot — 已跳过');
|
|
@@ -599,6 +755,26 @@ export function registerFeatures(ctx, config = {}, options = {}) {
|
|
|
599
755
|
}
|
|
600
756
|
}
|
|
601
757
|
|
|
758
|
+
// v2.8 §16.3 角色内核(1.8.0 默认 ON;任务 激活门禁):
|
|
759
|
+
// 默认注册 hook / 落盘;显式 role.enabled:false 或 DSH_LONGLIVE_DISABLE_ROLE=1 是独立 kill
|
|
760
|
+
// switch(零 hook、零目录、零 IO)。子开关走 normalizeRoleConfig 的代码默认。
|
|
761
|
+
if (roleOn) {
|
|
762
|
+
try {
|
|
763
|
+
const roleKernel = registerRole(ctx, config, {
|
|
764
|
+
memoryRoot,
|
|
765
|
+
now: config.now,
|
|
766
|
+
warn,
|
|
767
|
+
channels: Array.isArray(config.roleChannels) ? config.roleChannels : undefined,
|
|
768
|
+
channelSend: typeof config.roleChannelSend === 'function' ? config.roleChannelSend : undefined,
|
|
769
|
+
});
|
|
770
|
+
if (roleKernel.enabled) enabled.push('role');
|
|
771
|
+
else if (roleKernel.reason === 'no-memory-root') {
|
|
772
|
+
warn('[longlive] role 已开启但没有可解析的 memoryRoot — 已跳过');
|
|
773
|
+
}
|
|
774
|
+
} catch (error) {
|
|
775
|
+
warn(`[longlive] role 装配失败(${error?.code ?? error?.message ?? error})— 已跳过`);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
602
778
|
if (enabled.length > 0 && logger && typeof logger.info === 'function') {
|
|
603
779
|
logger.info(`[longlive] opt-in features: ${enabled.join(', ')}`);
|
|
604
780
|
}
|
package/src/heartbeat.js
CHANGED
|
@@ -1,24 +1,65 @@
|
|
|
1
1
|
// Auto-heartbeat for the "正在" live registry.
|
|
2
2
|
//
|
|
3
|
-
// Two clocks keep a
|
|
4
|
-
// 1. turn lifecycle — `session/event` with `turn/start` / `turn/end
|
|
5
|
-
// session
|
|
3
|
+
// Two clocks keep a row fresh without the caller passing sessionId:
|
|
4
|
+
// 1. turn lifecycle — `session/event` with `turn/start` / `turn/end`. The
|
|
5
|
+
// event itself carries the session id, so turn boundaries maintain EVERY
|
|
6
|
+
// non-subagent session's row (R4.5), bound or not; a missing row is
|
|
7
|
+
// created on the first boundary (128-row cap respected, R4.3);
|
|
6
8
|
// 2. a fallback interval (`heartbeatMs`, default 15 s, `0` disables), which
|
|
7
|
-
//
|
|
9
|
+
// keeps rows of sessions bound by a longlive tool call fresh through long
|
|
10
|
+
// tool calls and idle stretches. It never fabricates rows.
|
|
8
11
|
//
|
|
9
|
-
//
|
|
10
|
-
// `
|
|
11
|
-
//
|
|
12
|
-
//
|
|
12
|
+
// Turn boundaries are a state machine, not a heartbeat: `turn/start` writes
|
|
13
|
+
// `state='running'` plus the turn number, `turn/end` writes
|
|
14
|
+
// `idle`/`waiting`/`blocked` plus the turn number (R4.3). It is event driven,
|
|
15
|
+
// so it still runs when the fallback timer is off (`heartbeatMs: 0`); a timer
|
|
16
|
+
// tick, by contrast, only renews `heartbeatAt` and never touches state or
|
|
17
|
+
// `last_action`.
|
|
13
18
|
//
|
|
14
|
-
// Every write is best effort: a missing/corrupt row, an unset memoryRoot
|
|
15
|
-
// racing writer must never fail a tool call or crash the
|
|
19
|
+
// Every write is best effort: a missing/corrupt row, an unset memoryRoot, a
|
|
20
|
+
// full registry or a racing writer must never fail a tool call or crash the
|
|
21
|
+
// host.
|
|
16
22
|
|
|
17
|
-
import { liveTouch, liveUpdate } from './live.js';
|
|
23
|
+
import { liveGet, liveList, liveTouch, liveUpdate } from './live.js';
|
|
18
24
|
import { resolveCurrentSessionId } from './identity.js';
|
|
19
25
|
|
|
20
26
|
export const DEFAULT_HEARTBEAT_MS = 15_000;
|
|
21
27
|
export const MAX_BOUND_SESSIONS = 64;
|
|
28
|
+
/** DESIGN §2.1 live-row cap; mirrored here so turn boundaries cannot blow it up. */
|
|
29
|
+
export const MAX_LIVE_ROWS = 128;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* R4.3 pure state machine: state a live row must carry when a turn starts.
|
|
33
|
+
* @returns {'running'}
|
|
34
|
+
*/
|
|
35
|
+
export function stateForTurnStart() {
|
|
36
|
+
return 'running';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* R4.3 pure state machine: state a live row must carry when a turn ends.
|
|
41
|
+
* `waiting`/`blocked` are user-facing promises and survive the turn boundary;
|
|
42
|
+
* anything else falls back to `idle`.
|
|
43
|
+
* @param {unknown} priorState declared state read before the turn/end write
|
|
44
|
+
* @returns {'idle'|'waiting'|'blocked'}
|
|
45
|
+
*/
|
|
46
|
+
export function stateForTurnEnd(priorState) {
|
|
47
|
+
return priorState === 'waiting' || priorState === 'blocked' ? priorState : 'idle';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Pure description of the live-row patch caused by one turn boundary. Kept
|
|
52
|
+
* separate from I/O so the state machine can be pinned without a registry.
|
|
53
|
+
* @param {'turn/start'|'turn/end'} type
|
|
54
|
+
* @param {{turn?:unknown, priorState?:unknown}} [options]
|
|
55
|
+
* @returns {{state:string, turn:number|null, kind:'turn', detail:string}}
|
|
56
|
+
*/
|
|
57
|
+
export function turnBoundaryPlan(type, options = {}) {
|
|
58
|
+
const kind = type === 'turn/end' ? 'turn/end' : 'turn/start';
|
|
59
|
+
const state = kind === 'turn/start' ? stateForTurnStart() : stateForTurnEnd(options.priorState);
|
|
60
|
+
const turn = Number.isInteger(options.turn) && options.turn >= 0 ? options.turn : null;
|
|
61
|
+
return { state, turn, kind: 'turn', detail: turn == null ? kind : `${kind} #${turn}` };
|
|
62
|
+
}
|
|
22
63
|
|
|
23
64
|
function cleanId(value) {
|
|
24
65
|
if (typeof value !== 'string') return null;
|
|
@@ -33,12 +74,19 @@ function cleanId(value) {
|
|
|
33
74
|
* @param {object} [options]
|
|
34
75
|
* @param {object|null} [options.ctx] host context (used for `session/event`)
|
|
35
76
|
* @param {string} [options.memoryRoot] live-registry root; absent disables writes
|
|
36
|
-
* @param {number} [options.heartbeatMs] fallback interval; `0` disables
|
|
37
|
-
*
|
|
77
|
+
* @param {number} [options.heartbeatMs] fallback interval; `0` disables the
|
|
78
|
+
* timer and tool-call touches (binding still happens through the tool
|
|
79
|
+
* resolver). Turn-boundary state writes (`turn/start` → running + turn,
|
|
80
|
+
* `turn/end` → idle/waiting/blocked + turn) are event driven and keep
|
|
81
|
+
* working, because "no timer" is not "no state machine" (R4.3).
|
|
38
82
|
* @param {() => (Date|number)} [options.now] clock injection for tests
|
|
39
83
|
* @param {Function} [options.touch] `liveTouch` injection for tests
|
|
40
84
|
* @param {Function} [options.update] `liveUpdate` injection for tests (first
|
|
41
85
|
* registration of a session that has no row yet)
|
|
86
|
+
* @param {Function} [options.get] `liveGet` injection for tests (turn/end reads
|
|
87
|
+
* the prior declared state so waiting/blocked survive)
|
|
88
|
+
* @param {number} [options.maxRows] live-row cap for rows created by turn
|
|
89
|
+
* boundaries (default 128, DESIGN §2.1)
|
|
42
90
|
* @param {Function} [options.setInterval] timer injection for tests
|
|
43
91
|
* @param {Function} [options.clearInterval]
|
|
44
92
|
* @param {Function} [options.resolve] `(exec) => {id, source}` injection
|
|
@@ -51,6 +99,9 @@ export function createAutoHeartbeat(options = {}) {
|
|
|
51
99
|
now,
|
|
52
100
|
touch = liveTouch,
|
|
53
101
|
update = liveUpdate,
|
|
102
|
+
// Read side, used only to preserve waiting/blocked across turn/end.
|
|
103
|
+
get = liveGet,
|
|
104
|
+
maxRows = MAX_LIVE_ROWS,
|
|
54
105
|
setInterval: setIntervalFn = globalThis.setInterval,
|
|
55
106
|
clearInterval: clearIntervalFn = globalThis.clearInterval,
|
|
56
107
|
resolve = (exec) => resolveCurrentSessionId({ ctx, exec }),
|
|
@@ -61,7 +112,9 @@ export function createAutoHeartbeat(options = {}) {
|
|
|
61
112
|
? memoryRoot.trim()
|
|
62
113
|
: null;
|
|
63
114
|
const interval = typeof heartbeatMs === 'number' ? heartbeatMs : Number(heartbeatMs);
|
|
64
|
-
// Only a finite positive interval enables
|
|
115
|
+
// Only a finite positive interval enables the fallback timer and the
|
|
116
|
+
// tool-call touches; 0/invalid = those two off. Turn-boundary state writes
|
|
117
|
+
// (R4.3) are event driven and deliberately independent of this flag.
|
|
65
118
|
const enabled = Number.isFinite(interval) && interval > 0;
|
|
66
119
|
|
|
67
120
|
const bound = new Set();
|
|
@@ -156,18 +209,82 @@ export function createAutoHeartbeat(options = {}) {
|
|
|
156
209
|
return touched;
|
|
157
210
|
}
|
|
158
211
|
|
|
212
|
+
/**
|
|
213
|
+
* Prior row snapshot for a turn boundary: does it exist, and what state does
|
|
214
|
+
* it declare? Read-only; never throws. `known:false` means the read itself
|
|
215
|
+
* failed, in which case we still attempt the write (liveUpdate is atomic and
|
|
216
|
+
* the row keeps its prior values for omitted fields).
|
|
217
|
+
*/
|
|
218
|
+
function readPriorRow(id) {
|
|
219
|
+
if (root == null || typeof get !== 'function') return { known: false, found: false, state: null };
|
|
220
|
+
const config = { memoryRoot: root };
|
|
221
|
+
const at = stamp();
|
|
222
|
+
if (at !== undefined) config.now = at;
|
|
223
|
+
try {
|
|
224
|
+
const got = get({ sessionId: id }, config);
|
|
225
|
+
if (got?.ok === true) {
|
|
226
|
+
return { known: true, found: true, state: typeof got.live?.state === 'string' ? got.live.state : null };
|
|
227
|
+
}
|
|
228
|
+
if (got?.status === 'absent') return { known: true, found: false, state: null };
|
|
229
|
+
// corrupt/unreadable-but-present: it occupies a slot; a write repairs it.
|
|
230
|
+
return { known: true, found: true, state: null };
|
|
231
|
+
} catch {
|
|
232
|
+
return { known: false, found: false, state: null };
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** True when a NEW row may still be created without exceeding the 128 cap. */
|
|
237
|
+
function hasRowCapacity() {
|
|
238
|
+
if (root == null || typeof liveList !== 'function') return true;
|
|
239
|
+
const config = { memoryRoot: root };
|
|
240
|
+
const at = stamp();
|
|
241
|
+
if (at !== undefined) config.now = at;
|
|
242
|
+
try {
|
|
243
|
+
const listed = liveList({ includeDead: true }, config);
|
|
244
|
+
const scanned = Number.isInteger(listed?.scanned)
|
|
245
|
+
? listed.scanned
|
|
246
|
+
: (Array.isArray(listed?.entries) ? listed.entries.length : 0);
|
|
247
|
+
return scanned < maxRows;
|
|
248
|
+
} catch {
|
|
249
|
+
// Cannot tell -> do not create rows, but an existing row may be updated.
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** One best-effort live-row patch at a turn boundary (state + turn + action). */
|
|
255
|
+
function writeTurnBoundary(id, { state, turn, kind, detail }) {
|
|
256
|
+
if (root == null || typeof update !== 'function') return { ok: false, status: 'disabled' };
|
|
257
|
+
const args = { sessionId: id, state, last_action: { kind, detail } };
|
|
258
|
+
if (Number.isInteger(turn) && turn >= 0) args.turn = turn;
|
|
259
|
+
const config = { memoryRoot: root };
|
|
260
|
+
const at = stamp();
|
|
261
|
+
if (at !== undefined) config.now = at;
|
|
262
|
+
try {
|
|
263
|
+
return update(args, config);
|
|
264
|
+
} catch {
|
|
265
|
+
// A state-machine write is decoration for other sessions, never the
|
|
266
|
+
// turn itself: swallow and let the turn proceed.
|
|
267
|
+
return { ok: false, status: 'error' };
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
159
271
|
function onSessionEvent(session, event) {
|
|
160
272
|
let id = null;
|
|
273
|
+
let origin = null;
|
|
161
274
|
try {
|
|
162
|
-
id = cleanId(session?.id)
|
|
275
|
+
id = cleanId(session?.id)
|
|
276
|
+
?? cleanId(session?.header?.id)
|
|
277
|
+
?? cleanId(event?.session?.id)
|
|
278
|
+
?? cleanId(event?.session?.header?.id);
|
|
279
|
+
const header = session?.header ?? session?.session?.header ?? event?.session?.header ?? {};
|
|
280
|
+
origin = typeof header.origin === 'string' ? header.origin : null;
|
|
163
281
|
} catch {
|
|
164
282
|
id = null;
|
|
165
283
|
}
|
|
166
284
|
// Auto-truncation watches every session in this agent's scope, not only
|
|
167
285
|
// the ones bound to the live registry: a session that never called a
|
|
168
286
|
// longlive tool can still grow past the threshold. It runs before the
|
|
169
|
-
//
|
|
170
|
-
// maintenance off.
|
|
287
|
+
// live-state gate so `heartbeatMs:0` does not also turn maintenance off.
|
|
171
288
|
if (typeof onTurnEnd === 'function' && event?.type === 'turn/end' && id) {
|
|
172
289
|
try {
|
|
173
290
|
onTurnEnd({ session, event, sessionId: id, turn: event?.data?.turn });
|
|
@@ -175,15 +292,31 @@ export function createAutoHeartbeat(options = {}) {
|
|
|
175
292
|
/* automation is best effort; never fail the host feed */
|
|
176
293
|
}
|
|
177
294
|
}
|
|
178
|
-
if (!enabled) return;
|
|
179
|
-
if (!id || !bound.has(id)) return;
|
|
180
295
|
const type = event?.type;
|
|
296
|
+
if (!id) return;
|
|
181
297
|
if (type !== 'turn/start' && type !== 'turn/end') return;
|
|
298
|
+
// R4.6: subagents are counted separately on the board; they never get a
|
|
299
|
+
// live row from the heartbeat (same rule as the Router's L1 writer).
|
|
300
|
+
if (origin === 'subagent') return;
|
|
301
|
+
if (root == null || typeof update !== 'function') return;
|
|
182
302
|
const turn = event?.data?.turn;
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
303
|
+
// R4.5: the event carries the session id, so turn boundaries maintain
|
|
304
|
+
// EVERY non-subagent session's row — a session that only runs native tools
|
|
305
|
+
// (never calls a longlive tool, so it is never `bind`ed) must still switch
|
|
306
|
+
// state/turn. Create the row on its first boundary, within the 128 cap.
|
|
307
|
+
const prior = readPriorRow(id);
|
|
308
|
+
if (!prior.found && !hasRowCapacity()) return;
|
|
309
|
+
if (type === 'turn/start') {
|
|
310
|
+
// R4.3 状态机:turn/start 立刻让 live 行 state: 'running' 并写入 turn 号
|
|
311
|
+
// (liveUpdate 一次完成;与心跳 tick 无关,tick 只续 heartbeatAt)。
|
|
312
|
+
const plan = turnBoundaryPlan('turn/start', { turn });
|
|
313
|
+
writeTurnBoundary(id, plan);
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
// turn/end: idle/blocked/waiting 都落 turn 号;waiting/blocked 是给用户
|
|
317
|
+
// 看的承诺,turn 结束不能把它抹成 idle。
|
|
318
|
+
const endPlan = turnBoundaryPlan('turn/end', { turn, priorState: prior.state });
|
|
319
|
+
writeTurnBoundary(id, endPlan);
|
|
187
320
|
}
|
|
188
321
|
|
|
189
322
|
function tick() {
|
package/src/identity/handover.js
CHANGED
|
@@ -416,6 +416,41 @@ function allocateBudget(parts, total) {
|
|
|
416
416
|
return budgets;
|
|
417
417
|
}
|
|
418
418
|
|
|
419
|
+
/**
|
|
420
|
+
* R6.2: 「状态卡写于 X 分钟前」——X 是 STATE.md mtime 与 now 的差,不是卡片
|
|
421
|
+
* 生成时间,也不是会话开始时间。拿不到 mtime 时返回 ''(宁可不写,不编造)。
|
|
422
|
+
* @param {unknown} ageMs
|
|
423
|
+
* @returns {string}
|
|
424
|
+
*/
|
|
425
|
+
export function stateCardAgeText(ageMs) {
|
|
426
|
+
if (typeof ageMs !== 'number' || !Number.isFinite(ageMs)) return '';
|
|
427
|
+
const minutes = Math.max(0, Math.round(ageMs / 60000));
|
|
428
|
+
return `状态卡写于 ${minutes} 分钟前`;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Resolve the STATE.md age in ms from explicit inputs, falling back to stat()
|
|
433
|
+
* on `statePath`. Missing/unknown age returns null — the card then omits the
|
|
434
|
+
* sentence instead of inventing a number.
|
|
435
|
+
*/
|
|
436
|
+
function resolveStateAgeMs(input, safeNow) {
|
|
437
|
+
if (typeof input.stateAgeMs === 'number' && Number.isFinite(input.stateAgeMs)) {
|
|
438
|
+
return Math.max(0, input.stateAgeMs);
|
|
439
|
+
}
|
|
440
|
+
let mtimeMs = typeof input.stateMtimeMs === 'number' && Number.isFinite(input.stateMtimeMs)
|
|
441
|
+
? input.stateMtimeMs
|
|
442
|
+
: null;
|
|
443
|
+
if (mtimeMs === null && typeof input.statePath === 'string' && input.statePath.trim() !== '') {
|
|
444
|
+
try {
|
|
445
|
+
mtimeMs = fs.statSync(input.statePath).mtimeMs;
|
|
446
|
+
} catch {
|
|
447
|
+
mtimeMs = null;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
if (mtimeMs === null) return null;
|
|
451
|
+
return Math.max(0, safeNow.getTime() - mtimeMs);
|
|
452
|
+
}
|
|
453
|
+
|
|
419
454
|
/**
|
|
420
455
|
* 生成开机卡。纯函数:所有输入显式传入,方便覆盖缺失/超长/中文路径等边界。
|
|
421
456
|
* @param {{
|
|
@@ -424,11 +459,14 @@ function allocateBudget(parts, total) {
|
|
|
424
459
|
* maxChars?: number,
|
|
425
460
|
* now?: Date|number|string,
|
|
426
461
|
* statePath?: string,
|
|
462
|
+
* stateMtimeMs?: number,
|
|
463
|
+
* stateAgeMs?: number,
|
|
427
464
|
* handoverPath?: string,
|
|
428
465
|
* }} [input]
|
|
429
466
|
* @returns {{
|
|
430
467
|
* text:string, chars:number, truncated:boolean, warnings:string[],
|
|
431
468
|
* found:Record<string,boolean>, handoverName:string|null,
|
|
469
|
+
* stateAgeMinutes:number|null,
|
|
432
470
|
* }}
|
|
433
471
|
*/
|
|
434
472
|
export function buildOpenCard(input = {}) {
|
|
@@ -439,6 +477,8 @@ export function buildOpenCard(input = {}) {
|
|
|
439
477
|
? input.now
|
|
440
478
|
: new Date(input.now ?? Date.now());
|
|
441
479
|
const safeNow = Number.isFinite(now.getTime()) ? now : new Date();
|
|
480
|
+
const stateAgeMs = resolveStateAgeMs(input, safeNow);
|
|
481
|
+
const stateAgeMinutes = stateAgeMs === null ? null : Math.max(0, Math.round(stateAgeMs / 60000));
|
|
442
482
|
const warnings = [];
|
|
443
483
|
const stateText = typeof input.stateText === 'string' ? normalizeText(input.stateText) : '';
|
|
444
484
|
if (input.stateText === null || input.stateText === undefined) warnings.push('STATE_MISSING');
|
|
@@ -458,7 +498,8 @@ export function buildOpenCard(input = {}) {
|
|
|
458
498
|
if (!input.handover) warnings.push('HANDOVER_MISSING');
|
|
459
499
|
else if (handoverText.trim() === '') warnings.push('HANDOVER_EMPTY');
|
|
460
500
|
|
|
461
|
-
const
|
|
501
|
+
const ageText = stateCardAgeText(stateAgeMs);
|
|
502
|
+
const header = `【开机卡】${formatCardTime(safeNow)}${ageText === '' ? '' : ` · ${ageText}`}`;
|
|
462
503
|
const headings = {
|
|
463
504
|
where: '▍我在哪',
|
|
464
505
|
waiting: '▍在等什么',
|
|
@@ -516,6 +557,7 @@ export function buildOpenCard(input = {}) {
|
|
|
516
557
|
warnings,
|
|
517
558
|
found: { ...parsed.found, handover: handoverText.trim() !== '' },
|
|
518
559
|
handoverName,
|
|
560
|
+
stateAgeMinutes,
|
|
519
561
|
};
|
|
520
562
|
}
|
|
521
563
|
|
|
@@ -558,6 +600,14 @@ export function collectOpenCard(options = {}) {
|
|
|
558
600
|
const errors = [];
|
|
559
601
|
const stateRead = readTextFile(statePath);
|
|
560
602
|
if (!stateRead.ok) errors.push(`STATE_READ_FAILED:${stateRead.error}`);
|
|
603
|
+
// R6.2: the open card must say how old the state card is. Read the mtime
|
|
604
|
+
// once here; a missing file leaves it unknown and the sentence is omitted.
|
|
605
|
+
let stateMtimeMs = null;
|
|
606
|
+
try {
|
|
607
|
+
stateMtimeMs = fs.statSync(statePath).mtimeMs;
|
|
608
|
+
} catch {
|
|
609
|
+
stateMtimeMs = null;
|
|
610
|
+
}
|
|
561
611
|
|
|
562
612
|
let handover = null;
|
|
563
613
|
let handoverPath = null;
|
|
@@ -593,6 +643,7 @@ export function collectOpenCard(options = {}) {
|
|
|
593
643
|
maxChars: options.maxChars,
|
|
594
644
|
now: options.now,
|
|
595
645
|
statePath,
|
|
646
|
+
stateMtimeMs,
|
|
596
647
|
handoverPath: handoverPath ?? undefined,
|
|
597
648
|
});
|
|
598
649
|
|