@jjh32456/longlive 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,718 @@
|
|
|
1
|
+
// src/autoprocedure/runtime.js — autoProcedure 编排(v0.3 §3.1 调度 / §3.6 并发)。
|
|
2
|
+
//
|
|
3
|
+
// 生命周期:
|
|
4
|
+
// registerAutoProcedure():`enabled:false` 时立即返回(零注册、零读盘、零定时器);
|
|
5
|
+
// `session/event` 的 turn/end 回调只做字段过滤 + schedule(),绝不解析、绝不 IO;
|
|
6
|
+
// 真正的采样/蒸馏/写盘在 setTimeout(0..delayMs) 的异步 drain 里。
|
|
7
|
+
//
|
|
8
|
+
// 每会话一个可重置定时器(新 turn/end 重排),`ctx.effect` 负责清理;同一时刻
|
|
9
|
+
// 最多 1 个 drain(staging 目录下的 `.autoprocedure.drain.lock` 第二 key)。
|
|
10
|
+
// 重启丢队列是可接受损失(stalled 计数兜底)。
|
|
11
|
+
//
|
|
12
|
+
// 每个 drain 是一次「尝试」:先写 `sample` 账本行,最后恰好写一行终态
|
|
13
|
+
// (draft / reject / stale 之一,N3)。失败原因可枚举,绝不静默。
|
|
14
|
+
|
|
15
|
+
import {
|
|
16
|
+
AUTOPROCEDURE_MAX_DECOMPRESSED_BYTES,
|
|
17
|
+
} from './config.js';
|
|
18
|
+
import { autoProcedurePaths } from './paths.js';
|
|
19
|
+
import { makeRunId, autoProcedureHolder, acquireWithRetry, releaseSafe } from './locks.js';
|
|
20
|
+
import {
|
|
21
|
+
makeLedgerRow, appendLedgerRow, readLedgerRows,
|
|
22
|
+
draftsToday, llmUsageToday, evaluateStalled,
|
|
23
|
+
} from './ledger.js';
|
|
24
|
+
import {
|
|
25
|
+
readSessionFile, findTurnSample, AutoProcedureSampleError, SAMPLE_CODES,
|
|
26
|
+
} from './session-reader.js';
|
|
27
|
+
import { buildRuleDraft } from './rules.js';
|
|
28
|
+
import { verifyEvidence, verifyEvidenceSet } from './evidence.js';
|
|
29
|
+
import { runLocalLint } from './lint.js';
|
|
30
|
+
import { sanitizeFragment, sanitizeCandidateBody } from './privacy.js';
|
|
31
|
+
import {
|
|
32
|
+
buildSidecar, writeCandidate, applyRetention, listStagedCandidates, composeSectionsText,
|
|
33
|
+
} from './candidate.js';
|
|
34
|
+
import { buildLlmPrompt, callLlmOnce, parseLlmCandidateOutput, reserveLlmBudget } from './llm.js';
|
|
35
|
+
import { normalizeAutoProcedureConfig } from './config.js';
|
|
36
|
+
import { dayString } from '../memory/frontmatter.js';
|
|
37
|
+
|
|
38
|
+
export const SPOT_CHECK_LIMIT = 5;
|
|
39
|
+
export const SPOT_CHECK_SKIP_DAYS = 30;
|
|
40
|
+
|
|
41
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
42
|
+
|
|
43
|
+
function warn(logger, message) {
|
|
44
|
+
try {
|
|
45
|
+
if (typeof logger?.warn === 'function') logger.warn(`[autoprocedure] ${message}`);
|
|
46
|
+
else if (typeof logger === 'function') logger(message);
|
|
47
|
+
} catch {
|
|
48
|
+
/* a log line must never be the reason a turn fails */
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function toDate(now) {
|
|
53
|
+
try {
|
|
54
|
+
const value = typeof now === 'function' ? now() : now;
|
|
55
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
56
|
+
return Number.isNaN(date.getTime()) ? new Date() : date;
|
|
57
|
+
} catch {
|
|
58
|
+
return new Date();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function msOf(now) {
|
|
63
|
+
return toDate(now).getTime();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function mapErrorReason(error) {
|
|
67
|
+
if (error instanceof AutoProcedureSampleError) {
|
|
68
|
+
return error.code === SAMPLE_CODES.TOO_BIG ? 'too_big' : 'parse';
|
|
69
|
+
}
|
|
70
|
+
return 'io';
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Create the runtime object. Pure: does not touch the disk.
|
|
75
|
+
* `enabled:false` leaves memoryRoot null so even an accidental call cannot read.
|
|
76
|
+
*/
|
|
77
|
+
export function createAutoProcedureRuntime({
|
|
78
|
+
config = {},
|
|
79
|
+
memoryRoot = null,
|
|
80
|
+
home = null,
|
|
81
|
+
now = () => new Date(),
|
|
82
|
+
logger = null,
|
|
83
|
+
deps = {},
|
|
84
|
+
} = {}) {
|
|
85
|
+
const normalized = normalizeAutoProcedureConfig(config);
|
|
86
|
+
const cfg = normalized.config;
|
|
87
|
+
const runtime = {
|
|
88
|
+
enabled: cfg.enabled,
|
|
89
|
+
registered: false,
|
|
90
|
+
config: cfg,
|
|
91
|
+
warnings: normalized.warnings,
|
|
92
|
+
memoryRoot: cfg.enabled && typeof memoryRoot === 'string' && memoryRoot.trim() !== '' ? memoryRoot.trim() : null,
|
|
93
|
+
home: typeof home === 'string' && home !== '' ? home : null,
|
|
94
|
+
now,
|
|
95
|
+
logger,
|
|
96
|
+
deps,
|
|
97
|
+
ctx: null,
|
|
98
|
+
states: new Map(),
|
|
99
|
+
lastError: null,
|
|
100
|
+
ackWritten: false,
|
|
101
|
+
retentionDone: false,
|
|
102
|
+
lastRetentionDay: null,
|
|
103
|
+
};
|
|
104
|
+
initializeRuntime(runtime);
|
|
105
|
+
return runtime;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function initializeRuntime(runtime) {
|
|
109
|
+
const deps = runtime.deps ?? {};
|
|
110
|
+
const setTimeoutFn = typeof deps.setTimeout === 'function' ? deps.setTimeout : setTimeout;
|
|
111
|
+
const clearTimeoutFn = typeof deps.clearTimeout === 'function' ? deps.clearTimeout : clearTimeout;
|
|
112
|
+
const sleep = typeof deps.sleep === 'function' ? deps.sleep : (ms) => new Promise((resolve) => setTimeout(resolve, Math.max(0, Number(ms) || 0)));
|
|
113
|
+
|
|
114
|
+
function stateFor(sessionId) {
|
|
115
|
+
let state = runtime.states.get(sessionId);
|
|
116
|
+
if (!state) {
|
|
117
|
+
state = { timer: null, lastActivityAt: 0, lastTurn: null, drains: 0 };
|
|
118
|
+
runtime.states.set(sessionId, state);
|
|
119
|
+
}
|
|
120
|
+
return state;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function clearTimer(state) {
|
|
124
|
+
if (!state?.timer) return;
|
|
125
|
+
try {
|
|
126
|
+
clearTimeoutFn(state.timer);
|
|
127
|
+
} catch {
|
|
128
|
+
/* timer may already have fired */
|
|
129
|
+
}
|
|
130
|
+
state.timer = null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function schedule(sessionId, turn) {
|
|
134
|
+
if (!runtime.enabled || !runtime.registered) return null;
|
|
135
|
+
const state = stateFor(sessionId);
|
|
136
|
+
// D1/BLK-2: scheduling must NOT advance the idle clock — only a real
|
|
137
|
+
// turn/end does (see onSessionEvent). Otherwise delayMs < idleMs would
|
|
138
|
+
// re-arm forever and never sample.
|
|
139
|
+
if (Number.isInteger(turn) && turn > 0) state.lastTurn = turn;
|
|
140
|
+
clearTimer(state);
|
|
141
|
+
const timer = setTimeoutFn(() => {
|
|
142
|
+
state.timer = null;
|
|
143
|
+
Promise.resolve()
|
|
144
|
+
.then(() => runtime.drain(sessionId))
|
|
145
|
+
.catch((error) => {
|
|
146
|
+
runtime.lastError = String(error?.message ?? error);
|
|
147
|
+
});
|
|
148
|
+
}, Math.max(0, runtime.config.delayMs));
|
|
149
|
+
if (typeof timer?.unref === 'function') timer.unref();
|
|
150
|
+
state.timer = timer;
|
|
151
|
+
return timer;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function sampleWithRetry(sessionId) {
|
|
155
|
+
const readFn = typeof deps.readSessionFile === 'function' ? deps.readSessionFile : readSessionFile;
|
|
156
|
+
// D7: the cap is user-configurable (config.maxDecompressBytes) with a hard
|
|
157
|
+
// ceiling in config.js; deps.maxDecompressedBytes stays as a test override.
|
|
158
|
+
const configured = Number.isInteger(runtime.config.maxDecompressBytes) && runtime.config.maxDecompressBytes > 0
|
|
159
|
+
? runtime.config.maxDecompressBytes
|
|
160
|
+
: AUTOPROCEDURE_MAX_DECOMPRESSED_BYTES;
|
|
161
|
+
const maxBytes = Number.isInteger(deps.maxDecompressedBytes) && deps.maxDecompressedBytes > 0
|
|
162
|
+
? deps.maxDecompressedBytes
|
|
163
|
+
: configured;
|
|
164
|
+
let lastError = null;
|
|
165
|
+
// retry ≤1 (F3): a transient read/parse miss gets one more chance; too_big/oob does not.
|
|
166
|
+
for (let attempt = 0; attempt <= 1; attempt += 1) {
|
|
167
|
+
try {
|
|
168
|
+
return await readFn({
|
|
169
|
+
home: runtime.home,
|
|
170
|
+
sessionId,
|
|
171
|
+
maxBytes,
|
|
172
|
+
readFile: typeof deps.readFile === 'function' ? deps.readFile : null,
|
|
173
|
+
});
|
|
174
|
+
} catch (error) {
|
|
175
|
+
lastError = error;
|
|
176
|
+
if (error instanceof AutoProcedureSampleError && error.code === SAMPLE_CODES.TOO_BIG) throw error;
|
|
177
|
+
if (error instanceof AutoProcedureSampleError && error.code === SAMPLE_CODES.MISSING) {
|
|
178
|
+
// A file that does not exist yet is not retried forever: one retry only.
|
|
179
|
+
if (attempt >= 1) throw error;
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
if (attempt >= 1) throw error;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
throw lastError;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async function ensureLlmAck() {
|
|
189
|
+
if (runtime.ackWritten || !runtime.config.llm.enabled) return false;
|
|
190
|
+
runtime.ackWritten = true;
|
|
191
|
+
appendLedgerRow({
|
|
192
|
+
memoryRoot: runtime.memoryRoot,
|
|
193
|
+
row: makeLedgerRow({
|
|
194
|
+
kind: 'llm_enable_ack',
|
|
195
|
+
model: null,
|
|
196
|
+
now: runtime.now,
|
|
197
|
+
}),
|
|
198
|
+
now: toDate(runtime.now),
|
|
199
|
+
append: typeof deps.appendLedger === 'function' ? deps.appendLedger : null,
|
|
200
|
+
});
|
|
201
|
+
return true;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function secondPrivacyGate(draft) {
|
|
205
|
+
const options = { memoryRoot: runtime.memoryRoot ?? '', home: runtime.home ?? '' };
|
|
206
|
+
const next = { ...draft, sections: { ...draft.sections } };
|
|
207
|
+
const parts = [
|
|
208
|
+
['when', draft.sections.when],
|
|
209
|
+
['failureModes', draft.sections.failureModes],
|
|
210
|
+
['example', draft.sections.example],
|
|
211
|
+
];
|
|
212
|
+
for (const [key, value] of parts) {
|
|
213
|
+
const sanitized = sanitizeFragment(value, options);
|
|
214
|
+
if (!sanitized.ok) return { ok: false, code: 'E_AP_PRIVACY_BODY', reasons: sanitized.reasons };
|
|
215
|
+
next.sections[key] = sanitized.text;
|
|
216
|
+
}
|
|
217
|
+
const steps = [];
|
|
218
|
+
for (const step of Array.isArray(draft.sections.steps) ? draft.sections.steps : []) {
|
|
219
|
+
const sanitized = sanitizeFragment(step, options);
|
|
220
|
+
if (!sanitized.ok) return { ok: false, code: 'E_AP_PRIVACY_BODY', reasons: sanitized.reasons };
|
|
221
|
+
steps.push(sanitized.text);
|
|
222
|
+
}
|
|
223
|
+
if (steps.length === 0) return { ok: false, code: 'E_AP_NO_STEPS' };
|
|
224
|
+
next.sections.steps = steps;
|
|
225
|
+
const trigger = [];
|
|
226
|
+
for (const word of Array.isArray(draft.trigger) ? draft.trigger : []) {
|
|
227
|
+
const sanitized = sanitizeFragment(word, options);
|
|
228
|
+
if (sanitized.ok && sanitized.text.trim() !== '') trigger.push(sanitized.text.trim());
|
|
229
|
+
}
|
|
230
|
+
if (trigger.length === 0) return { ok: false, code: 'E_AP_PRIVACY_TRIGGER' };
|
|
231
|
+
next.trigger = trigger.slice(0, 5);
|
|
232
|
+
const bodyGate = sanitizeCandidateBody(composeSectionsText(next.sections), options);
|
|
233
|
+
if (!bodyGate.ok) return { ok: false, code: 'E_AP_PRIVACY_BODY', reasons: bodyGate.reasons };
|
|
234
|
+
return { ok: true, draft: next };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async function maybePolish(draft, attemptId, sessionId, turn) {
|
|
238
|
+
await ensureLlmAck();
|
|
239
|
+
const appendRow = (row) => appendLedgerRow({
|
|
240
|
+
memoryRoot: runtime.memoryRoot,
|
|
241
|
+
row: makeLedgerRow({ ...row, attemptId, sessionId, turn, kind: 'llm', now: runtime.now }),
|
|
242
|
+
now: toDate(runtime.now),
|
|
243
|
+
append: typeof deps.appendLedger === 'function' ? deps.appendLedger : null,
|
|
244
|
+
});
|
|
245
|
+
// MAJ-5: 预算拒绝与 provider 失败都只影响「这一轮能否润色」,不影响「这一轮能否
|
|
246
|
+
// 产出候选」。任何 LLM 侧的拒绝/失败都回落到本地 rules 草稿并如实记账,保证
|
|
247
|
+
// 开启 B 模式后的候选数 >= 同配置 A 模式(开 B 只会更好、不会更少)。
|
|
248
|
+
// `dailyLlmCalls` 统计的是真实 provider 调用尝试(成功、超时、不可用都算,预算
|
|
249
|
+
// 拒绝本身不计),它与候选产出解耦:预算耗尽后只是不再调模型,本地草稿照常产。
|
|
250
|
+
const fallbackToRules = (reason) => {
|
|
251
|
+
appendRow({ reason, tokens: { in: 0, out: 0 }, model: null });
|
|
252
|
+
return {
|
|
253
|
+
stop: false,
|
|
254
|
+
draft: { ...draft, generator: 'rules' },
|
|
255
|
+
llm: { used: true, model: null, tokens: { in: 0, out: 0 } },
|
|
256
|
+
llmNote: reason,
|
|
257
|
+
};
|
|
258
|
+
};
|
|
259
|
+
const prompt = buildLlmPrompt({ sections: draft.sections, trigger: draft.trigger });
|
|
260
|
+
if (!prompt.ok) {
|
|
261
|
+
// Prompt 隐私门属于安全 fail-closed:宁可不润色也不把可疑文本送进模型。
|
|
262
|
+
// 该分支不写 llm 行(没有发生 provider 调用),按 reject privacy 收口。
|
|
263
|
+
return { stop: true, reason: 'privacy', detail: { code: prompt.code } };
|
|
264
|
+
}
|
|
265
|
+
const ledger = readLedgerRows(runtime.memoryRoot);
|
|
266
|
+
if (!ledger.ok) return { stop: true, reason: 'io' };
|
|
267
|
+
const usage = llmUsageToday(ledger.rows, { now: toDate(runtime.now) });
|
|
268
|
+
const reserved = reserveLlmBudget({ usage, estimate: prompt.estimate, config: runtime.config.llm });
|
|
269
|
+
if (!reserved.ok) return fallbackToRules('budget');
|
|
270
|
+
const result = await callLlmOnce({
|
|
271
|
+
ctx: runtime.ctx,
|
|
272
|
+
prompt,
|
|
273
|
+
timeoutMs: typeof deps.llmTimeoutMs === 'number' && deps.llmTimeoutMs > 0 ? deps.llmTimeoutMs : undefined,
|
|
274
|
+
setTimeoutFn: typeof deps.setTimeout === 'function' ? deps.setTimeout : setTimeout,
|
|
275
|
+
clearTimeoutFn: typeof deps.clearTimeout === 'function' ? deps.clearTimeout : clearTimeout,
|
|
276
|
+
now: runtime.now,
|
|
277
|
+
});
|
|
278
|
+
if (!result.ok) {
|
|
279
|
+
const reason = result.code === 'E_LLM_TIMEOUT' ? 'llm_timeout' : 'llm_unavailable';
|
|
280
|
+
// BLK-1/MAJ-5: enabling B must never lose the local draft. A provider failure
|
|
281
|
+
// is booked on the `llm` row, then we fall back to the rules draft (never a
|
|
282
|
+
// reject) so B mode can only add polish, not remove candidates.
|
|
283
|
+
return fallbackToRules(reason);
|
|
284
|
+
}
|
|
285
|
+
appendRow({ reason: null, tokens: result.tokens, model: result.model });
|
|
286
|
+
const parsed = parseLlmCandidateOutput(result.text);
|
|
287
|
+
const llm = { used: true, model: result.model ?? null, tokens: result.tokens ?? { in: 0, out: 0 } };
|
|
288
|
+
if (!parsed.ok) {
|
|
289
|
+
// A malformed model answer never becomes a half-card: keep the local draft.
|
|
290
|
+
return { stop: false, draft: { ...draft, generator: 'rules' }, llm, llmNote: parsed.code };
|
|
291
|
+
}
|
|
292
|
+
return { stop: false, draft: { ...draft, sections: parsed.sections, generator: 'llm' }, llm };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function attempt({ sessionId, turn, attemptId }) {
|
|
296
|
+
runtime.lastError = null;
|
|
297
|
+
const sample = await sampleWithRetry(sessionId);
|
|
298
|
+
const parsed = sample?.parsed;
|
|
299
|
+
const turnSample = findTurnSample(parsed, turn);
|
|
300
|
+
if (!turnSample) {
|
|
301
|
+
throw new AutoProcedureSampleError(SAMPLE_CODES.TURN, `会话里找不到第 ${turn} 轮`);
|
|
302
|
+
}
|
|
303
|
+
const buildDraft = typeof deps.buildDraft === 'function' ? deps.buildDraft : buildRuleDraft;
|
|
304
|
+
const built = await buildDraft({
|
|
305
|
+
sessionId,
|
|
306
|
+
turn,
|
|
307
|
+
parsed,
|
|
308
|
+
turnSample,
|
|
309
|
+
minToolCalls: runtime.config.minToolCalls,
|
|
310
|
+
memoryRoot: runtime.memoryRoot,
|
|
311
|
+
home: runtime.home,
|
|
312
|
+
now: toDate(runtime.now),
|
|
313
|
+
readFile: typeof deps.readFile === 'function' ? deps.readFile : null,
|
|
314
|
+
});
|
|
315
|
+
if (!built?.eligible || !built.draft) {
|
|
316
|
+
return {
|
|
317
|
+
ok: false,
|
|
318
|
+
reason: 'ineligible',
|
|
319
|
+
detail: { ineligible: built?.reason ?? 'unknown', stats: built?.stats ?? null },
|
|
320
|
+
dropped: built?.stats?.privacyDropped > 0 ? { privacy: built.stats.privacyDropped } : null,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
let draft = built.draft;
|
|
324
|
+
let llmInfo = { used: false, model: null, tokens: { in: 0, out: 0 } };
|
|
325
|
+
if (runtime.config.llm.enabled) {
|
|
326
|
+
const polished = await maybePolish(draft, attemptId, sessionId, turn);
|
|
327
|
+
if (polished.stop) {
|
|
328
|
+
return { ok: false, reason: polished.reason, detail: polished.detail ?? null, dropped: null };
|
|
329
|
+
}
|
|
330
|
+
draft = polished.draft;
|
|
331
|
+
llmInfo = polished.llm ?? llmInfo;
|
|
332
|
+
}
|
|
333
|
+
const gated = secondPrivacyGate(draft);
|
|
334
|
+
if (!gated.ok) {
|
|
335
|
+
return { ok: false, reason: 'privacy', detail: { code: gated.code }, dropped: { privacy: 1 } };
|
|
336
|
+
}
|
|
337
|
+
draft = gated.draft;
|
|
338
|
+
const verification = verifyEvidenceSet(draft.evidence, {
|
|
339
|
+
parsed,
|
|
340
|
+
memoryRoot: runtime.memoryRoot,
|
|
341
|
+
readFile: typeof deps.readFile === 'function' ? deps.readFile : null,
|
|
342
|
+
});
|
|
343
|
+
if (!verification.ok) {
|
|
344
|
+
return { ok: false, reason: 'evidence', detail: { code: verification.code }, dropped: null };
|
|
345
|
+
}
|
|
346
|
+
const lint = runLocalLint({
|
|
347
|
+
memoryRoot: runtime.memoryRoot,
|
|
348
|
+
candidate: draft,
|
|
349
|
+
evidenceResults: verification.results,
|
|
350
|
+
at: toDate(runtime.now).toISOString(),
|
|
351
|
+
});
|
|
352
|
+
const risk = lint.issues.some((issue) => issue.code === 'DANGEROUS_ACTION') ? 'high' : 'low';
|
|
353
|
+
const sidecar = buildSidecar({
|
|
354
|
+
slug: draft.slug,
|
|
355
|
+
createdAt: toDate(runtime.now).toISOString(),
|
|
356
|
+
risk,
|
|
357
|
+
generator: draft.generator,
|
|
358
|
+
source: draft.source,
|
|
359
|
+
evidence: draft.evidence,
|
|
360
|
+
llm: llmInfo,
|
|
361
|
+
lint,
|
|
362
|
+
retentionDays: runtime.config.retentionDays,
|
|
363
|
+
now: toDate(runtime.now),
|
|
364
|
+
});
|
|
365
|
+
const paths = autoProcedurePaths(runtime.memoryRoot);
|
|
366
|
+
const holder = autoProcedureHolder({ runId: attemptId, sessionId });
|
|
367
|
+
const staging = await acquireWithRetry({
|
|
368
|
+
lockFile: paths.stagingLock,
|
|
369
|
+
holder,
|
|
370
|
+
sleep,
|
|
371
|
+
acquire: typeof deps.acquireLease === 'function' ? deps.acquireLease : undefined,
|
|
372
|
+
now: typeof deps.nowForLock === 'function' ? deps.nowForLock : undefined,
|
|
373
|
+
});
|
|
374
|
+
if (!staging.ok) {
|
|
375
|
+
return { ok: false, reason: 'lock', detail: { code: staging.code }, dropped: null };
|
|
376
|
+
}
|
|
377
|
+
try {
|
|
378
|
+
const written = writeCandidate({
|
|
379
|
+
memoryRoot: runtime.memoryRoot,
|
|
380
|
+
candidate: {
|
|
381
|
+
name: draft.name,
|
|
382
|
+
trigger: draft.trigger,
|
|
383
|
+
salience: draft.salience,
|
|
384
|
+
strength: draft.strength,
|
|
385
|
+
lastUsed: draft.lastUsed,
|
|
386
|
+
sections: draft.sections,
|
|
387
|
+
},
|
|
388
|
+
sidecar,
|
|
389
|
+
now: toDate(runtime.now),
|
|
390
|
+
});
|
|
391
|
+
if (!written.ok) return { ok: false, reason: 'io', detail: { code: written.code, message: written.detail }, dropped: null };
|
|
392
|
+
const dropped = built.stats?.privacyDropped > 0 ? { privacy: built.stats.privacyDropped } : null;
|
|
393
|
+
return {
|
|
394
|
+
ok: true,
|
|
395
|
+
row: {
|
|
396
|
+
candidateSlug: written.slug,
|
|
397
|
+
generator: draft.generator,
|
|
398
|
+
model: llmInfo.model ?? null,
|
|
399
|
+
// Tokens are booked on the `llm` row only; the terminal row keeps zeros
|
|
400
|
+
// so the ledger sum is not double-counted (D6)。
|
|
401
|
+
tokens: { in: 0, out: 0 },
|
|
402
|
+
dropped,
|
|
403
|
+
lintVerdict: lint.verdict,
|
|
404
|
+
},
|
|
405
|
+
};
|
|
406
|
+
} finally {
|
|
407
|
+
releaseSafe(paths.stagingLock, holder);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
async function drain(sessionId) {
|
|
412
|
+
if (!runtime.enabled || !runtime.registered) return { ok: false, code: 'E_AP_DISABLED' };
|
|
413
|
+
const state = stateFor(sessionId);
|
|
414
|
+
const nowMs = msOf(runtime.now);
|
|
415
|
+
// D1/BLK-2: idle is measured from the last REAL turn/end (lastActivityAt),
|
|
416
|
+
// never from a schedule. drain re-arms with schedule(), which no longer
|
|
417
|
+
// moves the clock, so the remaining time strictly decreases and the next
|
|
418
|
+
// fire actually samples (delayMs < idleMs included).
|
|
419
|
+
if (runtime.config.idleMs > 0 && state.lastActivityAt > 0) {
|
|
420
|
+
const remaining = runtime.config.idleMs - (nowMs - state.lastActivityAt);
|
|
421
|
+
if (remaining > 0) {
|
|
422
|
+
schedule(sessionId, state.lastTurn);
|
|
423
|
+
return { ok: false, code: 'E_AP_IDLE_REARM', remaining };
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
const turn = state.lastTurn;
|
|
427
|
+
if (!Number.isInteger(turn) || turn < 1) return { ok: false, code: 'E_AP_NO_TURN' };
|
|
428
|
+
const runId = makeRunId(runtime.now, typeof deps.random === 'function' ? deps.random : Math.random);
|
|
429
|
+
const attemptId = `${sessionId}:${turn}:${runId}`;
|
|
430
|
+
const appendRow = (row) => appendLedgerRow({
|
|
431
|
+
memoryRoot: runtime.memoryRoot,
|
|
432
|
+
row: makeLedgerRow({ ...row, attemptId, sessionId, turn, now: runtime.now }),
|
|
433
|
+
now: toDate(runtime.now),
|
|
434
|
+
append: typeof deps.appendLedger === 'function' ? deps.appendLedger : null,
|
|
435
|
+
});
|
|
436
|
+
let terminal = false;
|
|
437
|
+
const finish = (kind, extra = {}) => {
|
|
438
|
+
if (terminal) return;
|
|
439
|
+
terminal = true;
|
|
440
|
+
appendRow({ kind, reason: extra.reason ?? null, candidateSlug: extra.candidateSlug ?? null, generator: extra.generator ?? null, tokens: extra.tokens ?? null, model: extra.model ?? null, dropped: extra.dropped ?? null });
|
|
441
|
+
};
|
|
442
|
+
try {
|
|
443
|
+
state.drains += 1;
|
|
444
|
+
// N3: one sample row per attempt, always.
|
|
445
|
+
appendRow({ kind: 'sample' });
|
|
446
|
+
const ledger = readLedgerRows(runtime.memoryRoot);
|
|
447
|
+
if (!ledger.ok) {
|
|
448
|
+
finish('reject', { reason: 'io' });
|
|
449
|
+
return { ok: false, code: 'E_AP_LEDGER_READ' };
|
|
450
|
+
}
|
|
451
|
+
const today = draftsToday(ledger.rows, { now: toDate(runtime.now) });
|
|
452
|
+
if (today.total >= runtime.config.dailyCandidates) {
|
|
453
|
+
finish('reject', { reason: 'quota', detail: undefined });
|
|
454
|
+
return { ok: false, code: 'E_AP_DAILY_QUOTA', detail: { total: today.total } };
|
|
455
|
+
}
|
|
456
|
+
if ((today.bySession.get(sessionId) ?? 0) >= runtime.config.perSessionCandidates) {
|
|
457
|
+
finish('reject', { reason: 'quota' });
|
|
458
|
+
return { ok: false, code: 'E_AP_SESSION_QUOTA' };
|
|
459
|
+
}
|
|
460
|
+
const paths = autoProcedurePaths(runtime.memoryRoot);
|
|
461
|
+
const holder = autoProcedureHolder({ runId, sessionId });
|
|
462
|
+
const lock = await acquireWithRetry({
|
|
463
|
+
lockFile: paths.drainLock,
|
|
464
|
+
holder,
|
|
465
|
+
sleep,
|
|
466
|
+
acquire: typeof deps.acquireLease === 'function' ? deps.acquireLease : undefined,
|
|
467
|
+
});
|
|
468
|
+
if (!lock.ok) {
|
|
469
|
+
finish('reject', { reason: 'lock', detail: { code: lock.code } });
|
|
470
|
+
return { ok: false, code: lock.code, attempts: lock.attempts };
|
|
471
|
+
}
|
|
472
|
+
try {
|
|
473
|
+
const outcome = await attempt({ sessionId, turn, attemptId });
|
|
474
|
+
if (outcome.ok) {
|
|
475
|
+
finish('draft', outcome.row);
|
|
476
|
+
return { ok: true, attemptId, ...outcome.row };
|
|
477
|
+
}
|
|
478
|
+
finish('reject', {
|
|
479
|
+
reason: outcome.reason,
|
|
480
|
+
dropped: outcome.dropped ?? null,
|
|
481
|
+
});
|
|
482
|
+
return { ok: false, attemptId, reason: outcome.reason, detail: outcome.detail ?? null };
|
|
483
|
+
} finally {
|
|
484
|
+
releaseSafe(paths.drainLock, holder);
|
|
485
|
+
}
|
|
486
|
+
} catch (error) {
|
|
487
|
+
runtime.lastError = String(error?.message ?? error);
|
|
488
|
+
finish('reject', { reason: mapErrorReason(error) });
|
|
489
|
+
const reason = mapErrorReason(error);
|
|
490
|
+
return { ok: false, attemptId, reason, error: runtime.lastError };
|
|
491
|
+
} finally {
|
|
492
|
+
// F5: stalled evaluation point — in the async hook, reads only the ledger tail.
|
|
493
|
+
try {
|
|
494
|
+
evaluateStalled({ memoryRoot: runtime.memoryRoot, enabled: runtime.enabled, now: toDate(runtime.now) });
|
|
495
|
+
} catch (error) {
|
|
496
|
+
runtime.lastError = String(error?.message ?? error);
|
|
497
|
+
}
|
|
498
|
+
// Retention: at most once per local day, even if the host never restarts.
|
|
499
|
+
try {
|
|
500
|
+
const today = dayString(toDate(runtime.now));
|
|
501
|
+
if (runtime.lastRetentionDay !== today) {
|
|
502
|
+
runtime.lastRetentionDay = today;
|
|
503
|
+
applyRetention({ memoryRoot: runtime.memoryRoot, now: toDate(runtime.now), retentionDays: runtime.config.retentionDays });
|
|
504
|
+
}
|
|
505
|
+
} catch (error) {
|
|
506
|
+
runtime.lastError = String(error?.message ?? error);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
async function start() {
|
|
512
|
+
if (!runtime.enabled || !runtime.memoryRoot) return { ok: false, code: 'E_AP_DISABLED' };
|
|
513
|
+
const out = { ok: true, ackWritten: false, retention: null, spotCheck: null, stalled: null };
|
|
514
|
+
try {
|
|
515
|
+
if (!runtime.retentionDone) {
|
|
516
|
+
runtime.retentionDone = true;
|
|
517
|
+
runtime.lastRetentionDay = dayString(toDate(runtime.now));
|
|
518
|
+
out.retention = applyRetention({ memoryRoot: runtime.memoryRoot, now: toDate(runtime.now), retentionDays: runtime.config.retentionDays });
|
|
519
|
+
}
|
|
520
|
+
} catch (error) {
|
|
521
|
+
warn(runtime.logger, `候选保留期检查失败:${error?.message ?? error}`);
|
|
522
|
+
}
|
|
523
|
+
try {
|
|
524
|
+
out.ackWritten = await ensureLlmAck();
|
|
525
|
+
} catch (error) {
|
|
526
|
+
warn(runtime.logger, `llm_enable_ack 写入失败:${error?.message ?? error}`);
|
|
527
|
+
}
|
|
528
|
+
try {
|
|
529
|
+
out.spotCheck = await spotCheckCandidates({
|
|
530
|
+
memoryRoot: runtime.memoryRoot,
|
|
531
|
+
home: runtime.home,
|
|
532
|
+
now: toDate(runtime.now),
|
|
533
|
+
limit: SPOT_CHECK_LIMIT,
|
|
534
|
+
readFile: typeof deps.readFile === 'function' ? deps.readFile : null,
|
|
535
|
+
readSessionFile: typeof deps.readSessionFile === 'function' ? deps.readSessionFile : readSessionFile,
|
|
536
|
+
});
|
|
537
|
+
} catch (error) {
|
|
538
|
+
warn(runtime.logger, `候选证据抽查失败:${error?.message ?? error}`);
|
|
539
|
+
}
|
|
540
|
+
try {
|
|
541
|
+
out.stalled = evaluateStalled({ memoryRoot: runtime.memoryRoot, enabled: runtime.enabled, now: toDate(runtime.now) });
|
|
542
|
+
} catch (error) {
|
|
543
|
+
warn(runtime.logger, `stalled 评估失败:${error?.message ?? error}`);
|
|
544
|
+
}
|
|
545
|
+
return out;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function dispose() {
|
|
549
|
+
for (const state of runtime.states.values()) clearTimer(state);
|
|
550
|
+
runtime.states.clear();
|
|
551
|
+
runtime.registered = false;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function onSessionEvent(session, event) {
|
|
555
|
+
// Contract: this callback only reads cheap event fields and calls schedule().
|
|
556
|
+
// No parsing, no fs, no JSON, no locks.
|
|
557
|
+
try {
|
|
558
|
+
if (!runtime.enabled || !runtime.registered) return;
|
|
559
|
+
if (event?.type !== 'turn/end') return;
|
|
560
|
+
const data = event?.data ?? {};
|
|
561
|
+
const kind = typeof data.reason?.kind === 'string' ? data.reason.kind.trim().toLowerCase() : '';
|
|
562
|
+
if (kind !== 'completed') return;
|
|
563
|
+
// F12 + N2: exclude router-origin turns in both observed shapes.
|
|
564
|
+
if (data.origin === 'router' || data.task?.origin === 'router') return;
|
|
565
|
+
const sessionId = typeof session?.id === 'string' ? session.id : '';
|
|
566
|
+
if (sessionId === '') return;
|
|
567
|
+
const turn = Number.isInteger(data.turn) ? data.turn : null;
|
|
568
|
+
// D1/BLK-2: the idle clock advances ONLY on a real, completed, non-router
|
|
569
|
+
// turn/end. schedule() never touches it, so a re-armed drain cannot starve.
|
|
570
|
+
stateFor(sessionId).lastActivityAt = msOf(runtime.now);
|
|
571
|
+
schedule(sessionId, turn);
|
|
572
|
+
} catch (error) {
|
|
573
|
+
runtime.lastError = String(error?.message ?? error);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function status() {
|
|
578
|
+
return {
|
|
579
|
+
enabled: runtime.enabled,
|
|
580
|
+
registered: runtime.registered,
|
|
581
|
+
hooks: runtime.registered ? ['session/event'] : [],
|
|
582
|
+
memoryRootConfigured: runtime.memoryRoot !== null,
|
|
583
|
+
config: runtime.config,
|
|
584
|
+
warnings: runtime.warnings,
|
|
585
|
+
lastError: runtime.lastError,
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
Object.assign(runtime, { schedule, drain, start, dispose, onSessionEvent, status, ensureLlmAck });
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* F5/D4: periodic, read-only spot-check of staged candidate evidence.
|
|
594
|
+
* Failure only writes a `stale` ledger report — never changes a card, deletes a
|
|
595
|
+
* file, or moves a directory. Candidates with a stale report in the last 30
|
|
596
|
+
* days are skipped; at most `limit` per run.
|
|
597
|
+
*/
|
|
598
|
+
export async function spotCheckCandidates({
|
|
599
|
+
memoryRoot,
|
|
600
|
+
home = null,
|
|
601
|
+
now = new Date(),
|
|
602
|
+
limit = SPOT_CHECK_LIMIT,
|
|
603
|
+
readFile = null,
|
|
604
|
+
readSessionFile: readSession = readSessionFile,
|
|
605
|
+
} = {}) {
|
|
606
|
+
const candidates = listStagedCandidates(memoryRoot);
|
|
607
|
+
if (candidates.length === 0) return { checked: 0, stale: [], skipped: 0 };
|
|
608
|
+
const ledger = readLedgerRows(memoryRoot);
|
|
609
|
+
const rows = ledger.ok ? ledger.rows : [];
|
|
610
|
+
const cutoff = msOf(now) - SPOT_CHECK_SKIP_DAYS * DAY_MS;
|
|
611
|
+
const recentlyReported = new Set(rows
|
|
612
|
+
.filter((row) => row?.kind === 'stale' && typeof row.candidateSlug === 'string'
|
|
613
|
+
&& Number.isFinite(Date.parse(String(row.at ?? ''))) && Date.parse(String(row.at ?? '')) >= cutoff)
|
|
614
|
+
.map((row) => row.candidateSlug));
|
|
615
|
+
const picked = candidates.filter((item) => !recentlyReported.has(item.slug)).slice(0, Math.max(1, limit));
|
|
616
|
+
const stale = [];
|
|
617
|
+
for (const item of picked) {
|
|
618
|
+
const source = item.meta?.source ?? {};
|
|
619
|
+
let parsed = null;
|
|
620
|
+
try {
|
|
621
|
+
const sampled = await readSession({ home, sessionId: source.sessionId });
|
|
622
|
+
parsed = sampled?.parsed ?? null;
|
|
623
|
+
} catch {
|
|
624
|
+
parsed = null;
|
|
625
|
+
}
|
|
626
|
+
let code = null;
|
|
627
|
+
for (const evidence of Array.isArray(item.meta?.evidence) ? item.meta.evidence : []) {
|
|
628
|
+
if (!parsed) {
|
|
629
|
+
code = 'E_EVIDENCE_SESSION_MISSING';
|
|
630
|
+
break;
|
|
631
|
+
}
|
|
632
|
+
const verified = verifyEvidence({ evidence, parsed, memoryRoot, readFile });
|
|
633
|
+
if (!verified.ok) {
|
|
634
|
+
code = verified.code;
|
|
635
|
+
break;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
if (code) {
|
|
639
|
+
appendLedgerRow({
|
|
640
|
+
memoryRoot,
|
|
641
|
+
row: makeLedgerRow({
|
|
642
|
+
kind: 'stale',
|
|
643
|
+
attemptId: null,
|
|
644
|
+
sessionId: typeof source.sessionId === 'string' ? source.sessionId : null,
|
|
645
|
+
turn: Number.isInteger(source.turn) ? source.turn : null,
|
|
646
|
+
candidateSlug: item.slug,
|
|
647
|
+
reason: code,
|
|
648
|
+
now,
|
|
649
|
+
}),
|
|
650
|
+
now: now instanceof Date ? now : new Date(now),
|
|
651
|
+
});
|
|
652
|
+
stale.push({ slug: item.slug, code });
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
return { checked: picked.length, stale, skipped: candidates.length - picked.length };
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/**
|
|
659
|
+
* Plugin entry: mount the listener. Disabled → no hook, no disk, no timer, no log.
|
|
660
|
+
* @returns {{enabled:boolean, registered:boolean, reason?:string, hooks?:string[],
|
|
661
|
+
* runtime:object, started?:Promise<object>}}
|
|
662
|
+
*/
|
|
663
|
+
export function registerAutoProcedure(ctx, config = {}, {
|
|
664
|
+
memoryRoot = null,
|
|
665
|
+
home = null,
|
|
666
|
+
now = null,
|
|
667
|
+
logger = null,
|
|
668
|
+
deps = {},
|
|
669
|
+
} = {}) {
|
|
670
|
+
const runtime = createAutoProcedureRuntime({
|
|
671
|
+
// Strict: only the host config tree `config.autoProcedure` is accepted (no
|
|
672
|
+
// "treat the whole config as the autoProcedure subtree" fallback).
|
|
673
|
+
config: config?.autoProcedure,
|
|
674
|
+
memoryRoot,
|
|
675
|
+
home,
|
|
676
|
+
now: now ?? (() => new Date()),
|
|
677
|
+
logger,
|
|
678
|
+
deps,
|
|
679
|
+
});
|
|
680
|
+
if (!runtime.enabled) {
|
|
681
|
+
return { enabled: false, registered: false, reason: 'disabled', hooks: [], runtime };
|
|
682
|
+
}
|
|
683
|
+
if (runtime.memoryRoot === null) {
|
|
684
|
+
warn(runtime.logger, 'autoProcedure.enabled=true 但 memoryRoot 未配置 — 未注册(按 F11:warn + 不静默)');
|
|
685
|
+
return { enabled: true, registered: false, reason: 'E_MEMORY_ROOT_UNSET', hooks: [], runtime };
|
|
686
|
+
}
|
|
687
|
+
if (typeof ctx?.on !== 'function') {
|
|
688
|
+
warn(runtime.logger, 'autoProcedure 已启用但宿主 ctx 没有 on() — 未注册');
|
|
689
|
+
return { enabled: true, registered: false, reason: 'E_NO_HOOK_SEAM', hooks: [], runtime };
|
|
690
|
+
}
|
|
691
|
+
runtime.ctx = ctx;
|
|
692
|
+
let disposeHook = null;
|
|
693
|
+
try {
|
|
694
|
+
disposeHook = ctx.on('session/event', (session, event) => runtime.onSessionEvent(session, event));
|
|
695
|
+
} catch (error) {
|
|
696
|
+
warn(runtime.logger, `autoProcedure 监听注册失败:${error?.message ?? error}`);
|
|
697
|
+
return { enabled: true, registered: false, reason: 'E_HOOK_FAILED', hooks: [], runtime };
|
|
698
|
+
}
|
|
699
|
+
runtime.registered = true;
|
|
700
|
+
if (typeof disposeHook === 'function' && typeof ctx?.effect === 'function') {
|
|
701
|
+
try {
|
|
702
|
+
ctx.effect(() => () => {
|
|
703
|
+
try {
|
|
704
|
+
runtime.dispose();
|
|
705
|
+
} finally {
|
|
706
|
+
disposeHook();
|
|
707
|
+
}
|
|
708
|
+
}, 'longlive.auto-procedure');
|
|
709
|
+
} catch {
|
|
710
|
+
/* fake context without an effect scope: process lifetime is fine */
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
const started = runtime.start().catch((error) => {
|
|
714
|
+
runtime.lastError = String(error?.message ?? error);
|
|
715
|
+
return { ok: false, code: 'E_AP_START_FAILED' };
|
|
716
|
+
});
|
|
717
|
+
return { enabled: true, registered: true, reason: null, hooks: ['session/event'], runtime, started };
|
|
718
|
+
}
|