@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
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// src/lifecycle/index.js — M2-B / PLAN §2.7:宿主生命周期入账 + 双时钟空窗补记
|
|
2
|
+
//
|
|
3
|
+
// 启动时(memoryV2.enabled=true 且 host 支持):
|
|
4
|
+
// 1) 读上次 boot.json / shutdown.json → 判定 prevExitForm(clean|crash|unknown);
|
|
5
|
+
// 2) computeGaps() 算 host-gap / memory-gap(分别记录、不合并);
|
|
6
|
+
// 3) 追加 `.longlive/board/lifecycle.jsonl` 事件行;
|
|
7
|
+
// 4) 原子写本次 boot.json(tmp→rename);
|
|
8
|
+
// 5) 通过 capture 把两钟写进 journal(幂等 cap key)+ 索引 lifecycle 事件;
|
|
9
|
+
// 6) 注册退出钩子写 shutdown.json(exit form 的唯一可靠来源)。
|
|
10
|
+
// 任何异常只告警、不阻断插件加载(与 surgery-recovery 同款)。
|
|
11
|
+
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
|
|
15
|
+
import { createCapture, writeFileAtomic } from '../memory/capture.js';
|
|
16
|
+
import { acquireLease, releaseLease } from '../memory/lock.js';
|
|
17
|
+
import { computeGaps, renderGapLines } from './gap-clocks.js';
|
|
18
|
+
|
|
19
|
+
export const LIFECYCLE_SCHEMA = 'host-lifecycle/v1';
|
|
20
|
+
|
|
21
|
+
function nowMs(now) {
|
|
22
|
+
const value = typeof now === 'function' ? now() : new Date();
|
|
23
|
+
return value instanceof Date ? value.getTime() : Number(value);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function readJsonSafe(file) {
|
|
27
|
+
try {
|
|
28
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
29
|
+
return value && typeof value === 'object' ? value : null;
|
|
30
|
+
} catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function pidAlive(pid) {
|
|
36
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
37
|
+
try {
|
|
38
|
+
process.kill(pid, 0);
|
|
39
|
+
return true;
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (error?.code === 'ESRCH') return false;
|
|
42
|
+
return true; // EPERM etc: cannot prove dead -> treat as alive (conservative)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function lifecyclePaths(memoryRoot) {
|
|
47
|
+
const root = path.resolve(String(memoryRoot ?? ''));
|
|
48
|
+
const bridge = path.join(root, '.longlive', 'bridge');
|
|
49
|
+
return {
|
|
50
|
+
root,
|
|
51
|
+
bridge,
|
|
52
|
+
boot: path.join(bridge, 'boot.json'),
|
|
53
|
+
shutdown: path.join(bridge, 'shutdown.json'),
|
|
54
|
+
lifecycleLog: path.join(root, '.longlive', 'board', 'lifecycle.jsonl'),
|
|
55
|
+
lock: path.join(root, '.longlive', 'memory', 'lifecycle.lock'),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Create the host lifecycle recorder.
|
|
61
|
+
*
|
|
62
|
+
* @param {object} options
|
|
63
|
+
* @param {string} options.memoryRoot
|
|
64
|
+
* @param {() => Date} [options.now]
|
|
65
|
+
* @param {string[]} [options.sessionRoots]
|
|
66
|
+
* @param {object} [options.capture] injected createCapture() (tests)
|
|
67
|
+
* @param {string} [options.holder]
|
|
68
|
+
*/
|
|
69
|
+
export function createHostLifecycle(options = {}) {
|
|
70
|
+
const memoryRoot = path.resolve(String(options.memoryRoot ?? ''));
|
|
71
|
+
if (memoryRoot === '') throw new Error('E_MEMORY_ROOT: lifecycle requires memoryRoot');
|
|
72
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date();
|
|
73
|
+
const paths = lifecyclePaths(memoryRoot);
|
|
74
|
+
const sessionRoots = Array.isArray(options.sessionRoots) ? options.sessionRoots : [];
|
|
75
|
+
const holder = options.holder ?? `lifecycle-${process.pid}`;
|
|
76
|
+
const capture = options.capture ?? createCapture({ memoryRoot, now, sessionRoots, holder });
|
|
77
|
+
|
|
78
|
+
function withLease(fn) {
|
|
79
|
+
fs.mkdirSync(path.dirname(paths.lock), { recursive: true });
|
|
80
|
+
const lease = acquireLease(paths.lock, { holder, now });
|
|
81
|
+
try {
|
|
82
|
+
return fn();
|
|
83
|
+
} finally {
|
|
84
|
+
releaseLease(paths.lock, lease.holder);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function appendLifecycleLine(line) {
|
|
89
|
+
fs.mkdirSync(path.dirname(paths.lifecycleLog), { recursive: true });
|
|
90
|
+
fs.appendFileSync(paths.lifecycleLog, `${JSON.stringify({ schema: LIFECYCLE_SCHEMA, ...line })}\n`, 'utf8');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function prevExitFormOf(prevBoot, prevShutdown) {
|
|
94
|
+
if (prevShutdown && Number.isFinite(Number(prevShutdown.at))
|
|
95
|
+
&& (!prevBoot || Number(prevShutdown.at) >= Number(prevBoot.bootAt ?? 0))) return 'clean';
|
|
96
|
+
if (prevBoot && Number.isInteger(prevBoot.pid) && !pidAlive(prevBoot.pid)) return 'crash';
|
|
97
|
+
return 'unknown';
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Record a boot: prevExitForm + gap clocks + boot.json.
|
|
102
|
+
* Returns { ok, boot, gaps, lines, journal, lifecycleEvent }.
|
|
103
|
+
*/
|
|
104
|
+
function recordBoot(input = {}) {
|
|
105
|
+
const bootAtMs = Number.isFinite(input.bootAt) ? input.bootAt : nowMs(now);
|
|
106
|
+
const prevBoot = readJsonSafe(paths.boot);
|
|
107
|
+
const prevShutdown = readJsonSafe(paths.shutdown);
|
|
108
|
+
const prevExitForm = prevExitFormOf(prevBoot, prevShutdown);
|
|
109
|
+
const gaps = computeGaps({
|
|
110
|
+
memoryRoot,
|
|
111
|
+
bootAtMs,
|
|
112
|
+
sessionRoots,
|
|
113
|
+
lifecycle: {
|
|
114
|
+
prevExitForm,
|
|
115
|
+
lastShutdownAtMs: Number(prevShutdown?.at) > 0 ? Number(prevShutdown.at) : undefined,
|
|
116
|
+
lastActivityAtMs: Number(prevBoot?.lastActivityAt) > 0 ? Number(prevBoot.lastActivityAt) : undefined,
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
const boot = {
|
|
120
|
+
schema: LIFECYCLE_SCHEMA,
|
|
121
|
+
event: 'boot',
|
|
122
|
+
at: nowMs(now),
|
|
123
|
+
bootAt: bootAtMs,
|
|
124
|
+
pid: Number.isInteger(input.pid) ? input.pid : process.pid,
|
|
125
|
+
prevExitForm,
|
|
126
|
+
prevBootAt: Number(prevBoot?.bootAt) > 0 ? Number(prevBoot.bootAt) : null,
|
|
127
|
+
hostVersion: input.hostVersion ?? options.hostVersion ?? null,
|
|
128
|
+
pluginVersion: input.pluginVersion ?? options.pluginVersion ?? null,
|
|
129
|
+
hostGap: { gapMs: gaps.hostGap.gapMs, gapText: gaps.hostGap.gapText, uncertain: gaps.hostGap.uncertain },
|
|
130
|
+
memoryGap: { gapMs: gaps.memoryGap.gapMs, gapSec: gaps.memoryGap.gapSec, gapText: gaps.memoryGap.gapText, kind: gaps.memoryGap.kind },
|
|
131
|
+
};
|
|
132
|
+
let journal = null;
|
|
133
|
+
try {
|
|
134
|
+
journal = capture.captureMemoryGap({ gaps });
|
|
135
|
+
} catch (error) {
|
|
136
|
+
journal = { ok: false, code: 'E_GAP_CAPTURE', message: String(error?.message ?? error) };
|
|
137
|
+
}
|
|
138
|
+
let lifecycleEvent = null;
|
|
139
|
+
try {
|
|
140
|
+
lifecycleEvent = capture.captureLifecycleEvent({
|
|
141
|
+
event: 'boot',
|
|
142
|
+
at: boot.at,
|
|
143
|
+
key: `boot:${bootAtMs}`,
|
|
144
|
+
text: `prevExitForm=${prevExitForm} hostGap=${gaps.hostGap.gapText} memoryGap=${gaps.memoryGap.gapText}`,
|
|
145
|
+
data: { pid: boot.pid, bootAt: bootAtMs },
|
|
146
|
+
});
|
|
147
|
+
} catch (error) {
|
|
148
|
+
lifecycleEvent = { ok: false, code: 'E_LIFECYCLE_CAPTURE', message: String(error?.message ?? error) };
|
|
149
|
+
}
|
|
150
|
+
const writeResult = withLease(() => {
|
|
151
|
+
appendLifecycleLine(boot);
|
|
152
|
+
writeFileAtomic(paths.boot, `${JSON.stringify({
|
|
153
|
+
bootAt: bootAtMs,
|
|
154
|
+
pid: boot.pid,
|
|
155
|
+
hostVersion: boot.hostVersion,
|
|
156
|
+
pluginVersion: boot.pluginVersion,
|
|
157
|
+
prevExitForm,
|
|
158
|
+
lastActivityAt: boot.at,
|
|
159
|
+
}, null, 2)}\n`);
|
|
160
|
+
return { ok: true };
|
|
161
|
+
});
|
|
162
|
+
return {
|
|
163
|
+
ok: true,
|
|
164
|
+
boot,
|
|
165
|
+
gaps,
|
|
166
|
+
lines: renderGapLines(gaps),
|
|
167
|
+
journal,
|
|
168
|
+
lifecycleEvent,
|
|
169
|
+
write: writeResult,
|
|
170
|
+
bootPath: paths.boot,
|
|
171
|
+
lifecycleLog: paths.lifecycleLog,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Record a clean shutdown (exit form evidence). Best effort: never throws. */
|
|
176
|
+
function recordShutdown(input = {}) {
|
|
177
|
+
const at = Number.isFinite(input.at) ? input.at : nowMs(now);
|
|
178
|
+
const record = { schema: LIFECYCLE_SCHEMA, event: 'shutdown', at, pid: Number.isInteger(input.pid) ? input.pid : process.pid, form: input.form ?? 'clean' };
|
|
179
|
+
let written = false;
|
|
180
|
+
try {
|
|
181
|
+
withLease(() => {
|
|
182
|
+
writeFileAtomic(paths.shutdown, `${JSON.stringify(record, null, 2)}\n`);
|
|
183
|
+
appendLifecycleLine(record);
|
|
184
|
+
written = true;
|
|
185
|
+
});
|
|
186
|
+
} catch {
|
|
187
|
+
written = false;
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
capture.captureLifecycleEvent({ event: 'shutdown', at, key: `shutdown:${at}`, text: `form=${record.form}`, data: { pid: record.pid } });
|
|
191
|
+
} catch {
|
|
192
|
+
/* best effort */
|
|
193
|
+
}
|
|
194
|
+
return { ok: written, record, shutdownPath: paths.shutdown };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function history(input = {}) {
|
|
198
|
+
const limit = Number.isInteger(input.limit) ? Math.min(Math.max(input.limit, 1), 200) : 20;
|
|
199
|
+
const rows = [];
|
|
200
|
+
let text = '';
|
|
201
|
+
try {
|
|
202
|
+
text = fs.readFileSync(paths.lifecycleLog, 'utf8');
|
|
203
|
+
} catch {
|
|
204
|
+
return { ok: true, items: [], total: 0 };
|
|
205
|
+
}
|
|
206
|
+
for (const line of text.split('\n')) {
|
|
207
|
+
if (line.trim() === '') continue;
|
|
208
|
+
try {
|
|
209
|
+
rows.push(JSON.parse(line));
|
|
210
|
+
} catch {
|
|
211
|
+
/* skip corrupt line */
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return { ok: true, items: rows.slice(-limit), total: rows.length };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return { memoryRoot, paths, recordBoot, recordShutdown, history };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Host wiring entry point (called from src/index.js only when memoryV2 is on).
|
|
222
|
+
* Never throws: a lifecycle failure must not block plugin loading.
|
|
223
|
+
*/
|
|
224
|
+
export function registerHostLifecycle(ctx = {}, options = {}) {
|
|
225
|
+
const result = { ok: false, code: null, gaps: null, lines: [], handle: null };
|
|
226
|
+
try {
|
|
227
|
+
const memoryRoot = options.memoryRoot ?? options.memoryRootOf?.() ?? '';
|
|
228
|
+
if (typeof memoryRoot !== 'string' || memoryRoot === '') {
|
|
229
|
+
result.code = 'E_MEMORY_ROOT';
|
|
230
|
+
return result;
|
|
231
|
+
}
|
|
232
|
+
const lifecycle = createHostLifecycle({
|
|
233
|
+
memoryRoot,
|
|
234
|
+
now: options.now,
|
|
235
|
+
sessionRoots: Array.isArray(options.sessionRoots) ? options.sessionRoots : undefined,
|
|
236
|
+
hostVersion: options.hostVersion,
|
|
237
|
+
pluginVersion: options.pluginVersion,
|
|
238
|
+
});
|
|
239
|
+
const boot = lifecycle.recordBoot({
|
|
240
|
+
bootAt: options.bootAt,
|
|
241
|
+
hostVersion: options.hostVersion,
|
|
242
|
+
pluginVersion: options.pluginVersion,
|
|
243
|
+
});
|
|
244
|
+
if (options.registerExitHook === true) {
|
|
245
|
+
try {
|
|
246
|
+
process.once('exit', () => {
|
|
247
|
+
try {
|
|
248
|
+
lifecycle.recordShutdown({ form: 'clean' });
|
|
249
|
+
} catch {
|
|
250
|
+
/* exit hooks must never throw */
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
} catch {
|
|
254
|
+
/* best effort */
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
Object.assign(result, {
|
|
258
|
+
ok: true,
|
|
259
|
+
gaps: boot.gaps,
|
|
260
|
+
lines: boot.lines,
|
|
261
|
+
handle: { lifecycle, boot },
|
|
262
|
+
});
|
|
263
|
+
return result;
|
|
264
|
+
} catch (error) {
|
|
265
|
+
result.code = error?.code ?? 'E_LIFECYCLE';
|
|
266
|
+
result.message = String(error?.message ?? error);
|
|
267
|
+
return result;
|
|
268
|
+
}
|
|
269
|
+
}
|
package/src/live.js
CHANGED
|
@@ -82,6 +82,9 @@ export const LIVE_RECORD_FIELDS = Object.freeze([
|
|
|
82
82
|
'state',
|
|
83
83
|
'turn',
|
|
84
84
|
'goal',
|
|
85
|
+
// R3: the clock of the *goal*, not of the row. A heartbeat touch must never
|
|
86
|
+
// move it (see liveTouch), and the board renders focus.updatedAt from it.
|
|
87
|
+
'goalUpdatedAt',
|
|
85
88
|
'blocked_on',
|
|
86
89
|
'queued',
|
|
87
90
|
'last_action',
|
|
@@ -410,6 +413,9 @@ function decodeRecord(text, expectedSessionId) {
|
|
|
410
413
|
}
|
|
411
414
|
const updatedMs = parseTime(raw.updatedAt) ?? heartbeatMs;
|
|
412
415
|
const startedMs = parseTime(raw.startedAt) ?? heartbeatMs;
|
|
416
|
+
// R3 additive field: rows written before this version simply have no goal
|
|
417
|
+
// clock; keep it as '' (unknown) instead of inventing one from heartbeatAt.
|
|
418
|
+
const goalUpdatedMs = parseTime(raw.goalUpdatedAt);
|
|
413
419
|
if (!Array.isArray(raw.queued) || !raw.queued.every((item) => typeof item === 'string')) {
|
|
414
420
|
return { ok: false, reason: 'queued 必须是字符串数组' };
|
|
415
421
|
}
|
|
@@ -427,6 +433,7 @@ function decodeRecord(text, expectedSessionId) {
|
|
|
427
433
|
state: raw.state,
|
|
428
434
|
turn: Number.isInteger(raw.turn) && raw.turn >= 0 ? raw.turn : 0,
|
|
429
435
|
goal: typeof raw.goal === 'string' ? raw.goal : '',
|
|
436
|
+
goalUpdatedAt: goalUpdatedMs != null ? isoTime(goalUpdatedMs) : '',
|
|
430
437
|
blocked_on: typeof raw.blocked_on === 'string' ? raw.blocked_on : '',
|
|
431
438
|
queued: [...raw.queued],
|
|
432
439
|
last_action: normalizeLastAction(raw.last_action, updatedMs),
|
|
@@ -485,6 +492,9 @@ function liveEntry(record, { file, root, now, hostname }) {
|
|
|
485
492
|
pidAlive: alive,
|
|
486
493
|
turn: record.turn,
|
|
487
494
|
goal: record.goal,
|
|
495
|
+
// R3: the goal write clock (ISO) or null when the row never declared one.
|
|
496
|
+
// Never derived from heartbeatAt — that is exactly the lie R3 fixes.
|
|
497
|
+
goalUpdatedAt: record.goalUpdatedAt === '' ? null : record.goalUpdatedAt,
|
|
488
498
|
blocked_on: record.blocked_on,
|
|
489
499
|
queued: record.queued,
|
|
490
500
|
last_action: record.last_action,
|
|
@@ -513,6 +523,7 @@ function corruptEntry({ sessionId, file, root, reason, hostHint = null, hostname
|
|
|
513
523
|
pidAlive: null,
|
|
514
524
|
turn: null,
|
|
515
525
|
goal: '',
|
|
526
|
+
goalUpdatedAt: null,
|
|
516
527
|
blocked_on: '',
|
|
517
528
|
queued: [],
|
|
518
529
|
last_action: null,
|
|
@@ -852,6 +863,12 @@ export function liveUpdate(args = {}, config = {}) {
|
|
|
852
863
|
const base = prior.record;
|
|
853
864
|
const created = base == null;
|
|
854
865
|
const goal = fit ? fit.value : (base?.goal ?? '');
|
|
866
|
+
// R3: `goalUpdatedAt` is the goal's own clock. Only a write that supplies a
|
|
867
|
+
// goal stamps it; patches and heartbeat touches keep the previous value, so
|
|
868
|
+
// "目标 30 分钟没更新" can be told apart from "心跳 5 秒前刚动过".
|
|
869
|
+
const goalUpdatedAt = goalInput !== undefined
|
|
870
|
+
? isoTime(now)
|
|
871
|
+
: (base?.goalUpdatedAt ?? '');
|
|
855
872
|
// blocked_on describes a blocked session; anything else clears it, so a
|
|
856
873
|
// running row cannot keep advertising an obstacle nobody is waiting on.
|
|
857
874
|
const priorBlockedOn = base?.blocked_on ?? '';
|
|
@@ -873,6 +890,7 @@ export function liveUpdate(args = {}, config = {}) {
|
|
|
873
890
|
state,
|
|
874
891
|
turn: turn ?? base?.turn ?? 0,
|
|
875
892
|
goal,
|
|
893
|
+
goalUpdatedAt,
|
|
876
894
|
blocked_on: blockedOn,
|
|
877
895
|
queued: queued.value,
|
|
878
896
|
last_action: lastAction.value,
|
|
@@ -940,8 +958,10 @@ export function liveUpdate(args = {}, config = {}) {
|
|
|
940
958
|
* - it never creates a row (`status:'absent'` instead), so merely running a
|
|
941
959
|
* longlive tool does not fabricate a session row;
|
|
942
960
|
* - it never repairs/lists corrupt rows (`status:'corrupt'`, bytes untouched);
|
|
943
|
-
* - it preserves `state`, `goal`, `
|
|
944
|
-
* and `ttlMs`: heartbeat says "this writer is still
|
|
961
|
+
* - it preserves `state`, `goal`, `goalUpdatedAt`, `blocked_on`, `queued`,
|
|
962
|
+
* `turn`, `startedAt` and `ttlMs`: heartbeat says "this writer is still
|
|
963
|
+
* here", not "state changed". In particular the goal's own clock must not
|
|
964
|
+
* move, or the board could no longer tell a stale goal from a live one;
|
|
945
965
|
* - `lastAction:false` keeps `last_action` exactly as-is (the timer tick);
|
|
946
966
|
* otherwise only the action stamp is replaced, bounded like every other write.
|
|
947
967
|
*/
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
// src/memory/activity-capture.js — M2-B / §2.5:活动流并入统一事件模型
|
|
2
|
+
//
|
|
3
|
+
// 映射(提案 §2.5):
|
|
4
|
+
// board/activity.jsonl 行(doing/finding/blocked/done/结论)→ EventRecord(kind=activity|conclusion)
|
|
5
|
+
// 结论行 → 同时写 records.jsonl(kind='conclusion')
|
|
6
|
+
// .longlive/live/*.json 状态行 → EventRecord(kind=status)(时间线,默认不参与排序)
|
|
7
|
+
// goal/focus → records.jsonl(kind='goal', TTL)(status=active/expired)
|
|
8
|
+
//
|
|
9
|
+
// 只读原文件、写私有 .longlive;所有写入幂等(id+digest)。
|
|
10
|
+
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
|
|
15
|
+
import { stableStringify } from '../codec.js';
|
|
16
|
+
import { extractTerms } from './fts-query.js';
|
|
17
|
+
import { appendRecordLine, makeRecordId, upsertEventRecord } from './capture.js';
|
|
18
|
+
import { appendClaimFromRecord } from './governance.js';
|
|
19
|
+
import { evaluateEvidenceForWrite } from './records.js';
|
|
20
|
+
|
|
21
|
+
function sha1Short(text, length = 12) {
|
|
22
|
+
return crypto.createHash('sha1').update(text, 'utf8').digest('hex').slice(0, length);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function sha256Hex(text) {
|
|
26
|
+
return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function nowDate(now) {
|
|
30
|
+
const value = typeof now === 'function' ? now() : new Date();
|
|
31
|
+
return value instanceof Date ? value : new Date(value);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function createActivityCapture(options = {}) {
|
|
35
|
+
const memoryRoot = path.resolve(String(options.memoryRoot ?? ''));
|
|
36
|
+
if (memoryRoot === '') throw new Error('E_MEMORY_ROOT: activity-capture requires memoryRoot');
|
|
37
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date();
|
|
38
|
+
|
|
39
|
+
function captureBoardRow(row = {}) {
|
|
40
|
+
const at = Number(row.at ?? row.ts ?? row.time);
|
|
41
|
+
const text = String(row.text ?? row.message ?? row.content ?? '').trim();
|
|
42
|
+
if (text === '') return { ok: false, code: 'E_ACTIVITY_TEXT' };
|
|
43
|
+
const kind = row.kind === 'conclusion' ? 'conclusion' : 'activity';
|
|
44
|
+
const id = `evt:activity:${row.id ?? row.seq ?? sha1Short(`${at}|${text}`)}`;
|
|
45
|
+
const project = row.project ?? null;
|
|
46
|
+
const terms = extractTerms(text, [kind]);
|
|
47
|
+
const record = {
|
|
48
|
+
id,
|
|
49
|
+
sessionId: row.sessionId ?? 'activity',
|
|
50
|
+
turn: Number.isInteger(row.turn) ? row.turn : 0,
|
|
51
|
+
seqStart: Number.isInteger(row.seqStart) ? row.seqStart : null,
|
|
52
|
+
seqEnd: Number.isInteger(row.seqEnd) ? row.seqEnd : null,
|
|
53
|
+
timeStart: Number.isFinite(at) ? at : null,
|
|
54
|
+
timeEnd: Number.isFinite(at) ? at : null,
|
|
55
|
+
project,
|
|
56
|
+
kind,
|
|
57
|
+
topics: terms.filter((term) => /[\u3400-\u4dbf\u4e00-\u9fff]/.test(term)).slice(0, 5),
|
|
58
|
+
terms,
|
|
59
|
+
summary: text.slice(0, 400),
|
|
60
|
+
counts: {},
|
|
61
|
+
anchors: Array.isArray(row.anchors) ? row.anchors : [],
|
|
62
|
+
digest: sha256Hex(stableStringify({ at: Number.isFinite(at) ? at : null, text, kind })),
|
|
63
|
+
source: 'activity-capture',
|
|
64
|
+
};
|
|
65
|
+
const indexed = upsertEventRecord({ memoryRoot, now, record });
|
|
66
|
+
let assertion = null;
|
|
67
|
+
if (kind === 'conclusion') {
|
|
68
|
+
const createdAt = new Date(Number.isFinite(at) ? at : nowDate(now).getTime()).toISOString();
|
|
69
|
+
const recordId = makeRecordId({ content: text, createdAt, source: 'activity-conclusion' });
|
|
70
|
+
// EA-02:结论来源由服务端判定(活动流结论 = agent),不接受行内自报。
|
|
71
|
+
const sourceTier = 'agent';
|
|
72
|
+
const evidence = evaluateEvidenceForWrite(Array.isArray(row.anchors) ? row.anchors : [], { verifiedAt: createdAt }).evidence.map((entry) => ({ anchorId: entry.anchorId, sha256: entry.sha256, excerptRef: entry.excerptRef, verifiedAt: entry.verifiedAt, valid: entry.valid }));
|
|
73
|
+
assertion = appendRecordLine({
|
|
74
|
+
memoryRoot,
|
|
75
|
+
record: {
|
|
76
|
+
id: recordId,
|
|
77
|
+
kind: 'conclusion',
|
|
78
|
+
content: text,
|
|
79
|
+
subject: row.subject ?? null,
|
|
80
|
+
project,
|
|
81
|
+
salience: 4,
|
|
82
|
+
importance: 0.6,
|
|
83
|
+
status: 'active',
|
|
84
|
+
createdAt,
|
|
85
|
+
lastUsed: createdAt.slice(0, 10),
|
|
86
|
+
useCount: 0,
|
|
87
|
+
anchors: Array.isArray(row.anchors) ? row.anchors : [],
|
|
88
|
+
evidence,
|
|
89
|
+
sourceTier,
|
|
90
|
+
conflict: false,
|
|
91
|
+
conflict_with: [],
|
|
92
|
+
state: 'active',
|
|
93
|
+
anchorStatus: evidence.length > 0 ? 'live' : 'missing',
|
|
94
|
+
supersedes: [],
|
|
95
|
+
supersededBy: null,
|
|
96
|
+
audit: { createdBy: 'activity-capture', source: 'board-conclusion' },
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
if (assertion && assertion.written) {
|
|
101
|
+
try {
|
|
102
|
+
appendClaimFromRecord({ memoryRoot, record: { id: makeRecordId({ content: text, createdAt: new Date(Number.isFinite(at) ? at : nowDate(now).getTime()).toISOString(), source: 'activity-conclusion' }), kind: 'conclusion', content: text, subject: row.subject ?? null, project, salience: 4, createdAt: new Date(Number.isFinite(at) ? at : nowDate(now).getTime()).toISOString(), evidence: evaluateEvidenceForWrite(Array.isArray(row.anchors) ? row.anchors : []).evidence, sourceTier: 'agent', state: 'active' }, now });
|
|
103
|
+
} catch {
|
|
104
|
+
/* claim bridge best effort; records write already succeeded */
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return { ok: true, id, kind, indexed, assertion };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function captureBoardFile(activityPath = path.join(memoryRoot, '.longlive', 'board', 'activity.jsonl')) {
|
|
111
|
+
const out = { file: activityPath, rows: 0, inserted: 0, skipped: 0, conclusions: 0, errors: [] };
|
|
112
|
+
let text = '';
|
|
113
|
+
try {
|
|
114
|
+
text = fs.readFileSync(activityPath, 'utf8');
|
|
115
|
+
} catch {
|
|
116
|
+
return { ...out, code: 'E_ACTIVITY_FILE_MISSING' };
|
|
117
|
+
}
|
|
118
|
+
for (const line of text.split('\n')) {
|
|
119
|
+
if (line.trim() === '') continue;
|
|
120
|
+
let row = null;
|
|
121
|
+
try {
|
|
122
|
+
row = JSON.parse(line);
|
|
123
|
+
} catch {
|
|
124
|
+
out.errors.push({ code: 'E_ACTIVITY_JSON' });
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const result = captureBoardRow(row);
|
|
128
|
+
out.rows += 1;
|
|
129
|
+
if (result.indexed?.inserted) out.inserted += 1;
|
|
130
|
+
else out.skipped += 1;
|
|
131
|
+
if (result.kind === 'conclusion') out.conclusions += 1;
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function captureLiveRows(liveDir = path.join(memoryRoot, '.longlive', 'live')) {
|
|
137
|
+
const out = { dir: liveDir, files: 0, inserted: 0, skipped: 0, errors: [] };
|
|
138
|
+
let entries = [];
|
|
139
|
+
try {
|
|
140
|
+
entries = fs.readdirSync(liveDir, { withFileTypes: true });
|
|
141
|
+
} catch {
|
|
142
|
+
return { ...out, code: 'E_LIVE_DIR_MISSING' };
|
|
143
|
+
}
|
|
144
|
+
for (const entry of entries) {
|
|
145
|
+
if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
|
|
146
|
+
const file = path.join(liveDir, entry.name);
|
|
147
|
+
let row = null;
|
|
148
|
+
try {
|
|
149
|
+
row = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
150
|
+
} catch {
|
|
151
|
+
out.errors.push({ file: entry.name, code: 'E_LIVE_JSON' });
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
out.files += 1;
|
|
155
|
+
const sessionId = typeof row.sessionId === 'string' ? row.sessionId : entry.name.replace(/\.json$/, '');
|
|
156
|
+
const updatedAt = Number(row.updatedAt ?? row.at ?? 0);
|
|
157
|
+
const at = Number.isFinite(updatedAt) && updatedAt > 0 ? updatedAt : fs.statSync(file).mtimeMs;
|
|
158
|
+
const state = String(row.state ?? 'unknown');
|
|
159
|
+
const goal = String(row.goal ?? '');
|
|
160
|
+
const lastAction = row.lastAction ?? null;
|
|
161
|
+
const summary = `会话 ${sessionId} state=${state}${Number.isInteger(row.turn) ? ` turn=${row.turn}` : ''}`
|
|
162
|
+
+ `${goal ? ` goal=${goal}` : ''}${lastAction ? ` lastAction=${lastAction.kind ?? ''}` : ''}`;
|
|
163
|
+
const record = {
|
|
164
|
+
id: `evt:live:${sessionId}:${Math.round(at / 1000)}`,
|
|
165
|
+
sessionId,
|
|
166
|
+
turn: Number.isInteger(row.turn) ? row.turn : 0,
|
|
167
|
+
seqStart: null,
|
|
168
|
+
seqEnd: null,
|
|
169
|
+
timeStart: at,
|
|
170
|
+
timeEnd: at,
|
|
171
|
+
project: row.project ?? null,
|
|
172
|
+
kind: 'status',
|
|
173
|
+
topics: ['live', 'status'],
|
|
174
|
+
terms: [state, ...(goal !== '' ? [goal] : [])].slice(0, 20),
|
|
175
|
+
summary: summary.slice(0, 400),
|
|
176
|
+
counts: {},
|
|
177
|
+
anchors: [],
|
|
178
|
+
digest: sha256Hex(stableStringify({ sessionId, state, turn: row.turn ?? null, goal, lastAction, at })),
|
|
179
|
+
source: 'activity-capture',
|
|
180
|
+
};
|
|
181
|
+
const indexed = upsertEventRecord({ memoryRoot, now, record });
|
|
182
|
+
if (indexed.inserted) out.inserted += 1;
|
|
183
|
+
else out.skipped += 1;
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function captureGoal(goal = {}) {
|
|
189
|
+
const text = String(goal.text ?? '').trim();
|
|
190
|
+
if (text === '') return { ok: false, code: 'E_GOAL_TEXT' };
|
|
191
|
+
const at = Number.isFinite(goal.at) ? goal.at : nowDate(now).getTime();
|
|
192
|
+
const createdAt = new Date(at).toISOString();
|
|
193
|
+
const record = {
|
|
194
|
+
id: makeRecordId({ content: text, createdAt, source: 'goal' }),
|
|
195
|
+
kind: 'goal',
|
|
196
|
+
content: text,
|
|
197
|
+
subject: goal.subject ?? null,
|
|
198
|
+
project: goal.project ?? null,
|
|
199
|
+
salience: 4,
|
|
200
|
+
importance: 0.7,
|
|
201
|
+
status: goal.status === 'expired' ? 'expired' : 'active',
|
|
202
|
+
createdAt,
|
|
203
|
+
lastUsed: createdAt.slice(0, 10),
|
|
204
|
+
useCount: 0,
|
|
205
|
+
anchors: Array.isArray(goal.anchors) ? goal.anchors : [],
|
|
206
|
+
evidence: evaluateEvidenceForWrite(Array.isArray(goal.anchors) ? goal.anchors : []).evidence,
|
|
207
|
+
sourceTier: 'host', // EA-02:目标由宿主运行时写入,服务端判定
|
|
208
|
+
conflict: false,
|
|
209
|
+
conflict_with: [],
|
|
210
|
+
state: 'active',
|
|
211
|
+
anchorStatus: 'missing',
|
|
212
|
+
supersedes: [],
|
|
213
|
+
supersededBy: null,
|
|
214
|
+
ttlDays: Number.isInteger(goal.ttlDays) ? goal.ttlDays : 7,
|
|
215
|
+
audit: { createdBy: 'activity-capture', source: 'goal-focus' },
|
|
216
|
+
};
|
|
217
|
+
const written = appendRecordLine({ memoryRoot, record });
|
|
218
|
+
return { ok: true, id: record.id, written: written.written };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function captureAll(input = {}) {
|
|
222
|
+
return {
|
|
223
|
+
board: captureBoardFile(input.activityPath),
|
|
224
|
+
live: captureLiveRows(input.liveDir),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return { memoryRoot, captureBoardRow, captureBoardFile, captureLiveRows, captureGoal, captureAll };
|
|
229
|
+
}
|