@jjh32456/longlive 0.0.0-stage → 1.8.12
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 +205 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +363 -0
- package/README.en.md +55 -0
- package/README.md +225 -2
- package/SPEC.md +211 -0
- package/build-info.json +1555 -0
- package/cordis.patch.yml +177 -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 +807 -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 +46 -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 +160 -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-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/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 +146 -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 +824 -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 +912 -0
- package/src/handoff/index.js +944 -0
- package/src/handoff/model.js +1010 -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 +657 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +131 -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 +124 -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/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +228 -0
- package/src/memory/capture.js +457 -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/conclusion-distill.js +332 -0
- package/src/memory/conclusion-drafts.js +239 -0
- package/src/memory/conflicts.js +147 -0
- package/src/memory/consolidate.js +815 -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 +410 -0
- package/src/memory/forget.js +512 -0
- package/src/memory/frames-activation.js +247 -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 +362 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/lifecycle.js +107 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +785 -0
- package/src/memory/manifest.js +245 -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.js +963 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-v2.js +206 -0
- package/src/memory/recall.js +256 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +145 -0
- package/src/memory/retention.js +128 -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/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 +189 -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-fallback.mjs +235 -0
- package/src/recall/archive-search.mjs +425 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/edges.js +379 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +433 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/index.js +1036 -0
- package/src/recall/inject-order.mjs +277 -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 +765 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/retention/config.js +106 -0
- package/src/retention/index.js +643 -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 +3146 -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,785 @@
|
|
|
1
|
+
// Daily memory maintenance (feature batch 2026-11-05, B1/B2).
|
|
2
|
+
//
|
|
3
|
+
// B1: once per local calendar day, run `memory_consolidate` (report only; it
|
|
4
|
+
// never edits a card) and record the result.
|
|
5
|
+
// B2: once per local calendar day, run `memory_forget` with NO `confirm`, i.e.
|
|
6
|
+
// the dry-run branch, and write a human-readable pending list. There is no
|
|
7
|
+
// code path here that can move, delete or rewrite a card: the confirm word
|
|
8
|
+
// is never supplied by this module.
|
|
9
|
+
//
|
|
10
|
+
// Triggering is deliberately cheap: one unref'd `setTimeout` to the next local
|
|
11
|
+
// midnight, re-armed after each run, plus one catch-up run at plugin start.
|
|
12
|
+
// There is no polling loop and no per-turn hook, so a failed run cannot affect
|
|
13
|
+
// a turn. Every failure is caught, recorded in the schedule state and at most
|
|
14
|
+
// logged as one warning.
|
|
15
|
+
//
|
|
16
|
+
// Shared state lives at `<memoryRoot>/.longlive/bridge/schedule.json` with
|
|
17
|
+
// `lastConsolidateDate` / `lastForgetDate` as the per-day idempotency keys.
|
|
18
|
+
// Reports live in `<memoryRoot>/.longlive/reports/`:
|
|
19
|
+
// consolidate-<YYYY-MM-DD>.md (written by memoryConsolidate)
|
|
20
|
+
// forget-pending-<YYYYMMDD>.md (written here)
|
|
21
|
+
|
|
22
|
+
import fs from 'node:fs';
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
|
|
25
|
+
import { dayString, isoStamp } from './frontmatter.js';
|
|
26
|
+
import { memoryRootFromConfig, resolveInside, relativePath } from './paths.js';
|
|
27
|
+
import { ensureDir, writeFileAtomic } from './state.js';
|
|
28
|
+
import { memoryConsolidate } from './consolidate.js';
|
|
29
|
+
import { memoryForget } from './forget.js';
|
|
30
|
+
import { runConclusionDistillJob } from './conclusion-distill.js';
|
|
31
|
+
|
|
32
|
+
export const SCHEDULE_VERSION = 1;
|
|
33
|
+
export const SCHEDULE_REL = path.join('.longlive', 'bridge', 'schedule.json');
|
|
34
|
+
export const LOCK_REL = path.join('.longlive', 'bridge', 'schedule.lock');
|
|
35
|
+
export const PENDING_REPORT_PREFIX = 'forget-pending-';
|
|
36
|
+
export const RUN_HISTORY_LIMIT = 30;
|
|
37
|
+
export const DEFAULT_START_DELAY_MS = 500;
|
|
38
|
+
export const MIDNIGHT_PAD_MS = 1000;
|
|
39
|
+
const LOCK_STALE_MS = 10 * 60 * 1000;
|
|
40
|
+
|
|
41
|
+
export const AUTO_MAINTENANCE_DEFAULTS = Object.freeze({
|
|
42
|
+
enabled: false,
|
|
43
|
+
consolidate: true,
|
|
44
|
+
forget: true,
|
|
45
|
+
runOnStart: true,
|
|
46
|
+
startDelayMs: DEFAULT_START_DELAY_MS,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
50
|
+
|
|
51
|
+
function isDay(value) {
|
|
52
|
+
return typeof value === 'string' && DAY_RE.test(value.trim());
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function errorInfo(error) {
|
|
56
|
+
return {
|
|
57
|
+
code: error?.code ?? 'E_MAINTENANCE_FAILED',
|
|
58
|
+
message: String(error?.message ?? error),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function warnTo(logger, message) {
|
|
63
|
+
try {
|
|
64
|
+
if (typeof logger === 'function') logger(message);
|
|
65
|
+
else if (logger && typeof logger.warn === 'function') logger.warn(message);
|
|
66
|
+
} catch {
|
|
67
|
+
/* a logger failure must never break maintenance */
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function toClock(now) {
|
|
72
|
+
if (typeof now === 'function') {
|
|
73
|
+
return () => {
|
|
74
|
+
const value = now();
|
|
75
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
76
|
+
return Number.isNaN(date.getTime()) ? new Date() : date;
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
if (now instanceof Date) {
|
|
80
|
+
return () => new Date(now.getTime());
|
|
81
|
+
}
|
|
82
|
+
return () => new Date();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function emptyState() {
|
|
86
|
+
return {
|
|
87
|
+
version: SCHEDULE_VERSION,
|
|
88
|
+
lastConsolidateDate: null,
|
|
89
|
+
lastConsolidateAt: null,
|
|
90
|
+
lastConsolidateReport: null,
|
|
91
|
+
lastConsolidateProposals: null,
|
|
92
|
+
lastConsolidateError: null,
|
|
93
|
+
lastForgetDate: null,
|
|
94
|
+
lastForgetAt: null,
|
|
95
|
+
lastForgetPending: null,
|
|
96
|
+
lastForgetPendingCount: null,
|
|
97
|
+
lastForgetError: null,
|
|
98
|
+
lastConclusionDistillDate: null,
|
|
99
|
+
lastConclusionDistillAt: null,
|
|
100
|
+
lastConclusionDistillResult: null,
|
|
101
|
+
lastConclusionDistillError: null,
|
|
102
|
+
lastRunAt: null,
|
|
103
|
+
lastRunDay: null,
|
|
104
|
+
lastTrigger: null,
|
|
105
|
+
runs: [],
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function normalizeState(raw) {
|
|
110
|
+
const state = emptyState();
|
|
111
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return state;
|
|
112
|
+
state.lastConsolidateDate = isDay(raw.lastConsolidateDate) ? raw.lastConsolidateDate : null;
|
|
113
|
+
state.lastForgetDate = isDay(raw.lastForgetDate) ? raw.lastForgetDate : null;
|
|
114
|
+
state.lastConclusionDistillDate = isDay(raw.lastConclusionDistillDate) ? raw.lastConclusionDistillDate : null;
|
|
115
|
+
for (const key of [
|
|
116
|
+
'lastConsolidateAt', 'lastConsolidateReport',
|
|
117
|
+
'lastForgetAt', 'lastForgetPending',
|
|
118
|
+
'lastConclusionDistillAt',
|
|
119
|
+
'lastRunAt', 'lastRunDay', 'lastTrigger',
|
|
120
|
+
]) {
|
|
121
|
+
if (raw[key] == null || typeof raw[key] === 'string') state[key] = raw[key] ?? null;
|
|
122
|
+
}
|
|
123
|
+
for (const key of ['lastConsolidateError', 'lastForgetError', 'lastConclusionDistillError']) {
|
|
124
|
+
const value = raw[key];
|
|
125
|
+
if (value == null) {
|
|
126
|
+
state[key] = null;
|
|
127
|
+
} else if (typeof value === 'string') {
|
|
128
|
+
state[key] = { code: 'E_MAINTENANCE_FAILED', message: value };
|
|
129
|
+
} else if (typeof value === 'object' && !Array.isArray(value)) {
|
|
130
|
+
state[key] = {
|
|
131
|
+
code: typeof value.code === 'string' ? value.code : 'E_MAINTENANCE_FAILED',
|
|
132
|
+
message: typeof value.message === 'string' ? value.message : '',
|
|
133
|
+
...(typeof value.at === 'string' ? { at: value.at } : {}),
|
|
134
|
+
...(typeof value.day === 'string' ? { day: value.day } : {}),
|
|
135
|
+
};
|
|
136
|
+
} else {
|
|
137
|
+
state[key] = null;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
for (const key of ['lastConsolidateProposals', 'lastForgetPendingCount']) {
|
|
141
|
+
if (Number.isFinite(raw[key])) state[key] = raw[key];
|
|
142
|
+
}
|
|
143
|
+
state.lastConclusionDistillResult = raw.lastConclusionDistillResult
|
|
144
|
+
&& typeof raw.lastConclusionDistillResult === 'object'
|
|
145
|
+
&& !Array.isArray(raw.lastConclusionDistillResult)
|
|
146
|
+
? {
|
|
147
|
+
archived: Number(raw.lastConclusionDistillResult.archived) || 0,
|
|
148
|
+
distilled: Number(raw.lastConclusionDistillResult.distilled) || 0,
|
|
149
|
+
rejected: Number(raw.lastConclusionDistillResult.rejected) || 0,
|
|
150
|
+
skipped: Number(raw.lastConclusionDistillResult.skipped) || 0,
|
|
151
|
+
}
|
|
152
|
+
: null;
|
|
153
|
+
state.runs = Array.isArray(raw.runs)
|
|
154
|
+
? raw.runs.filter((entry) => entry && typeof entry === 'object').slice(-RUN_HISTORY_LIMIT)
|
|
155
|
+
: [];
|
|
156
|
+
return state;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function scheduleStatePath(root) {
|
|
160
|
+
return resolveInside(root, SCHEDULE_REL);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function lockPathFor(root) {
|
|
164
|
+
return resolveInside(root, LOCK_REL);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Best-effort cross-process guard. Multiple sessions can share one memoryRoot;
|
|
169
|
+
* without this, two startup ticks could both run the same day's jobs. The lock
|
|
170
|
+
* is advisory and stale after 10 minutes, so a crashed process cannot block
|
|
171
|
+
* maintenance forever.
|
|
172
|
+
*/
|
|
173
|
+
function acquireLock(root, { now = new Date() } = {}) {
|
|
174
|
+
const file = lockPathFor(root);
|
|
175
|
+
ensureDir(root, path.dirname(file));
|
|
176
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
177
|
+
try {
|
|
178
|
+
const fd = fs.openSync(file, 'wx');
|
|
179
|
+
try {
|
|
180
|
+
fs.writeSync(fd, JSON.stringify({
|
|
181
|
+
pid: process.pid,
|
|
182
|
+
at: isoStamp(now),
|
|
183
|
+
day: dayString(now),
|
|
184
|
+
}));
|
|
185
|
+
} finally {
|
|
186
|
+
fs.closeSync(fd);
|
|
187
|
+
}
|
|
188
|
+
return {
|
|
189
|
+
acquired: true,
|
|
190
|
+
path: file,
|
|
191
|
+
release: () => {
|
|
192
|
+
try {
|
|
193
|
+
fs.unlinkSync(file);
|
|
194
|
+
} catch {
|
|
195
|
+
/* already gone */
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
} catch (error) {
|
|
200
|
+
if (error?.code !== 'EEXIST') {
|
|
201
|
+
return { acquired: false, reason: 'lock-error', error: errorInfo(error) };
|
|
202
|
+
}
|
|
203
|
+
let stat;
|
|
204
|
+
try {
|
|
205
|
+
stat = fs.statSync(file);
|
|
206
|
+
} catch {
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (Date.now() - stat.mtimeMs > LOCK_STALE_MS) {
|
|
210
|
+
try {
|
|
211
|
+
fs.unlinkSync(file);
|
|
212
|
+
} catch {
|
|
213
|
+
/* raced with another cleaner; retry */
|
|
214
|
+
}
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
let holder = null;
|
|
218
|
+
try {
|
|
219
|
+
holder = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
220
|
+
} catch {
|
|
221
|
+
/* unreadable holder is still a live lock */
|
|
222
|
+
}
|
|
223
|
+
return { acquired: false, reason: 'locked', holder };
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return { acquired: false, reason: 'locked' };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Read the schedule state. A missing file is an empty state; a corrupt file is
|
|
231
|
+
* reported (never thrown) and is backed up by the next atomic write.
|
|
232
|
+
*/
|
|
233
|
+
export function readScheduleState(root) {
|
|
234
|
+
const file = scheduleStatePath(root);
|
|
235
|
+
let text;
|
|
236
|
+
try {
|
|
237
|
+
text = fs.readFileSync(file, 'utf8');
|
|
238
|
+
} catch (error) {
|
|
239
|
+
if (error?.code === 'ENOENT') {
|
|
240
|
+
return { state: emptyState(), exists: false, corrupt: false, error: null, path: file };
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
state: emptyState(),
|
|
244
|
+
exists: true,
|
|
245
|
+
corrupt: true,
|
|
246
|
+
error: errorInfo(error),
|
|
247
|
+
path: file,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
try {
|
|
251
|
+
const raw = JSON.parse(text);
|
|
252
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
253
|
+
throw new Error('schedule.json 必须是对象');
|
|
254
|
+
}
|
|
255
|
+
return { state: normalizeState(raw), exists: true, corrupt: false, error: null, path: file };
|
|
256
|
+
} catch (error) {
|
|
257
|
+
return {
|
|
258
|
+
state: emptyState(),
|
|
259
|
+
exists: true,
|
|
260
|
+
corrupt: true,
|
|
261
|
+
error: errorInfo(error),
|
|
262
|
+
path: file,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function writeScheduleState(root, state, { now = new Date() } = {}) {
|
|
268
|
+
const file = scheduleStatePath(root);
|
|
269
|
+
ensureDir(root, path.dirname(file));
|
|
270
|
+
const next = normalizeState(state);
|
|
271
|
+
next.version = SCHEDULE_VERSION;
|
|
272
|
+
next.updatedAt = isoStamp(now);
|
|
273
|
+
const write = writeFileAtomic(root, file, `${JSON.stringify(next, null, 2)}\n`, { backup: true, now });
|
|
274
|
+
return { state: next, write };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Next local midnight (+ a small pad so dayString() has already changed). */
|
|
278
|
+
export function nextLocalMidnight(now = new Date(), padMs = MIDNIGHT_PAD_MS) {
|
|
279
|
+
const base = now instanceof Date ? now : new Date(now);
|
|
280
|
+
const next = new Date(base.getFullYear(), base.getMonth(), base.getDate() + 1, 0, 0, 0, 0);
|
|
281
|
+
const pad = Number.isFinite(padMs) && padMs > 0 ? Math.floor(padMs) : 0;
|
|
282
|
+
next.setTime(next.getTime() + pad);
|
|
283
|
+
return next;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function compactDay(day) {
|
|
287
|
+
return String(day).replaceAll('-', '');
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function pendingReportPath(root, day) {
|
|
291
|
+
return resolveInside(root, path.join('.longlive', 'reports', `${PENDING_REPORT_PREFIX}${compactDay(day)}.md`));
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Write the pending list. If today's file already exists (e.g. a manual rerun
|
|
296
|
+
* after a state-write failure), keep a copy in reports/.backups first, matching
|
|
297
|
+
* the memoryConsolidate convention.
|
|
298
|
+
*/
|
|
299
|
+
function writePendingReport(root, file, content, { now = new Date() } = {}) {
|
|
300
|
+
ensureDir(root, path.dirname(file));
|
|
301
|
+
if (fs.existsSync(file)) {
|
|
302
|
+
const backupDir = resolveInside(root, path.join('.longlive', 'reports', '.backups'));
|
|
303
|
+
ensureDir(root, backupDir);
|
|
304
|
+
const stamp = isoStamp(now).replace(/[:.]/g, '-');
|
|
305
|
+
const stem = path.basename(file, '.md');
|
|
306
|
+
let name = `${stem}.${stamp}.md`;
|
|
307
|
+
for (let suffix = 2; fs.existsSync(path.join(backupDir, name)); suffix += 1) {
|
|
308
|
+
name = `${stem}.${stamp}-${suffix}.md`;
|
|
309
|
+
}
|
|
310
|
+
fs.copyFileSync(file, path.join(backupDir, name));
|
|
311
|
+
}
|
|
312
|
+
return writeFileAtomic(root, file, content, { backup: false, now });
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function kindLabel(kind) {
|
|
316
|
+
if (kind === 'tombstone') return '立碑(tombstone)';
|
|
317
|
+
if (kind === 'epochs') return '降级(epochs)';
|
|
318
|
+
return String(kind ?? '未知');
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Render the B2 pending list. Pure: takes the dry-run result and returns text.
|
|
323
|
+
* Deliberately repeats the confirm requirement so a human never mistakes this
|
|
324
|
+
* file for an executed forget run.
|
|
325
|
+
*/
|
|
326
|
+
export function renderForgetPending({ day, at = new Date(), result = {} } = {}) {
|
|
327
|
+
const proposals = Array.isArray(result.proposals) ? result.proposals : [];
|
|
328
|
+
const immune = Array.isArray(result.immune) ? result.immune : [];
|
|
329
|
+
const undated = Array.isArray(result.undated) ? result.undated : [];
|
|
330
|
+
const missing = Array.isArray(result.scaffold?.missing) ? result.scaffold.missing : [];
|
|
331
|
+
const tombstones = proposals.filter((item) => item.kind === 'tombstone').length;
|
|
332
|
+
const epochs = proposals.filter((item) => item.kind === 'epochs').length;
|
|
333
|
+
const scanned = Number.isFinite(result.scanned) ? result.scanned : 0;
|
|
334
|
+
const lines = [];
|
|
335
|
+
|
|
336
|
+
lines.push(`# 遗忘提案待确认 · ${day}`, '');
|
|
337
|
+
lines.push(
|
|
338
|
+
'> 本文件由每日自动维护任务对 `memory_forget` 执行的 dry-run 生成:**没有移动、删除或改写任何卡片**。',
|
|
339
|
+
`> 真正执行仍需人工显式确认 \`confirm:"FORGET"\`;自动任务不会触发执行。`,
|
|
340
|
+
'',
|
|
341
|
+
);
|
|
342
|
+
lines.push(`- 生成时间:${isoStamp(at)}`);
|
|
343
|
+
lines.push(`- 扫描卡片:${scanned}`);
|
|
344
|
+
lines.push(`- 待确认提案:${proposals.length}(立碑 ${tombstones} / 降级 ${epochs})`);
|
|
345
|
+
lines.push(`- 核心记忆免疫:${immune.length}`);
|
|
346
|
+
lines.push(`- 无 last_used 跳过:${undated.length}`);
|
|
347
|
+
lines.push(`- 脚手架:${missing.length ? `缺 ${missing.join('/')}` : '齐全'}`);
|
|
348
|
+
lines.push('');
|
|
349
|
+
|
|
350
|
+
if (proposals.length === 0) {
|
|
351
|
+
lines.push('今天没有到期的遗忘提案。', '');
|
|
352
|
+
} else {
|
|
353
|
+
lines.push('## 待确认提案', '');
|
|
354
|
+
proposals.forEach((item, index) => {
|
|
355
|
+
lines.push(`### ${index + 1}. \`${item.path}\``, '');
|
|
356
|
+
lines.push(`- 动作:${kindLabel(item.kind)}`);
|
|
357
|
+
lines.push(
|
|
358
|
+
`- 年龄:${item.ageDays ?? '—'} 天` +
|
|
359
|
+
`(last_used: ${item.last_used ?? '—'},strength: ${item.strength ?? '—'},salience: ${item.salience ?? '—'})`,
|
|
360
|
+
);
|
|
361
|
+
lines.push(`- 依据:${item.reason ?? '—'}`);
|
|
362
|
+
lines.push(`- 目标位置:\`${item.destRel ?? '—'}\``);
|
|
363
|
+
if (item.epitaph && typeof item.epitaph === 'object') {
|
|
364
|
+
lines.push('- 墓志铭:');
|
|
365
|
+
lines.push(` - 为什么关:${item.epitaph.reason ?? '—'}`);
|
|
366
|
+
lines.push(` - 影响谁:${item.epitaph.affects ?? '—'}`);
|
|
367
|
+
lines.push(` - 还有用吗:${item.epitaph.stillUseful ?? '—'}`);
|
|
368
|
+
}
|
|
369
|
+
lines.push('');
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (immune.length > 0) {
|
|
374
|
+
lines.push('## 免疫(未列入提案)', '');
|
|
375
|
+
lines.push('| 卡片 | 状态 | 原因 |');
|
|
376
|
+
lines.push('|---|---|---|');
|
|
377
|
+
for (const item of immune) {
|
|
378
|
+
lines.push(`| \`${item.path}\` | ${item.status ?? 'active'} | ${item.reason ?? '—'} |`);
|
|
379
|
+
}
|
|
380
|
+
lines.push('');
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
if (undated.length > 0) {
|
|
384
|
+
lines.push('## 无日期跳过', '');
|
|
385
|
+
for (const item of undated) {
|
|
386
|
+
lines.push(`- \`${item.path}\` — ${item.reason ?? '没有可用的 last_used'}`);
|
|
387
|
+
}
|
|
388
|
+
lines.push('');
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
lines.push(
|
|
392
|
+
'---',
|
|
393
|
+
'',
|
|
394
|
+
'确认方式:人工核对本清单后,调用 `memory_forget` 并传 `confirm:"FORGET"`。',
|
|
395
|
+
'自动维护只产生本清单;没有卡被移动、删除或改写。',
|
|
396
|
+
'',
|
|
397
|
+
);
|
|
398
|
+
return lines.join('\n');
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Run the daily jobs once. Both jobs are independent: one failing does not stop
|
|
403
|
+
* the other, and neither failure is thrown to the caller. A job is skipped when
|
|
404
|
+
* its `last*Date` already equals today's local date.
|
|
405
|
+
*
|
|
406
|
+
* Returns a plain summary:
|
|
407
|
+
* { ok, ran, day, trigger, consolidate, forget, state, corruptState?, stateError? }
|
|
408
|
+
*/
|
|
409
|
+
export function runDailyMaintenance({
|
|
410
|
+
memoryRoot,
|
|
411
|
+
config = {},
|
|
412
|
+
now = new Date(),
|
|
413
|
+
logger = null,
|
|
414
|
+
trigger = 'manual',
|
|
415
|
+
consolidate = memoryConsolidate,
|
|
416
|
+
forget = memoryForget,
|
|
417
|
+
} = {}) {
|
|
418
|
+
let root;
|
|
419
|
+
try {
|
|
420
|
+
root = memoryRoot ? path.resolve(memoryRoot) : memoryRootFromConfig(config);
|
|
421
|
+
} catch (error) {
|
|
422
|
+
return { ok: false, ran: false, reason: 'no-memory-root', error: errorInfo(error) };
|
|
423
|
+
}
|
|
424
|
+
if (!root) return { ok: false, ran: false, reason: 'no-memory-root' };
|
|
425
|
+
|
|
426
|
+
const at = now instanceof Date ? now : new Date(now);
|
|
427
|
+
if (Number.isNaN(at.getTime())) return { ok: false, ran: false, reason: 'bad-clock' };
|
|
428
|
+
const day = isDay(config.today) ? config.today.trim() : dayString(at);
|
|
429
|
+
const wantConsolidate = config.consolidate !== false;
|
|
430
|
+
const wantForget = config.forget !== false;
|
|
431
|
+
const wantDrafts = config.autoConclusion !== false;
|
|
432
|
+
if (!wantConsolidate && !wantForget && !wantDrafts) {
|
|
433
|
+
return { ok: true, ran: false, reason: 'disabled', day, trigger };
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const summary = {
|
|
437
|
+
ok: true,
|
|
438
|
+
ran: false,
|
|
439
|
+
day,
|
|
440
|
+
trigger,
|
|
441
|
+
consolidate: null,
|
|
442
|
+
forget: null,
|
|
443
|
+
conclusionDistill: null,
|
|
444
|
+
state: null,
|
|
445
|
+
corruptState: false,
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
let read;
|
|
449
|
+
try {
|
|
450
|
+
read = readScheduleState(root);
|
|
451
|
+
} catch (error) {
|
|
452
|
+
return { ...summary, ok: false, reason: 'state-unreadable', error: errorInfo(error) };
|
|
453
|
+
}
|
|
454
|
+
summary.corruptState = read.corrupt;
|
|
455
|
+
if (read.corrupt) {
|
|
456
|
+
warnTo(
|
|
457
|
+
logger,
|
|
458
|
+
`[auto-maintenance] schedule.json 不可读(${read.error?.code ?? 'E_STATE_CORRUPT'})— 按空状态继续,下一次写入会先备份旧文件`,
|
|
459
|
+
);
|
|
460
|
+
}
|
|
461
|
+
let state = read.state;
|
|
462
|
+
|
|
463
|
+
let needConsolidate = wantConsolidate && state.lastConsolidateDate !== day;
|
|
464
|
+
let needForget = wantForget && state.lastForgetDate !== day;
|
|
465
|
+
let needDrafts = wantDrafts && state.lastConclusionDistillDate !== day;
|
|
466
|
+
if (!needConsolidate && !needForget && !needDrafts) {
|
|
467
|
+
return { ...summary, reason: 'already-ran-today', state };
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const lock = acquireLock(root, { now: at });
|
|
471
|
+
if (!lock.acquired) {
|
|
472
|
+
return {
|
|
473
|
+
...summary,
|
|
474
|
+
reason: lock.reason === 'lock-error' ? 'lock-error' : 'locked',
|
|
475
|
+
lock: lock.holder ?? null,
|
|
476
|
+
error: lock.error,
|
|
477
|
+
state,
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
try {
|
|
482
|
+
// Re-read after taking the lock: another session may have finished the
|
|
483
|
+
// same day's jobs between our first read and the lock acquisition.
|
|
484
|
+
const latest = readScheduleState(root);
|
|
485
|
+
if (latest.corrupt) summary.corruptState = true;
|
|
486
|
+
state = latest.state;
|
|
487
|
+
needConsolidate = wantConsolidate && state.lastConsolidateDate !== day;
|
|
488
|
+
needForget = wantForget && state.lastForgetDate !== day;
|
|
489
|
+
needDrafts = wantDrafts && state.lastConclusionDistillDate !== day;
|
|
490
|
+
if (!needConsolidate && !needForget && !needDrafts) {
|
|
491
|
+
return { ...summary, reason: 'already-ran-today', state };
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// ---- B1: consolidate (report only) ------------------------------------
|
|
495
|
+
if (needConsolidate) {
|
|
496
|
+
try {
|
|
497
|
+
const result = consolidate({}, { memoryRoot: root, now: at });
|
|
498
|
+
const proposals = Array.isArray(result?.proposals) ? result.proposals.length : 0;
|
|
499
|
+
summary.consolidate = {
|
|
500
|
+
status: 'ran',
|
|
501
|
+
reportRel: result?.reportRel ?? null,
|
|
502
|
+
proposals,
|
|
503
|
+
stateUpdated: result?.stateUpdated === true,
|
|
504
|
+
};
|
|
505
|
+
state.lastConsolidateDate = day;
|
|
506
|
+
state.lastConsolidateAt = isoStamp(at);
|
|
507
|
+
state.lastConsolidateReport = summary.consolidate.reportRel;
|
|
508
|
+
state.lastConsolidateProposals = proposals;
|
|
509
|
+
state.lastConsolidateError = null;
|
|
510
|
+
} catch (error) {
|
|
511
|
+
summary.consolidate = { status: 'failed', ...errorInfo(error) };
|
|
512
|
+
state.lastConsolidateError = { ...errorInfo(error), at: isoStamp(at), day };
|
|
513
|
+
warnTo(
|
|
514
|
+
logger,
|
|
515
|
+
`[auto-maintenance] consolidate 失败(${summary.consolidate.code})— ${summary.consolidate.message};已跳过,不影响对话`,
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// ---- B2: forget dry-run + pending list --------------------------------
|
|
521
|
+
if (needForget) {
|
|
522
|
+
try {
|
|
523
|
+
// `{}` means no confirm -> memoryForget's dry-run branch. The guard below
|
|
524
|
+
// is defensive: if a future refactor ever makes this write cards, the
|
|
525
|
+
// scheduler reports a failure instead of silently applying a forget.
|
|
526
|
+
const result = forget({}, { memoryRoot: root, now: at });
|
|
527
|
+
if (!result || result.dryRun !== true || result.applied === true) {
|
|
528
|
+
const error = new Error('memory_forget 调度必须停留在 dry-run');
|
|
529
|
+
error.code = 'E_MAINTENANCE_DRYRUN_REQUIRED';
|
|
530
|
+
throw error;
|
|
531
|
+
}
|
|
532
|
+
const file = pendingReportPath(root, day);
|
|
533
|
+
const content = renderForgetPending({ day, at, result });
|
|
534
|
+
const write = writePendingReport(root, file, content, { now: at });
|
|
535
|
+
const pending = Array.isArray(result.proposals) ? result.proposals.length : 0;
|
|
536
|
+
summary.forget = {
|
|
537
|
+
status: 'ran',
|
|
538
|
+
pending,
|
|
539
|
+
pendingRel: relativePath(root, file),
|
|
540
|
+
immune: Array.isArray(result.immune) ? result.immune.length : 0,
|
|
541
|
+
undated: Array.isArray(result.undated) ? result.undated.length : 0,
|
|
542
|
+
sha256: write.sha256,
|
|
543
|
+
};
|
|
544
|
+
state.lastForgetDate = day;
|
|
545
|
+
state.lastForgetAt = isoStamp(at);
|
|
546
|
+
state.lastForgetPending = summary.forget.pendingRel;
|
|
547
|
+
state.lastForgetPendingCount = pending;
|
|
548
|
+
state.lastForgetError = null;
|
|
549
|
+
} catch (error) {
|
|
550
|
+
summary.forget = { status: 'failed', ...errorInfo(error) };
|
|
551
|
+
state.lastForgetError = { ...errorInfo(error), at: isoStamp(at), day };
|
|
552
|
+
warnTo(
|
|
553
|
+
logger,
|
|
554
|
+
`[auto-maintenance] forget dry-run 失败(${summary.forget.code})— ${summary.forget.message};卡未改动,不影响对话`,
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// ---- B3: A1 conclusion drafts -> distilled topic cards -----------------
|
|
560
|
+
// Distillation is a maintenance concern: raw A1 output stays in the draft
|
|
561
|
+
// pool; only validated, source-anchored extracts reach topics/. A failure
|
|
562
|
+
// here is recorded and audited but never thrown to the caller.
|
|
563
|
+
if (needDrafts) {
|
|
564
|
+
try {
|
|
565
|
+
const result = runConclusionDistillJob({
|
|
566
|
+
memoryRoot: root, config, now: at,
|
|
567
|
+
sessionsRoot: config.sessionsRoot,
|
|
568
|
+
});
|
|
569
|
+
summary.conclusionDistill = { status: 'ran', ...result };
|
|
570
|
+
state.lastConclusionDistillDate = day;
|
|
571
|
+
state.lastConclusionDistillAt = isoStamp(at);
|
|
572
|
+
state.lastConclusionDistillResult = {
|
|
573
|
+
archived: result.archived ?? 0,
|
|
574
|
+
distilled: result.distilled ?? 0,
|
|
575
|
+
rejected: result.rejected ?? 0,
|
|
576
|
+
skipped: result.skipped ?? 0,
|
|
577
|
+
};
|
|
578
|
+
state.lastConclusionDistillError = null;
|
|
579
|
+
} catch (error) {
|
|
580
|
+
summary.conclusionDistill = { status: 'failed', ...errorInfo(error) };
|
|
581
|
+
state.lastConclusionDistillError = { ...errorInfo(error), at: isoStamp(at), day };
|
|
582
|
+
warnTo(
|
|
583
|
+
logger,
|
|
584
|
+
`[auto-maintenance] conclusion distill 失败(${summary.conclusionDistill.code})— ${summary.conclusionDistill.message};候选保留,不影响对话`,
|
|
585
|
+
);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// ---- state -------------------------------------------------------------
|
|
590
|
+
if (!summary.consolidate && !summary.forget && !summary.conclusionDistill) {
|
|
591
|
+
return { ...summary, reason: 'nothing-to-do', state };
|
|
592
|
+
}
|
|
593
|
+
summary.ran = true;
|
|
594
|
+
state.lastRunAt = isoStamp(at);
|
|
595
|
+
state.lastRunDay = day;
|
|
596
|
+
state.lastTrigger = trigger;
|
|
597
|
+
state.runs = [
|
|
598
|
+
...(Array.isArray(state.runs) ? state.runs : []),
|
|
599
|
+
{
|
|
600
|
+
at: isoStamp(at),
|
|
601
|
+
day,
|
|
602
|
+
trigger,
|
|
603
|
+
consolidate: summary.consolidate?.status ?? 'skipped',
|
|
604
|
+
forget: summary.forget?.status ?? 'skipped',
|
|
605
|
+
...(summary.consolidate?.status === 'ran' ? { consolidateReport: summary.consolidate.reportRel } : {}),
|
|
606
|
+
...(summary.consolidate?.status === 'failed' ? { consolidateError: summary.consolidate.code } : {}),
|
|
607
|
+
...(summary.forget?.status === 'ran' ? { forgetPending: summary.forget.pendingRel } : {}),
|
|
608
|
+
...(summary.forget?.status === 'failed' ? { forgetError: summary.forget.code } : {}),
|
|
609
|
+
},
|
|
610
|
+
].slice(-RUN_HISTORY_LIMIT);
|
|
611
|
+
|
|
612
|
+
try {
|
|
613
|
+
const written = writeScheduleState(root, state, { now: at });
|
|
614
|
+
summary.state = written.state;
|
|
615
|
+
summary.stateWrite = written.write;
|
|
616
|
+
} catch (error) {
|
|
617
|
+
summary.ok = false;
|
|
618
|
+
summary.state = state;
|
|
619
|
+
summary.stateError = errorInfo(error);
|
|
620
|
+
warnTo(
|
|
621
|
+
logger,
|
|
622
|
+
`[auto-maintenance] schedule.json 写入失败(${summary.stateError.code})— ${summary.stateError.message};下次启动会重试`,
|
|
623
|
+
);
|
|
624
|
+
}
|
|
625
|
+
return summary;
|
|
626
|
+
} finally {
|
|
627
|
+
lock.release();
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
function defaultTimers() {
|
|
632
|
+
return {
|
|
633
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
634
|
+
clearTimeout: (handle) => clearTimeout(handle),
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/**
|
|
639
|
+
* Create the daily scheduler. Injectable clock/timers/runner make it testable
|
|
640
|
+
* without waiting a day:
|
|
641
|
+
* now : Date | () => Date
|
|
642
|
+
* timers : { setTimeout(fn, ms), clearTimeout(handle) }
|
|
643
|
+
* run : async/sync (options) => summary (default runDailyMaintenance)
|
|
644
|
+
*
|
|
645
|
+
* start() arms exactly one timer: a short startup tick (runOnStart !== false)
|
|
646
|
+
* or directly the next local midnight. Each tick re-arms the next midnight;
|
|
647
|
+
* a run that straddles midnight arms a 1s catch-up tick instead of skipping a
|
|
648
|
+
* whole day.
|
|
649
|
+
*/
|
|
650
|
+
export function createMaintenanceScheduler(options = {}) {
|
|
651
|
+
const memoryRoot = options.memoryRoot ?? null;
|
|
652
|
+
const config = options.config && typeof options.config === 'object' ? options.config : {};
|
|
653
|
+
const clock = toClock(options.now);
|
|
654
|
+
const timers = options.timers && typeof options.timers.setTimeout === 'function'
|
|
655
|
+
? options.timers
|
|
656
|
+
: defaultTimers();
|
|
657
|
+
const clearTimer = typeof timers.clearTimeout === 'function'
|
|
658
|
+
? (handle) => timers.clearTimeout(handle)
|
|
659
|
+
: () => {};
|
|
660
|
+
const runner = typeof options.run === 'function' ? options.run : runDailyMaintenance;
|
|
661
|
+
const logger = options.logger ?? null;
|
|
662
|
+
const startupDelay = Number.isFinite(options.startDelayMs)
|
|
663
|
+
? Math.max(0, options.startDelayMs)
|
|
664
|
+
: Number.isFinite(config.startDelayMs)
|
|
665
|
+
? Math.max(0, config.startDelayMs)
|
|
666
|
+
: DEFAULT_START_DELAY_MS;
|
|
667
|
+
|
|
668
|
+
let timer = null;
|
|
669
|
+
let started = false;
|
|
670
|
+
let stopped = false;
|
|
671
|
+
let running = false;
|
|
672
|
+
let lastResult = null;
|
|
673
|
+
|
|
674
|
+
function unref(handle) {
|
|
675
|
+
if (handle && typeof handle.unref === 'function') handle.unref();
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
function clear() {
|
|
679
|
+
if (timer) {
|
|
680
|
+
try {
|
|
681
|
+
clearTimer(timer);
|
|
682
|
+
} catch {
|
|
683
|
+
/* a timer implementation failure must not break stop() */
|
|
684
|
+
}
|
|
685
|
+
timer = null;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
function arm(delayMs, trigger) {
|
|
690
|
+
if (stopped) return null;
|
|
691
|
+
const delay = Math.max(0, Math.floor(Number(delayMs) || 0));
|
|
692
|
+
timer = timers.setTimeout(() => {
|
|
693
|
+
timer = null;
|
|
694
|
+
return tick(trigger);
|
|
695
|
+
}, delay);
|
|
696
|
+
unref(timer);
|
|
697
|
+
return timer;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function armNextMidnight() {
|
|
701
|
+
const current = clock();
|
|
702
|
+
const next = nextLocalMidnight(current, MIDNIGHT_PAD_MS);
|
|
703
|
+
const delay = Math.max(0, next.getTime() - current.getTime());
|
|
704
|
+
arm(delay, 'midnight');
|
|
705
|
+
return { at: next.toISOString(), delayMs: delay };
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
async function tick(trigger) {
|
|
709
|
+
if (stopped) return { ok: true, ran: false, reason: 'stopped' };
|
|
710
|
+
if (running) return { ok: true, ran: false, reason: 'busy' };
|
|
711
|
+
running = true;
|
|
712
|
+
const startedAt = clock();
|
|
713
|
+
try {
|
|
714
|
+
const result = await runner({
|
|
715
|
+
memoryRoot,
|
|
716
|
+
config,
|
|
717
|
+
now: startedAt,
|
|
718
|
+
logger,
|
|
719
|
+
trigger,
|
|
720
|
+
});
|
|
721
|
+
lastResult = result;
|
|
722
|
+
return result;
|
|
723
|
+
} catch (error) {
|
|
724
|
+
const info = errorInfo(error);
|
|
725
|
+
lastResult = { ok: false, ran: false, reason: 'failed', error: info };
|
|
726
|
+
warnTo(
|
|
727
|
+
logger,
|
|
728
|
+
`[auto-maintenance] ${trigger} 运行失败(${info.code})— ${info.message};已跳过,不影响对话`,
|
|
729
|
+
);
|
|
730
|
+
return lastResult;
|
|
731
|
+
} finally {
|
|
732
|
+
running = false;
|
|
733
|
+
if (!stopped) {
|
|
734
|
+
const finishedAt = clock();
|
|
735
|
+
if (dayString(finishedAt) !== dayString(startedAt)) {
|
|
736
|
+
// The run started before local midnight and finished after it; run
|
|
737
|
+
// again for the new date rather than waiting a full extra day.
|
|
738
|
+
arm(1000, 'midnight-catchup');
|
|
739
|
+
} else {
|
|
740
|
+
armNextMidnight();
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
function start() {
|
|
747
|
+
if (stopped) return { started: false, reason: 'stopped' };
|
|
748
|
+
if (started) return { started: true, reason: 'already-started', timerArmed: timer !== null };
|
|
749
|
+
if (!memoryRoot) return { started: false, reason: 'no-memory-root' };
|
|
750
|
+
if (config.consolidate === false && config.forget === false) {
|
|
751
|
+
return { started: false, reason: 'disabled' };
|
|
752
|
+
}
|
|
753
|
+
started = true;
|
|
754
|
+
if (config.runOnStart !== false) {
|
|
755
|
+
arm(startupDelay, 'startup');
|
|
756
|
+
return { started: true, mode: 'startup', delayMs: startupDelay };
|
|
757
|
+
}
|
|
758
|
+
const next = armNextMidnight();
|
|
759
|
+
return { started: true, mode: 'midnight', ...next };
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
function stop() {
|
|
763
|
+
stopped = true;
|
|
764
|
+
started = false;
|
|
765
|
+
clear();
|
|
766
|
+
return { stopped: true };
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
async function runNow(trigger = 'manual') {
|
|
770
|
+
clear();
|
|
771
|
+
return tick(trigger);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
function status() {
|
|
775
|
+
return {
|
|
776
|
+
started,
|
|
777
|
+
stopped,
|
|
778
|
+
running,
|
|
779
|
+
timerArmed: timer !== null,
|
|
780
|
+
lastResult,
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
return { start, stop, runNow, status };
|
|
785
|
+
}
|