@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,1367 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Resident session watchdog: out-of-app, threshold-driven visible truncation.
|
|
3
|
+
//
|
|
4
|
+
// Why a second resident script exists
|
|
5
|
+
// ------------------------------------
|
|
6
|
+
// scripts/resident-watcher.ps1 + watch-loop.ps1 consume *requests* written by
|
|
7
|
+
// the in-app plugin. That path closes and restarts the GUI around the cut,
|
|
8
|
+
// because a running host keeps the old sequence in memory. This script is the
|
|
9
|
+
// other half: it scans session logs on a schedule (size / event count / token
|
|
10
|
+
// estimate), checks that the file is not owned by a live host, and then calls
|
|
11
|
+
// the same truncate CLI the request path uses. It never closes, starts or
|
|
12
|
+
// talks to the GUI; a failed cut is a log line, not a host event.
|
|
13
|
+
//
|
|
14
|
+
// Modes (mirroring autoTruncate.mode)
|
|
15
|
+
// log plan in-process; never starts the CLI; never writes the session.
|
|
16
|
+
// dryrun call `truncate-cli.mjs --dry-run`; receipt proves nothing moved.
|
|
17
|
+
// request call `truncate-cli.mjs --confirm TRUNCATE-VISIBLE`; this is the
|
|
18
|
+
// real cut. It is refused while a live row / live pid / open handle
|
|
19
|
+
// exists (the CLI repeats the registry + handle check itself).
|
|
20
|
+
//
|
|
21
|
+
// Kill switch: `enabled: false` in the source of truth makes the next wake-up
|
|
22
|
+
// inert (the loop re-reads config every few seconds). A `stop.flag` file makes
|
|
23
|
+
// the loop exit entirely. No config change requires restarting the task.
|
|
24
|
+
//
|
|
25
|
+
// The script is deliberately dependency-free and runs on the DSH node runtime:
|
|
26
|
+
// node scripts/session-watch.mjs --config <path> --once
|
|
27
|
+
// node scripts/session-watch.mjs --config <path> --loop
|
|
28
|
+
// node scripts/session-watch.mjs --config <path> --check
|
|
29
|
+
// node scripts/session-watch.mjs --config <path> --once --dry-run
|
|
30
|
+
//
|
|
31
|
+
// Exit codes: 0 tick completed (even when a session failed -- fail-soft is the
|
|
32
|
+
// point), 2 bad arguments, 3 unusable config. A scheduled task therefore sees
|
|
33
|
+
// "success" for a noisy but healthy watcher and "failure" only for config rot.
|
|
34
|
+
|
|
35
|
+
import fs from 'node:fs';
|
|
36
|
+
import path from 'node:path';
|
|
37
|
+
import os from 'node:os';
|
|
38
|
+
import crypto from 'node:crypto';
|
|
39
|
+
import { fileURLToPath } from 'node:url';
|
|
40
|
+
import { spawnSync } from 'node:child_process';
|
|
41
|
+
|
|
42
|
+
import { parseSession } from '../src/codec.js';
|
|
43
|
+
import {
|
|
44
|
+
INFLIGHT_FILENAME,
|
|
45
|
+
inflightPathFor,
|
|
46
|
+
sessionEstimate,
|
|
47
|
+
} from '../src/truncate-visible.js';
|
|
48
|
+
import { liveList, pidAlive } from '../src/live.js';
|
|
49
|
+
import { normalizeAutoTruncateConfig } from '../src/auto-truncate.js';
|
|
50
|
+
|
|
51
|
+
const WATCH_VERSION = '1.0.0';
|
|
52
|
+
const MODES = Object.freeze(['log', 'dryrun', 'request']);
|
|
53
|
+
const SESSION_FILE = 'session.v4.jsonl.zstd';
|
|
54
|
+
const MAX_SCAN_DEPTH = 4;
|
|
55
|
+
const MAX_STATE_SESSIONS = 500;
|
|
56
|
+
const LOG_ROTATE_BYTES = 5 * 1024 * 1024;
|
|
57
|
+
const DISABLED_LOG_EVERY_MS = 10 * 60 * 1000;
|
|
58
|
+
const STOP_CHECK_MS = 5_000;
|
|
59
|
+
|
|
60
|
+
const DEFAULTS = Object.freeze({
|
|
61
|
+
enabled: true,
|
|
62
|
+
mode: 'dryrun',
|
|
63
|
+
intervalSeconds: 300,
|
|
64
|
+
settleSeconds: 10,
|
|
65
|
+
tokensThreshold: 300_000,
|
|
66
|
+
minTurns: 12,
|
|
67
|
+
bytesThreshold: 0,
|
|
68
|
+
eventsThreshold: 0,
|
|
69
|
+
keepTurns: 12,
|
|
70
|
+
keepTokens: 80_000,
|
|
71
|
+
firstUserCapChars: 4_000,
|
|
72
|
+
boundaryRetries: 3,
|
|
73
|
+
cooldownMinutes: 60,
|
|
74
|
+
profileConfig: '',
|
|
75
|
+
memoryRoot: '',
|
|
76
|
+
sessionsRoot: '',
|
|
77
|
+
dshHome: '',
|
|
78
|
+
nodeExe: '',
|
|
79
|
+
cliPath: '',
|
|
80
|
+
logPath: '',
|
|
81
|
+
statePath: '',
|
|
82
|
+
receiptDir: '',
|
|
83
|
+
lockPath: '',
|
|
84
|
+
lastTickPath: '',
|
|
85
|
+
stopFlag: '',
|
|
86
|
+
scanMaxFiles: 500,
|
|
87
|
+
cliTimeoutSeconds: 600,
|
|
88
|
+
logMaxBytes: LOG_ROTATE_BYTES,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
const CONFIG_KEYS = new Set(Object.keys(DEFAULTS).concat([
|
|
92
|
+
'version', 'taskName', 'installDir', 'notes',
|
|
93
|
+
]));
|
|
94
|
+
|
|
95
|
+
function scriptDir() {
|
|
96
|
+
return path.dirname(fileURLToPath(import.meta.url));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function packageRoot() {
|
|
100
|
+
return path.resolve(scriptDir(), '..');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function nowIso(now = Date.now()) {
|
|
104
|
+
return new Date(now).toISOString();
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function badConfig(message) {
|
|
108
|
+
const error = new Error(message);
|
|
109
|
+
error.code = 'WATCH_BAD_CONFIG';
|
|
110
|
+
return error;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function argError(message) {
|
|
114
|
+
const error = new Error(message);
|
|
115
|
+
error.code = 'WATCH_BAD_ARGUMENT';
|
|
116
|
+
return error;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function readText(file) {
|
|
120
|
+
let text = fs.readFileSync(file, 'utf8');
|
|
121
|
+
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
|
|
122
|
+
return text;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function resolveFrom(baseDir, value) {
|
|
126
|
+
if (typeof value !== 'string' || value.trim() === '') return '';
|
|
127
|
+
return path.isAbsolute(value) ? path.normalize(value) : path.resolve(baseDir, value);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function asObject(value, label) {
|
|
131
|
+
if (value == null) return {};
|
|
132
|
+
if (typeof value !== 'object' || Array.isArray(value)) {
|
|
133
|
+
throw badConfig(`${label} must be a JSON object`);
|
|
134
|
+
}
|
|
135
|
+
return value;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function cfgString(raw, key, fallback) {
|
|
139
|
+
const value = raw[key];
|
|
140
|
+
if (value === undefined || value === null) return fallback;
|
|
141
|
+
if (typeof value !== 'string') throw badConfig(`${key} must be a string`);
|
|
142
|
+
return value;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function cfgBool(raw, key, fallback) {
|
|
146
|
+
const value = raw[key];
|
|
147
|
+
if (value === undefined || value === null) return fallback;
|
|
148
|
+
if (typeof value !== 'boolean') throw badConfig(`${key} must be a boolean`);
|
|
149
|
+
return value;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function cfgInt(raw, key, fallback, { min = 0, max = Number.MAX_SAFE_INTEGER } = {}) {
|
|
153
|
+
const value = raw[key];
|
|
154
|
+
if (value === undefined || value === null) return fallback;
|
|
155
|
+
if (!Number.isInteger(value) || value < min || value > max) {
|
|
156
|
+
throw badConfig(`${key} must be an integer in [${min}, ${max}] (got ${JSON.stringify(value)})`);
|
|
157
|
+
}
|
|
158
|
+
return value;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// ---------------------------------------------------------------------- YAML
|
|
162
|
+
// cordis.patch.yml is YAML, but the watcher only needs the scalar children of
|
|
163
|
+
// the `autoTruncate:` block. Pulling in a YAML parser (or writing a full one)
|
|
164
|
+
// would add a dependency for four integers and a mode string, so this is a
|
|
165
|
+
// deliberately narrow indentation reader: direct children of the *last*
|
|
166
|
+
// autoTruncate block, scalar values only, no anchors/flow collections.
|
|
167
|
+
export function extractAutoTruncateBlock(text) {
|
|
168
|
+
const lines = String(text ?? '').split(/\r?\n/);
|
|
169
|
+
let start = -1;
|
|
170
|
+
let baseIndent = 0;
|
|
171
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
172
|
+
const match = /^([ \t]*)autoTruncate[ \t]*:[ \t]*(?:#.*)?$/.exec(lines[i]);
|
|
173
|
+
if (match) {
|
|
174
|
+
start = i;
|
|
175
|
+
baseIndent = match[1].length;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (start < 0) return { found: false, raw: {} };
|
|
179
|
+
|
|
180
|
+
const raw = {};
|
|
181
|
+
let childIndent = null;
|
|
182
|
+
for (let i = start + 1; i < lines.length; i += 1) {
|
|
183
|
+
const line = lines[i];
|
|
184
|
+
if (line.trim() === '' || /^[ \t]*#/.test(line)) continue;
|
|
185
|
+
const indent = (line.match(/^[ \t]*/) ?? [''])[0].length;
|
|
186
|
+
if (indent <= baseIndent) break;
|
|
187
|
+
const match = /^[ \t]*([A-Za-z0-9_.-]+)[ \t]*:[ \t]*(.*)$/.exec(line);
|
|
188
|
+
if (!match) continue;
|
|
189
|
+
if (childIndent === null) childIndent = indent;
|
|
190
|
+
if (indent !== childIndent) continue;
|
|
191
|
+
const valueText = stripYamlComment(match[2]).trim();
|
|
192
|
+
if (valueText === '') continue;
|
|
193
|
+
const parsedValue = parseYamlScalar(valueText);
|
|
194
|
+
if (parsedValue !== undefined) raw[match[1]] = parsedValue;
|
|
195
|
+
}
|
|
196
|
+
return { found: true, raw };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function stripYamlComment(value) {
|
|
200
|
+
let quote = null;
|
|
201
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
202
|
+
const ch = value[i];
|
|
203
|
+
if (quote) {
|
|
204
|
+
if (ch === quote) quote = null;
|
|
205
|
+
else if (ch === '\\' && quote === '"') i += 1;
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
if (ch === '"' || ch === "'") {
|
|
209
|
+
quote = ch;
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (ch === '#' && (i === 0 || /\s/.test(value[i - 1]))) return value.slice(0, i);
|
|
213
|
+
}
|
|
214
|
+
return value;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function parseYamlScalar(text) {
|
|
218
|
+
if (text === 'true') return true;
|
|
219
|
+
if (text === 'false') return false;
|
|
220
|
+
if (text === 'null' || text === '~') return null;
|
|
221
|
+
if (/^-?[0-9]+$/.test(text)) return Number(text);
|
|
222
|
+
if (/^-?[0-9]+\.[0-9]+$/.test(text)) return Number(text);
|
|
223
|
+
if (
|
|
224
|
+
(text.startsWith('"') && text.endsWith('"') && text.length >= 2)
|
|
225
|
+
|| (text.startsWith("'") && text.endsWith("'") && text.length >= 2)
|
|
226
|
+
) {
|
|
227
|
+
const inner = text.slice(1, -1);
|
|
228
|
+
return text[0] === '"'
|
|
229
|
+
? inner.replace(/\\"/g, '"').replace(/\\\\/g, '\\')
|
|
230
|
+
: inner.replace(/''/g, "'");
|
|
231
|
+
}
|
|
232
|
+
if (text.startsWith('{') || text.startsWith('[')) return undefined;
|
|
233
|
+
return text;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ------------------------------------------------------------------- config
|
|
237
|
+
function profileOverrides(profileConfig, baseDir) {
|
|
238
|
+
const file = resolveFrom(baseDir, profileConfig);
|
|
239
|
+
if (!fs.existsSync(file)) {
|
|
240
|
+
throw badConfig(`profileConfig does not exist: ${file}`);
|
|
241
|
+
}
|
|
242
|
+
if (!fs.statSync(file).isFile()) throw badConfig(`profileConfig is not a file: ${file}`);
|
|
243
|
+
let parsed;
|
|
244
|
+
try {
|
|
245
|
+
parsed = extractAutoTruncateBlock(readText(file));
|
|
246
|
+
} catch (error) {
|
|
247
|
+
throw badConfig(`cannot read profileConfig ${file}: ${error?.message ?? error}`);
|
|
248
|
+
}
|
|
249
|
+
let normalized;
|
|
250
|
+
try {
|
|
251
|
+
// Reuse the plugin's own validation: a typo in mode must fail closed here
|
|
252
|
+
// exactly as it would in the app, not silently fall back to dryrun.
|
|
253
|
+
normalized = normalizeAutoTruncateConfig(parsed.found ? parsed.raw : {});
|
|
254
|
+
} catch (error) {
|
|
255
|
+
throw badConfig(`autoTruncate block in ${file} is invalid: ${error?.message ?? error}`);
|
|
256
|
+
}
|
|
257
|
+
return { file, found: parsed.found, config: normalized };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function loadConfig(configPath, { checkOnly = false } = {}) {
|
|
261
|
+
const absConfig = path.resolve(configPath);
|
|
262
|
+
if (!fs.existsSync(absConfig)) throw badConfig(`config does not exist: ${absConfig}`);
|
|
263
|
+
let raw;
|
|
264
|
+
try {
|
|
265
|
+
raw = JSON.parse(readText(absConfig));
|
|
266
|
+
} catch (error) {
|
|
267
|
+
throw badConfig(`config is not valid JSON: ${absConfig} (${error?.message ?? error})`);
|
|
268
|
+
}
|
|
269
|
+
raw = asObject(raw, 'config');
|
|
270
|
+
const baseDir = path.dirname(absConfig);
|
|
271
|
+
const warnings = [];
|
|
272
|
+
const unknown = Object.keys(raw).filter((key) => !CONFIG_KEYS.has(key));
|
|
273
|
+
if (unknown.length > 0) warnings.push(`ignoring unknown config keys: ${unknown.join(', ')}`);
|
|
274
|
+
|
|
275
|
+
const enabled = cfgBool(raw, 'enabled', DEFAULTS.enabled);
|
|
276
|
+
const fileMode = cfgString(raw, 'mode', DEFAULTS.mode).trim().toLowerCase();
|
|
277
|
+
if (!MODES.includes(fileMode)) {
|
|
278
|
+
throw badConfig(`mode must be one of ${MODES.join('|')} (got ${JSON.stringify(fileMode)})`);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const dshHomeInput = cfgString(raw, 'dshHome', '').trim();
|
|
282
|
+
const sessionsRootInput = cfgString(raw, 'sessionsRoot', '').trim();
|
|
283
|
+
let dshHomePath = resolveFrom(baseDir, dshHomeInput)
|
|
284
|
+
|| (process.env.DSH_HOME ? path.resolve(process.env.DSH_HOME) : path.join(os.homedir(), '.dsh'));
|
|
285
|
+
let sessionsRoot = resolveFrom(baseDir, sessionsRootInput);
|
|
286
|
+
if (!sessionsRoot) {
|
|
287
|
+
sessionsRoot = path.join(dshHomePath, 'sessions');
|
|
288
|
+
} else if (!dshHomeInput && path.basename(sessionsRoot).toLowerCase() === 'sessions') {
|
|
289
|
+
// The CLI proves --session is under <DSH_HOME>/sessions; infer the home
|
|
290
|
+
// from a caller-supplied sessions root so the two cannot disagree.
|
|
291
|
+
dshHomePath = path.dirname(sessionsRoot);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const memoryRootInput = cfgString(raw, 'memoryRoot', '').trim();
|
|
295
|
+
const memoryRoot = resolveFrom(baseDir, memoryRootInput)
|
|
296
|
+
|| (process.env.DSH_MEM ? path.resolve(process.env.DSH_MEM) : path.join(dshHomePath, 'longlive-memory'));
|
|
297
|
+
|
|
298
|
+
const profileConfigInput = cfgString(raw, 'profileConfig', '').trim();
|
|
299
|
+
let profile = null;
|
|
300
|
+
let profileFile = '';
|
|
301
|
+
if (profileConfigInput) {
|
|
302
|
+
profile = profileOverrides(profileConfigInput, baseDir);
|
|
303
|
+
profileFile = profile.file;
|
|
304
|
+
if (!profile.found) {
|
|
305
|
+
// A profile without an autoTruncate block says nothing about the
|
|
306
|
+
// watcher. Treating the plugin defaults as an override would silently
|
|
307
|
+
// turn a dryrun install into log mode, so fall back to config.json.
|
|
308
|
+
warnings.push(`profileConfig ${profile.file} has no autoTruncate block; using config.json values`);
|
|
309
|
+
profile = null;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
let mode = fileMode;
|
|
314
|
+
let modeSource = 'config';
|
|
315
|
+
let auto = null;
|
|
316
|
+
if (profile) {
|
|
317
|
+
auto = profile.config;
|
|
318
|
+
mode = auto.mode;
|
|
319
|
+
modeSource = `profile:${profile.file}`;
|
|
320
|
+
}
|
|
321
|
+
if (!MODES.includes(mode)) throw badConfig(`resolved mode is not supported: ${JSON.stringify(mode)}`);
|
|
322
|
+
|
|
323
|
+
// Kill switch is an AND across layers: a profile may override mode and
|
|
324
|
+
// thresholds, but it must not be able to re-enable a watcher that the
|
|
325
|
+
// operator disabled in config.json. Either layer false means no action.
|
|
326
|
+
const effectiveEnabled = profile ? (enabled && auto.enabled) : enabled;
|
|
327
|
+
const tokensThreshold = profile ? auto.tokensThreshold : cfgInt(raw, 'tokensThreshold', DEFAULTS.tokensThreshold, { min: 0 });
|
|
328
|
+
const minTurns = profile ? auto.minTurns : cfgInt(raw, 'minTurns', DEFAULTS.minTurns, { min: 0 });
|
|
329
|
+
const keepTurns = profile ? auto.keepTurns : cfgInt(raw, 'keepTurns', DEFAULTS.keepTurns, { min: 1 });
|
|
330
|
+
const keepTokens = profile ? auto.keepTokens : cfgInt(raw, 'keepTokens', DEFAULTS.keepTokens, { min: 1 });
|
|
331
|
+
const firstUserCapChars = profile
|
|
332
|
+
? auto.firstUserCapChars
|
|
333
|
+
: cfgInt(raw, 'firstUserCapChars', DEFAULTS.firstUserCapChars, { min: 1 });
|
|
334
|
+
const boundaryRetries = profile
|
|
335
|
+
? auto.boundaryRetries
|
|
336
|
+
: cfgInt(raw, 'boundaryRetries', DEFAULTS.boundaryRetries, { min: 0 });
|
|
337
|
+
const cooldownMinutes = profile
|
|
338
|
+
? auto.cooldownMinutes
|
|
339
|
+
: cfgInt(raw, 'cooldownMinutes', DEFAULTS.cooldownMinutes, { min: 0 });
|
|
340
|
+
|
|
341
|
+
const config = {
|
|
342
|
+
version: cfgInt(raw, 'version', 1, { min: 1 }),
|
|
343
|
+
configPath: absConfig,
|
|
344
|
+
configDir: baseDir,
|
|
345
|
+
enabled: effectiveEnabled,
|
|
346
|
+
mode,
|
|
347
|
+
modeSource,
|
|
348
|
+
fileMode,
|
|
349
|
+
profile,
|
|
350
|
+
intervalSeconds: cfgInt(raw, 'intervalSeconds', DEFAULTS.intervalSeconds, { min: 1 }),
|
|
351
|
+
settleSeconds: cfgInt(raw, 'settleSeconds', DEFAULTS.settleSeconds, { min: 0 }),
|
|
352
|
+
tokensThreshold,
|
|
353
|
+
minTurns,
|
|
354
|
+
bytesThreshold: cfgInt(raw, 'bytesThreshold', DEFAULTS.bytesThreshold, { min: 0 }),
|
|
355
|
+
eventsThreshold: cfgInt(raw, 'eventsThreshold', DEFAULTS.eventsThreshold, { min: 0 }),
|
|
356
|
+
keepTurns,
|
|
357
|
+
keepTokens,
|
|
358
|
+
firstUserCapChars,
|
|
359
|
+
boundaryRetries,
|
|
360
|
+
cooldownMinutes,
|
|
361
|
+
profileConfig: profileFile,
|
|
362
|
+
memoryRoot,
|
|
363
|
+
sessionsRoot,
|
|
364
|
+
dshHome: dshHomePath,
|
|
365
|
+
nodeExe: resolveFrom(baseDir, cfgString(raw, 'nodeExe', '').trim()) || process.execPath,
|
|
366
|
+
cliPath: resolveFrom(baseDir, cfgString(raw, 'cliPath', '').trim())
|
|
367
|
+
|| path.join(packageRoot(), 'scripts', 'truncate-cli.mjs'),
|
|
368
|
+
logPath: '',
|
|
369
|
+
statePath: '',
|
|
370
|
+
receiptDir: '',
|
|
371
|
+
lockPath: '',
|
|
372
|
+
lastTickPath: '',
|
|
373
|
+
stopFlag: '',
|
|
374
|
+
scanMaxFiles: cfgInt(raw, 'scanMaxFiles', DEFAULTS.scanMaxFiles, { min: 1 }),
|
|
375
|
+
cliTimeoutSeconds: cfgInt(raw, 'cliTimeoutSeconds', DEFAULTS.cliTimeoutSeconds, { min: 10 }),
|
|
376
|
+
logMaxBytes: cfgInt(raw, 'logMaxBytes', DEFAULTS.logMaxBytes, { min: 1024 }),
|
|
377
|
+
taskName: cfgString(raw, 'taskName', 'DshSessionWatch'),
|
|
378
|
+
installDir: cfgString(raw, 'installDir', packageRoot()),
|
|
379
|
+
warnings,
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
const defaultsForPaths = {
|
|
383
|
+
logPath: path.join(memoryRoot, '.longlive', 'logs', 'session-watch.log'),
|
|
384
|
+
statePath: path.join(memoryRoot, '.longlive', 'session-watch', 'state.json'),
|
|
385
|
+
receiptDir: path.join(memoryRoot, '.longlive', 'session-watch', 'receipts'),
|
|
386
|
+
lockPath: path.join(memoryRoot, '.longlive', 'session-watch', 'watch.pid'),
|
|
387
|
+
lastTickPath: path.join(memoryRoot, '.longlive', 'session-watch', 'last-tick.json'),
|
|
388
|
+
stopFlag: path.join(memoryRoot, '.longlive', 'session-watch', 'stop.flag'),
|
|
389
|
+
};
|
|
390
|
+
for (const [key, fallback] of Object.entries(defaultsForPaths)) {
|
|
391
|
+
config[key] = resolveFrom(baseDir, cfgString(raw, key, '').trim()) || fallback;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// "At least one threshold" is not an error: a deliberately inert install is
|
|
395
|
+
// a valid way to stage the task before turning it on.
|
|
396
|
+
if (config.tokensThreshold === 0 && config.bytesThreshold === 0 && config.eventsThreshold === 0) {
|
|
397
|
+
config.warnings.push('all thresholds are 0: no session can ever become a candidate');
|
|
398
|
+
}
|
|
399
|
+
if (!fs.existsSync(config.nodeExe)) throw badConfig(`nodeExe does not exist: ${config.nodeExe}`);
|
|
400
|
+
if (!fs.existsSync(config.cliPath)) throw badConfig(`cliPath does not exist: ${config.cliPath}`);
|
|
401
|
+
if (!fs.existsSync(config.memoryRoot) || !fs.statSync(config.memoryRoot).isDirectory()) {
|
|
402
|
+
throw badConfig(`memoryRoot does not exist or is not a directory: ${config.memoryRoot}`);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
if (!checkOnly) {
|
|
406
|
+
for (const dir of [path.dirname(config.logPath), path.dirname(config.statePath), config.receiptDir,
|
|
407
|
+
path.dirname(config.lockPath), path.dirname(config.lastTickPath), path.dirname(config.stopFlag)]) {
|
|
408
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
return config;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function configForCheck(config) {
|
|
415
|
+
const result = { ...config };
|
|
416
|
+
delete result.profile;
|
|
417
|
+
result.enabled = config.enabled;
|
|
418
|
+
result.paths = {
|
|
419
|
+
nodeExe: config.nodeExe,
|
|
420
|
+
cliPath: config.cliPath,
|
|
421
|
+
logPath: config.logPath,
|
|
422
|
+
statePath: config.statePath,
|
|
423
|
+
receiptDir: config.receiptDir,
|
|
424
|
+
lockPath: config.lockPath,
|
|
425
|
+
stopFlag: config.stopFlag,
|
|
426
|
+
};
|
|
427
|
+
return result;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// --------------------------------------------------------------------- state
|
|
431
|
+
function readState(statePath) {
|
|
432
|
+
const empty = { version: 1, updatedAt: null, sessions: {} };
|
|
433
|
+
if (!fs.existsSync(statePath)) return empty;
|
|
434
|
+
try {
|
|
435
|
+
const parsed = JSON.parse(readText(statePath));
|
|
436
|
+
if (!parsed || typeof parsed !== 'object' || typeof parsed.sessions !== 'object' || parsed.sessions == null) {
|
|
437
|
+
return empty;
|
|
438
|
+
}
|
|
439
|
+
return { version: 1, updatedAt: parsed.updatedAt ?? null, sessions: parsed.sessions };
|
|
440
|
+
} catch {
|
|
441
|
+
try {
|
|
442
|
+
fs.renameSync(statePath, `${statePath}.corrupt-${Date.now()}`);
|
|
443
|
+
} catch { /* read-only evidence is not worth killing the tick */ }
|
|
444
|
+
return empty;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function writeDurable(file, text) {
|
|
449
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
450
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
451
|
+
const fd = fs.openSync(tmp, 'w');
|
|
452
|
+
try {
|
|
453
|
+
fs.writeFileSync(fd, text, 'utf8');
|
|
454
|
+
fs.fsyncSync(fd);
|
|
455
|
+
} finally {
|
|
456
|
+
fs.closeSync(fd);
|
|
457
|
+
}
|
|
458
|
+
fs.renameSync(tmp, file);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// A disabled or stopped tick is still a tick: record it so `status` can show
|
|
462
|
+
// the current kill-switch state instead of a stale last result.
|
|
463
|
+
function writeLastTick(config, summary) {
|
|
464
|
+
try {
|
|
465
|
+
writeDurable(config.lastTickPath, `${JSON.stringify(summary, null, 2)}\n`);
|
|
466
|
+
} catch { /* last-tick is convenience, not evidence */ }
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function writeState(config, state) {
|
|
470
|
+
const entries = Object.entries(state.sessions ?? {});
|
|
471
|
+
entries.sort((a, b) => (b[1]?.updatedAtMs ?? 0) - (a[1]?.updatedAtMs ?? 0));
|
|
472
|
+
const trimmed = Object.fromEntries(entries.slice(0, MAX_STATE_SESSIONS));
|
|
473
|
+
const body = {
|
|
474
|
+
version: 1,
|
|
475
|
+
updatedAt: nowIso(),
|
|
476
|
+
sessions: trimmed,
|
|
477
|
+
};
|
|
478
|
+
try {
|
|
479
|
+
writeDurable(config.statePath, `${JSON.stringify(body, null, 2)}\n`);
|
|
480
|
+
return true;
|
|
481
|
+
} catch (error) {
|
|
482
|
+
log(config, { event: 'state-write-failed', error: stringifyError(error) });
|
|
483
|
+
return false;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// ------------------------------------------------------------------ logging
|
|
488
|
+
function rotateLog(config) {
|
|
489
|
+
try {
|
|
490
|
+
const stat = fs.statSync(config.logPath);
|
|
491
|
+
if (stat.size <= config.logMaxBytes) return;
|
|
492
|
+
const old = `${config.logPath}.1`;
|
|
493
|
+
try { fs.rmSync(old, { force: true }); } catch { /* ignore */ }
|
|
494
|
+
fs.renameSync(config.logPath, old);
|
|
495
|
+
} catch { /* no log yet */ }
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function log(config, record, { alsoStderr = false } = {}) {
|
|
499
|
+
const line = JSON.stringify({ at: nowIso(), pid: process.pid, ...record });
|
|
500
|
+
try {
|
|
501
|
+
rotateLog(config);
|
|
502
|
+
fs.appendFileSync(config.logPath, `${line}\n`, 'utf8');
|
|
503
|
+
} catch (error) {
|
|
504
|
+
process.stderr.write(`session-watch: cannot write log ${config.logPath}: ${error?.message ?? error}\n`);
|
|
505
|
+
}
|
|
506
|
+
if (alsoStderr) process.stderr.write(`${line}\n`);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function stringifyError(error) {
|
|
510
|
+
return {
|
|
511
|
+
code: error?.code ?? null,
|
|
512
|
+
message: String(error?.message ?? error).slice(0, 2_000),
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// ----------------------------------------------------------------- scanning
|
|
517
|
+
function scanSessionFiles(root, maxFiles) {
|
|
518
|
+
const out = [];
|
|
519
|
+
if (!fs.existsSync(root)) return out;
|
|
520
|
+
const walk = (dir, depth) => {
|
|
521
|
+
if (out.length >= maxFiles || depth > MAX_SCAN_DEPTH) return;
|
|
522
|
+
let entries;
|
|
523
|
+
try {
|
|
524
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
525
|
+
} catch {
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
for (const entry of entries) {
|
|
529
|
+
if (out.length >= maxFiles) return;
|
|
530
|
+
const full = path.join(dir, entry.name);
|
|
531
|
+
if (entry.isDirectory()) {
|
|
532
|
+
walk(full, depth + 1);
|
|
533
|
+
} else if (entry.isFile() && entry.name === SESSION_FILE) {
|
|
534
|
+
out.push(full);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
walk(root, 0);
|
|
539
|
+
out.sort();
|
|
540
|
+
return out;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
function sessionMeta(file, config) {
|
|
544
|
+
const rel = path.relative(config.sessionsRoot, file);
|
|
545
|
+
const parts = rel.split(path.sep);
|
|
546
|
+
const scope = parts.length >= 3 ? parts[0] : '';
|
|
547
|
+
const folderId = path.basename(path.dirname(file));
|
|
548
|
+
return { scope, folderId };
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function localHostName() {
|
|
552
|
+
return os.hostname();
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function sameHost(host) {
|
|
556
|
+
return typeof host === 'string' && host.toLowerCase() === localHostName().toLowerCase();
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
function readLive(config) {
|
|
560
|
+
try {
|
|
561
|
+
const listed = liveList({ includeDead: true }, { memoryRoot: config.memoryRoot });
|
|
562
|
+
const byId = new Map();
|
|
563
|
+
for (const entry of listed.entries ?? []) {
|
|
564
|
+
const id = String(entry.sessionId ?? '').toLowerCase();
|
|
565
|
+
if (!id) continue;
|
|
566
|
+
if (!byId.has(id)) byId.set(id, []);
|
|
567
|
+
byId.get(id).push(entry);
|
|
568
|
+
}
|
|
569
|
+
return { ok: true, byId, count: listed.count ?? 0, error: null };
|
|
570
|
+
} catch (error) {
|
|
571
|
+
return { ok: false, byId: new Map(), count: 0, error: stringifyError(error) };
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
function healthCheck({ file, stat, ids, live, config, now }) {
|
|
576
|
+
const reasons = [];
|
|
577
|
+
if (!live.ok) {
|
|
578
|
+
reasons.push({ signal: 'live-registry', state: 'unavailable', detail: live.error?.message ?? 'unknown' });
|
|
579
|
+
} else {
|
|
580
|
+
for (const id of ids) {
|
|
581
|
+
for (const row of live.byId.get(id.toLowerCase()) ?? []) {
|
|
582
|
+
const state = row.effectiveState ?? row.state ?? 'unknown';
|
|
583
|
+
const pid = Number.isInteger(row.pid) ? row.pid : null;
|
|
584
|
+
const host = row.host ?? null;
|
|
585
|
+
if (state === 'corrupt') {
|
|
586
|
+
reasons.push({ signal: 'live-registry', state, sessionId: row.sessionId, detail: 'row is corrupt; fail closed' });
|
|
587
|
+
} else if (state === 'running' || state === 'waiting' || state === 'blocked' || state === 'idle') {
|
|
588
|
+
reasons.push({
|
|
589
|
+
signal: 'live-registry',
|
|
590
|
+
state,
|
|
591
|
+
sessionId: row.sessionId,
|
|
592
|
+
pid,
|
|
593
|
+
heartbeatAt: row.heartbeatAt ?? null,
|
|
594
|
+
detail: 'fresh heartbeat -- the writer still owns this session',
|
|
595
|
+
});
|
|
596
|
+
} else if (pid != null && pid > 0 && (host == null || sameHost(host)) && pidAlive(pid)) {
|
|
597
|
+
// stale/dead by heartbeat, but the recorded process is still here:
|
|
598
|
+
// a heartbeat writer can pause, a pid is harder evidence.
|
|
599
|
+
reasons.push({
|
|
600
|
+
signal: 'pid',
|
|
601
|
+
state,
|
|
602
|
+
sessionId: row.sessionId,
|
|
603
|
+
pid,
|
|
604
|
+
detail: 'recorded process is still alive',
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
if (now - stat.mtimeMs < config.settleSeconds * 1000) {
|
|
611
|
+
reasons.push({
|
|
612
|
+
signal: 'settle',
|
|
613
|
+
mtime: new Date(stat.mtimeMs).toISOString(),
|
|
614
|
+
settleSeconds: config.settleSeconds,
|
|
615
|
+
detail: 'file changed too recently; wait for the writer to finish',
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
const inflight = inflightPathFor(file);
|
|
619
|
+
if (fs.existsSync(inflight)) {
|
|
620
|
+
reasons.push({ signal: 'inflight', path: inflight, detail: 'another truncation left an in-flight record' });
|
|
621
|
+
}
|
|
622
|
+
return { ok: reasons.length === 0, reasons, inflightPath: inflight };
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function decisionFor(estimate, config) {
|
|
626
|
+
const reasons = [];
|
|
627
|
+
if (config.tokensThreshold > 0 && estimate.tokens >= config.tokensThreshold && estimate.turns > config.minTurns) {
|
|
628
|
+
reasons.push({
|
|
629
|
+
kind: 'tokens', value: estimate.tokens, threshold: config.tokensThreshold, minTurns: config.minTurns,
|
|
630
|
+
turns: estimate.turns,
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
if (config.bytesThreshold > 0 && estimate.bytes >= config.bytesThreshold) {
|
|
634
|
+
reasons.push({ kind: 'bytes', value: estimate.bytes, threshold: config.bytesThreshold });
|
|
635
|
+
}
|
|
636
|
+
if (config.eventsThreshold > 0 && estimate.events >= config.eventsThreshold) {
|
|
637
|
+
reasons.push({ kind: 'events', value: estimate.events, threshold: config.eventsThreshold });
|
|
638
|
+
}
|
|
639
|
+
return reasons;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
function cooldownWait(config, record, now) {
|
|
643
|
+
if (!record) return null;
|
|
644
|
+
if (record.failures > 0) {
|
|
645
|
+
const base = Math.max(config.cooldownMinutes, 5);
|
|
646
|
+
const minutes = Math.min(60, base * 2 ** Math.min(record.failures - 1, 3));
|
|
647
|
+
const until = (record.lastAttemptAtMs ?? 0) + minutes * 60_000;
|
|
648
|
+
if (until > now) return { until, minutes, kind: 'backoff' };
|
|
649
|
+
return null;
|
|
650
|
+
}
|
|
651
|
+
if (config.cooldownMinutes > 0 && record.lastAttemptAtMs) {
|
|
652
|
+
const until = record.lastAttemptAtMs + config.cooldownMinutes * 60_000;
|
|
653
|
+
if (until > now) return { until, minutes: config.cooldownMinutes, kind: 'cooldown' };
|
|
654
|
+
}
|
|
655
|
+
return null;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// ------------------------------------------------------------------- runner
|
|
659
|
+
function sha256File(file) {
|
|
660
|
+
return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function parseCliJson(stdout) {
|
|
664
|
+
const lines = String(stdout ?? '').split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
665
|
+
for (let i = lines.length - 1; i >= 0; i -= 1) {
|
|
666
|
+
if (!lines[i].startsWith('{')) continue;
|
|
667
|
+
try {
|
|
668
|
+
return JSON.parse(lines[i]);
|
|
669
|
+
} catch { /* keep looking */ }
|
|
670
|
+
}
|
|
671
|
+
return null;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
function runCli(config, file, mode) {
|
|
675
|
+
const args = [
|
|
676
|
+
config.cliPath,
|
|
677
|
+
'--session', file,
|
|
678
|
+
'--keep-turns', String(config.keepTurns),
|
|
679
|
+
'--keep-tokens', String(config.keepTokens),
|
|
680
|
+
'--first-user-cap', String(config.firstUserCapChars),
|
|
681
|
+
'--boundary-retries', String(config.boundaryRetries),
|
|
682
|
+
'--memory-root', config.memoryRoot,
|
|
683
|
+
];
|
|
684
|
+
if (mode === 'dryrun') {
|
|
685
|
+
args.push('--dry-run');
|
|
686
|
+
} else {
|
|
687
|
+
args.push('--confirm', 'TRUNCATE-VISIBLE');
|
|
688
|
+
}
|
|
689
|
+
const env = { ...process.env };
|
|
690
|
+
delete env.DSH_SESSION_ID;
|
|
691
|
+
env.DSH_HOME = config.dshHome;
|
|
692
|
+
env.DSH_MEM = config.memoryRoot;
|
|
693
|
+
|
|
694
|
+
const started = Date.now();
|
|
695
|
+
let result;
|
|
696
|
+
try {
|
|
697
|
+
result = spawnSync(config.nodeExe, args, {
|
|
698
|
+
cwd: path.dirname(config.cliPath),
|
|
699
|
+
env,
|
|
700
|
+
encoding: 'utf8',
|
|
701
|
+
windowsHide: true,
|
|
702
|
+
timeout: config.cliTimeoutSeconds * 1000,
|
|
703
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
704
|
+
});
|
|
705
|
+
} catch (error) {
|
|
706
|
+
return {
|
|
707
|
+
ok: false,
|
|
708
|
+
exitCode: null,
|
|
709
|
+
signal: null,
|
|
710
|
+
durationMs: Date.now() - started,
|
|
711
|
+
json: null,
|
|
712
|
+
error: stringifyError(error),
|
|
713
|
+
stderr: '',
|
|
714
|
+
argv: args,
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
const json = parseCliJson(result.stdout);
|
|
718
|
+
const timedOut = result.error?.code === 'ETIMEDOUT';
|
|
719
|
+
return {
|
|
720
|
+
ok: !timedOut && result.status === 0 && json != null && json.ok !== false,
|
|
721
|
+
exitCode: result.status,
|
|
722
|
+
signal: result.signal ?? null,
|
|
723
|
+
durationMs: Date.now() - started,
|
|
724
|
+
json,
|
|
725
|
+
error: result.error ? stringifyError(result.error) : null,
|
|
726
|
+
timedOut,
|
|
727
|
+
stderr: String(result.stderr ?? '').slice(0, 4_000),
|
|
728
|
+
argv: args,
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
function verifyDryRun({ file, beforeHash, archiveExistedBefore, cli }) {
|
|
733
|
+
const checks = [];
|
|
734
|
+
let afterHash = null;
|
|
735
|
+
try {
|
|
736
|
+
afterHash = sha256File(file);
|
|
737
|
+
} catch (error) {
|
|
738
|
+
checks.push({ name: 'session-readable-after', ok: false, detail: stringifyError(error) });
|
|
739
|
+
}
|
|
740
|
+
if (afterHash != null) {
|
|
741
|
+
checks.push({ name: 'session-unchanged', ok: afterHash === beforeHash, beforeHash, afterHash });
|
|
742
|
+
}
|
|
743
|
+
checks.push({ name: 'no-backup', ok: !cli.json?.backupPath, backupPath: cli.json?.backupPath ?? null });
|
|
744
|
+
const archivePath = cli.json?.archivePath ?? null;
|
|
745
|
+
if (archivePath) {
|
|
746
|
+
checks.push({
|
|
747
|
+
name: 'no-archive-created',
|
|
748
|
+
ok: archiveExistedBefore || !fs.existsSync(archivePath),
|
|
749
|
+
archivePath,
|
|
750
|
+
existedBefore: archiveExistedBefore,
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
checks.push({ name: 'no-inflight', ok: !fs.existsSync(inflightPathFor(file)) });
|
|
754
|
+
return { ok: checks.every((check) => check.ok), checks };
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
function verifyRequest({ file, beforeHash, beforeStat, cli }) {
|
|
758
|
+
const checks = [];
|
|
759
|
+
const json = cli.json;
|
|
760
|
+
if (!json) return { ok: false, checks: [{ name: 'cli-json', ok: false }] };
|
|
761
|
+
if (json.status === 'noop') {
|
|
762
|
+
checks.push({ name: 'cli-noop', ok: true, needed: json.needed === false });
|
|
763
|
+
checks.push({ name: 'session-unchanged-on-noop', ok: sha256File(file) === beforeHash });
|
|
764
|
+
return { ok: checks.every((check) => check.ok), checks };
|
|
765
|
+
}
|
|
766
|
+
const afterStat = (() => {
|
|
767
|
+
try { return fs.statSync(file); } catch { return null; }
|
|
768
|
+
})();
|
|
769
|
+
checks.push({
|
|
770
|
+
name: 'bytes-shrunk',
|
|
771
|
+
ok: Boolean(afterStat && json.bytes?.after != null && afterStat.size === json.bytes.after && afterStat.size < beforeStat.size),
|
|
772
|
+
beforeBytes: beforeStat.size,
|
|
773
|
+
afterBytes: afterStat?.size ?? null,
|
|
774
|
+
reportedAfter: json.bytes?.after ?? null,
|
|
775
|
+
});
|
|
776
|
+
checks.push({
|
|
777
|
+
name: 'reported-status',
|
|
778
|
+
ok: json.status === 'truncated' && json.applied === true,
|
|
779
|
+
status: json.status,
|
|
780
|
+
applied: json.applied,
|
|
781
|
+
});
|
|
782
|
+
const expectedAfter = json.after?.sha256 ?? null;
|
|
783
|
+
checks.push({
|
|
784
|
+
name: 'session-sha-matches-plan',
|
|
785
|
+
ok: expectedAfter != null && sha256File(file) === expectedAfter,
|
|
786
|
+
expected: expectedAfter,
|
|
787
|
+
});
|
|
788
|
+
checks.push({
|
|
789
|
+
name: 'snapshot-sha-matches',
|
|
790
|
+
ok: json.before?.sha256 === beforeHash,
|
|
791
|
+
cliSnapshot: json.before?.sha256 ?? null,
|
|
792
|
+
observed: beforeHash,
|
|
793
|
+
});
|
|
794
|
+
const backupPath = json.backupPath ?? null;
|
|
795
|
+
let backupOk = false;
|
|
796
|
+
let backupHash = null;
|
|
797
|
+
if (backupPath && fs.existsSync(backupPath)) {
|
|
798
|
+
backupHash = sha256File(backupPath);
|
|
799
|
+
backupOk = backupHash === beforeHash;
|
|
800
|
+
}
|
|
801
|
+
checks.push({
|
|
802
|
+
name: 'backup-exists-and-matches',
|
|
803
|
+
ok: backupOk,
|
|
804
|
+
backupPath,
|
|
805
|
+
backupHash,
|
|
806
|
+
expected: beforeHash,
|
|
807
|
+
});
|
|
808
|
+
const archivePath = json.archivePath ?? null;
|
|
809
|
+
checks.push({
|
|
810
|
+
name: 'archive-exists',
|
|
811
|
+
ok: Boolean(archivePath && fs.existsSync(archivePath)),
|
|
812
|
+
archivePath,
|
|
813
|
+
});
|
|
814
|
+
checks.push({ name: 'no-inflight-left', ok: !fs.existsSync(inflightPathFor(file)) });
|
|
815
|
+
return { ok: checks.every((check) => check.ok), checks };
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
function receiptPathFor(config, sessionId, mode, now) {
|
|
819
|
+
const stamp = nowIso(now).replace(/[-:]/g, '').replace(/\..*$/, '').replace('T', '-');
|
|
820
|
+
const safe = String(sessionId || 'session').replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 80);
|
|
821
|
+
return path.join(config.receiptDir, `${stamp}-${safe}-${mode}.json`);
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
function ensureEvidenceWritable(config) {
|
|
825
|
+
fs.mkdirSync(config.receiptDir, { recursive: true });
|
|
826
|
+
const probe = path.join(config.receiptDir, `.probe-${process.pid}`);
|
|
827
|
+
fs.writeFileSync(probe, 'ok', 'utf8');
|
|
828
|
+
fs.rmSync(probe, { force: true });
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
function makeReceiptMaybeUnique(config, sessionId, mode, now) {
|
|
832
|
+
let file = receiptPathFor(config, sessionId, mode, now);
|
|
833
|
+
if (fs.existsSync(file)) file = file.replace(/\.json$/, `-${process.pid}.json`);
|
|
834
|
+
return file;
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// --------------------------------------------------------------------- tick
|
|
838
|
+
function stopRequested(config) {
|
|
839
|
+
try {
|
|
840
|
+
return fs.existsSync(config.stopFlag);
|
|
841
|
+
} catch {
|
|
842
|
+
return false;
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
function tick(config, { verbose = false } = {}) {
|
|
847
|
+
const startedAt = Date.now();
|
|
848
|
+
const summary = {
|
|
849
|
+
ok: true,
|
|
850
|
+
at: nowIso(startedAt),
|
|
851
|
+
pid: process.pid,
|
|
852
|
+
version: WATCH_VERSION,
|
|
853
|
+
enabled: config.enabled,
|
|
854
|
+
mode: config.mode,
|
|
855
|
+
modeSource: config.modeSource,
|
|
856
|
+
configPath: config.configPath,
|
|
857
|
+
memoryRoot: config.memoryRoot,
|
|
858
|
+
sessionsRoot: config.sessionsRoot,
|
|
859
|
+
scanned: 0,
|
|
860
|
+
candidates: 0,
|
|
861
|
+
actions: [],
|
|
862
|
+
blocked: [],
|
|
863
|
+
errors: [],
|
|
864
|
+
intervalSeconds: config.intervalSeconds,
|
|
865
|
+
stop: false,
|
|
866
|
+
};
|
|
867
|
+
if (stopRequested(config)) {
|
|
868
|
+
summary.stop = true;
|
|
869
|
+
summary.status = 'stop-flag';
|
|
870
|
+
writeLastTick(config, summary);
|
|
871
|
+
return summary;
|
|
872
|
+
}
|
|
873
|
+
if (!config.enabled) {
|
|
874
|
+
summary.status = 'disabled';
|
|
875
|
+
writeLastTick(config, summary);
|
|
876
|
+
return summary;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
const live = readLive(config);
|
|
880
|
+
if (!live.ok) {
|
|
881
|
+
summary.errors.push({ stage: 'live-registry', ...live.error });
|
|
882
|
+
// Fail closed: no cut just because the registry became unreadable.
|
|
883
|
+
summary.ok = false;
|
|
884
|
+
summary.status = 'live-registry-unavailable';
|
|
885
|
+
writeLastTick(config, summary);
|
|
886
|
+
return summary;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
const state = readState(config.statePath);
|
|
890
|
+
let stateDirty = false;
|
|
891
|
+
let files;
|
|
892
|
+
try {
|
|
893
|
+
files = scanSessionFiles(config.sessionsRoot, config.scanMaxFiles);
|
|
894
|
+
} catch (error) {
|
|
895
|
+
summary.errors.push({ stage: 'scan', ...stringifyError(error) });
|
|
896
|
+
summary.ok = false;
|
|
897
|
+
summary.status = 'scan-failed';
|
|
898
|
+
return summary;
|
|
899
|
+
}
|
|
900
|
+
summary.scanned = files.length;
|
|
901
|
+
|
|
902
|
+
for (const file of files) {
|
|
903
|
+
if (stopRequested(config)) {
|
|
904
|
+
summary.stop = true;
|
|
905
|
+
break;
|
|
906
|
+
}
|
|
907
|
+
let stat;
|
|
908
|
+
try {
|
|
909
|
+
stat = fs.statSync(file);
|
|
910
|
+
} catch (error) {
|
|
911
|
+
summary.errors.push({ stage: 'stat', file, ...stringifyError(error) });
|
|
912
|
+
continue;
|
|
913
|
+
}
|
|
914
|
+
if (!stat.isFile() || stat.size === 0) continue;
|
|
915
|
+
|
|
916
|
+
const key = path.resolve(file).toLowerCase();
|
|
917
|
+
const meta = sessionMeta(file, config);
|
|
918
|
+
let record = state.sessions[key] ?? null;
|
|
919
|
+
let ids = [meta.folderId];
|
|
920
|
+
let estimate = null;
|
|
921
|
+
let parseError = null;
|
|
922
|
+
|
|
923
|
+
if (record && record.size === stat.size && record.mtimeMs === Math.trunc(stat.mtimeMs) && record.estimate) {
|
|
924
|
+
estimate = record.estimate;
|
|
925
|
+
ids = Array.isArray(record.ids) && record.ids.length > 0 ? record.ids : ids;
|
|
926
|
+
} else {
|
|
927
|
+
try {
|
|
928
|
+
const parsed = parseSession(fs.readFileSync(file));
|
|
929
|
+
estimate = sessionEstimate(parsed);
|
|
930
|
+
const headerId = typeof parsed.header?.id === 'string' ? parsed.header.id.trim() : '';
|
|
931
|
+
ids = headerId && headerId !== meta.folderId ? [meta.folderId, headerId] : [meta.folderId];
|
|
932
|
+
record = {
|
|
933
|
+
...(record ?? {}),
|
|
934
|
+
path: file,
|
|
935
|
+
size: stat.size,
|
|
936
|
+
mtimeMs: Math.trunc(stat.mtimeMs),
|
|
937
|
+
estimate,
|
|
938
|
+
ids,
|
|
939
|
+
updatedAtMs: Date.now(),
|
|
940
|
+
};
|
|
941
|
+
state.sessions[key] = record;
|
|
942
|
+
stateDirty = true;
|
|
943
|
+
} catch (error) {
|
|
944
|
+
parseError = error;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
if (parseError) {
|
|
949
|
+
// A torn log is usually a live writer; let health decide whether it is
|
|
950
|
+
// safety or just damage. Either way: never invoke the CLI on unparsed
|
|
951
|
+
// bytes, and back off so a permanently corrupt file cannot spin the CPU.
|
|
952
|
+
const health = healthCheck({ file, stat, ids, live, config, now: Date.now() });
|
|
953
|
+
summary.errors.push({
|
|
954
|
+
stage: 'parse', file, ...stringifyError(parseError),
|
|
955
|
+
health: health.ok ? 'free' : 'blocked',
|
|
956
|
+
healthReasons: health.reasons,
|
|
957
|
+
});
|
|
958
|
+
const now = Date.now();
|
|
959
|
+
const failures = (record?.failures ?? 0) + 1;
|
|
960
|
+
state.sessions[key] = {
|
|
961
|
+
...(record ?? { path: file }),
|
|
962
|
+
failures,
|
|
963
|
+
lastAttemptAtMs: now,
|
|
964
|
+
lastStatus: 'parse-error',
|
|
965
|
+
lastError: String(parseError.message ?? parseError).slice(0, 1_000),
|
|
966
|
+
updatedAtMs: now,
|
|
967
|
+
};
|
|
968
|
+
stateDirty = true;
|
|
969
|
+
continue;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
const reasons = decisionFor(estimate, config);
|
|
973
|
+
if (reasons.length === 0) continue;
|
|
974
|
+
summary.candidates += 1;
|
|
975
|
+
|
|
976
|
+
const now = Date.now();
|
|
977
|
+
const wait = cooldownWait(config, record, now);
|
|
978
|
+
if (wait) {
|
|
979
|
+
summary.blocked.push({
|
|
980
|
+
file, sessionId: ids[0], stage: 'cooldown', waitUntil: new Date(wait.until).toISOString(),
|
|
981
|
+
minutes: wait.minutes, kind: wait.kind,
|
|
982
|
+
});
|
|
983
|
+
continue;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
const health = healthCheck({ file, stat, ids, live, config, now });
|
|
987
|
+
if (!health.ok) {
|
|
988
|
+
summary.blocked.push({ file, sessionId: ids[0], stage: 'health', reasons: health.reasons });
|
|
989
|
+
state.sessions[key] = {
|
|
990
|
+
...(record ?? { path: file }),
|
|
991
|
+
lastBlockedAtMs: now,
|
|
992
|
+
lastStatus: 'blocked-live',
|
|
993
|
+
lastHealth: health.reasons,
|
|
994
|
+
updatedAtMs: now,
|
|
995
|
+
};
|
|
996
|
+
stateDirty = true;
|
|
997
|
+
continue;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
if (config.mode === 'log') {
|
|
1001
|
+
summary.actions.push({
|
|
1002
|
+
file, sessionId: ids[0], status: 'would-truncate', mode: 'log', reasons,
|
|
1003
|
+
estimate: { bytes: estimate.bytes, events: estimate.events, tokens: estimate.tokens, turns: estimate.turns },
|
|
1004
|
+
});
|
|
1005
|
+
state.sessions[key] = {
|
|
1006
|
+
...(record ?? { path: file }),
|
|
1007
|
+
lastWouldAtMs: now,
|
|
1008
|
+
lastStatus: 'would-truncate',
|
|
1009
|
+
updatedAtMs: now,
|
|
1010
|
+
};
|
|
1011
|
+
stateDirty = true;
|
|
1012
|
+
continue;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
try {
|
|
1016
|
+
ensureEvidenceWritable(config);
|
|
1017
|
+
} catch (error) {
|
|
1018
|
+
summary.errors.push({ stage: 'receipt-dir', file, ...stringifyError(error) });
|
|
1019
|
+
state.sessions[key] = {
|
|
1020
|
+
...(record ?? { path: file }),
|
|
1021
|
+
lastStatus: 'evidence-unwritable',
|
|
1022
|
+
lastError: String(error?.message ?? error).slice(0, 1_000),
|
|
1023
|
+
updatedAtMs: now,
|
|
1024
|
+
};
|
|
1025
|
+
stateDirty = true;
|
|
1026
|
+
continue;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
let beforeHash;
|
|
1030
|
+
let beforeStat;
|
|
1031
|
+
let archiveExistedBefore = false;
|
|
1032
|
+
try {
|
|
1033
|
+
beforeHash = sha256File(file);
|
|
1034
|
+
beforeStat = fs.statSync(file);
|
|
1035
|
+
} catch (error) {
|
|
1036
|
+
summary.errors.push({ stage: 'snapshot', file, ...stringifyError(error) });
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
const cli = runCli(config, file, config.mode);
|
|
1041
|
+
let verification;
|
|
1042
|
+
let status;
|
|
1043
|
+
if (cli.json?.code === 'SESSION_IS_RUNNING') {
|
|
1044
|
+
status = 'blocked-live';
|
|
1045
|
+
verification = { ok: false, skipped: 'session-is-running', code: cli.json.code };
|
|
1046
|
+
} else if (cli.exitCode !== 0 || !cli.json) {
|
|
1047
|
+
status = 'failed';
|
|
1048
|
+
verification = { ok: false, checks: [] };
|
|
1049
|
+
} else if (config.mode === 'dryrun') {
|
|
1050
|
+
// A dry-run can legitimately answer `infeasible` (keep budget too high):
|
|
1051
|
+
// that is a plan result, not a watcher failure. What must hold is that
|
|
1052
|
+
// nothing moved, so verification still checks the file bytes.
|
|
1053
|
+
const plannedArchive = cli.json?.archivePath ?? null;
|
|
1054
|
+
archiveExistedBefore = Boolean(plannedArchive && fs.existsSync(plannedArchive));
|
|
1055
|
+
verification = verifyDryRun({ file, beforeHash, archiveExistedBefore, cli });
|
|
1056
|
+
status = verification.ok
|
|
1057
|
+
? (cli.json?.status === 'noop' ? 'noop' : cli.json?.status === 'infeasible' ? 'infeasible' : 'planned')
|
|
1058
|
+
: 'failed-verification';
|
|
1059
|
+
} else {
|
|
1060
|
+
verification = verifyRequest({ file, beforeHash, beforeStat, cli });
|
|
1061
|
+
status = verification.ok
|
|
1062
|
+
? (cli.json?.status === 'noop' ? 'noop' : 'truncated')
|
|
1063
|
+
: 'failed-verification';
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
const receiptPath = makeReceiptMaybeUnique(config, ids[0], config.mode, now);
|
|
1067
|
+
const receipt = {
|
|
1068
|
+
version: 1,
|
|
1069
|
+
kind: 'session-watch',
|
|
1070
|
+
at: nowIso(now),
|
|
1071
|
+
host: localHostName(),
|
|
1072
|
+
watcherPid: process.pid,
|
|
1073
|
+
mode: config.mode,
|
|
1074
|
+
modeSource: config.modeSource,
|
|
1075
|
+
dryRun: config.mode !== 'request',
|
|
1076
|
+
configPath: config.configPath,
|
|
1077
|
+
profileConfig: config.profileConfig,
|
|
1078
|
+
memoryRoot: config.memoryRoot,
|
|
1079
|
+
session: {
|
|
1080
|
+
path: file,
|
|
1081
|
+
id: ids[0],
|
|
1082
|
+
ids,
|
|
1083
|
+
scope: meta.scope,
|
|
1084
|
+
sizeBefore: beforeStat.size,
|
|
1085
|
+
mtimeBefore: new Date(beforeStat.mtimeMs).toISOString(),
|
|
1086
|
+
sha256Before: beforeHash,
|
|
1087
|
+
},
|
|
1088
|
+
estimate,
|
|
1089
|
+
decision: reasons,
|
|
1090
|
+
health,
|
|
1091
|
+
cli,
|
|
1092
|
+
verification,
|
|
1093
|
+
status,
|
|
1094
|
+
wroteSession: config.mode === 'request' && status === 'truncated',
|
|
1095
|
+
};
|
|
1096
|
+
let receiptWritten = false;
|
|
1097
|
+
try {
|
|
1098
|
+
receipt.receiptPath = receiptPath;
|
|
1099
|
+
writeDurable(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`);
|
|
1100
|
+
receiptWritten = true;
|
|
1101
|
+
} catch (error) {
|
|
1102
|
+
summary.errors.push({ stage: 'receipt-write', file, ...stringifyError(error) });
|
|
1103
|
+
log(config, { event: 'receipt-write-failed', file, error: stringifyError(error) });
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
summary.actions.push({
|
|
1107
|
+
file,
|
|
1108
|
+
sessionId: ids[0],
|
|
1109
|
+
status,
|
|
1110
|
+
mode: config.mode,
|
|
1111
|
+
reasons,
|
|
1112
|
+
cliExitCode: cli.exitCode,
|
|
1113
|
+
cliStatus: cli.json?.status ?? null,
|
|
1114
|
+
verificationOk: verification.ok,
|
|
1115
|
+
receiptPath,
|
|
1116
|
+
receiptWritten,
|
|
1117
|
+
bytesBefore: beforeStat.size,
|
|
1118
|
+
bytesAfter: cli.json?.bytes?.after ?? null,
|
|
1119
|
+
backupPath: cli.json?.backupPath ?? null,
|
|
1120
|
+
});
|
|
1121
|
+
|
|
1122
|
+
record = {
|
|
1123
|
+
...(record ?? { path: file }),
|
|
1124
|
+
path: file,
|
|
1125
|
+
ids,
|
|
1126
|
+
lastAttemptAtMs: config.mode === 'request' ? now : (record?.lastAttemptAtMs ?? null),
|
|
1127
|
+
lastStatus: status,
|
|
1128
|
+
lastMode: config.mode,
|
|
1129
|
+
lastReceipt: receiptPath,
|
|
1130
|
+
lastVerification: verification.ok,
|
|
1131
|
+
lastError: cli.error?.message ?? null,
|
|
1132
|
+
failures: (config.mode === 'request' && status !== 'truncated' && status !== 'noop' && status !== 'blocked-live')
|
|
1133
|
+
? (record?.failures ?? 0) + 1
|
|
1134
|
+
: 0,
|
|
1135
|
+
updatedAtMs: now,
|
|
1136
|
+
};
|
|
1137
|
+
state.sessions[key] = record;
|
|
1138
|
+
stateDirty = true;
|
|
1139
|
+
log(config, {
|
|
1140
|
+
event: 'action', mode: config.mode, file, sessionId: ids[0], status,
|
|
1141
|
+
verificationOk: verification.ok, receipt: receiptPath, receiptWritten,
|
|
1142
|
+
cliExitCode: cli.exitCode, bytesBefore: beforeStat.size, bytesAfter: cli.json?.bytes?.after ?? null,
|
|
1143
|
+
}, { alsoStderr: verbose });
|
|
1144
|
+
|
|
1145
|
+
if (verification.ok && cli.json?.status !== 'noop' && config.mode === 'request') {
|
|
1146
|
+
state.sessions[key].lastTruncatedAtMs = now;
|
|
1147
|
+
state.sessions[key].lastBackup = cli.json?.backupPath ?? null;
|
|
1148
|
+
state.sessions[key].lastArchive = cli.json?.archivePath ?? null;
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
if (stateDirty) writeState(config, state);
|
|
1153
|
+
summary.ok = summary.errors.length === 0;
|
|
1154
|
+
summary.status = summary.ok ? 'ok' : 'degraded';
|
|
1155
|
+
writeLastTick(config, summary);
|
|
1156
|
+
return summary;
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
// --------------------------------------------------------------------- loop
|
|
1160
|
+
function sleep(ms) {
|
|
1161
|
+
return new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
function acquireLock(config) {
|
|
1165
|
+
const lockPath = config.lockPath;
|
|
1166
|
+
fs.mkdirSync(path.dirname(lockPath), { recursive: true });
|
|
1167
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1168
|
+
try {
|
|
1169
|
+
const fd = fs.openSync(lockPath, 'wx');
|
|
1170
|
+
try {
|
|
1171
|
+
fs.writeFileSync(fd, `${process.pid}\n`, 'utf8');
|
|
1172
|
+
fs.fsyncSync(fd);
|
|
1173
|
+
} finally {
|
|
1174
|
+
fs.closeSync(fd);
|
|
1175
|
+
}
|
|
1176
|
+
return { ok: true };
|
|
1177
|
+
} catch (error) {
|
|
1178
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
1179
|
+
let holder = null;
|
|
1180
|
+
try { holder = Number.parseInt(readText(lockPath).trim(), 10); } catch { /* unreadable */ }
|
|
1181
|
+
if (Number.isInteger(holder) && holder > 0 && holder !== process.pid && pidAlive(holder)) {
|
|
1182
|
+
return { ok: false, holder };
|
|
1183
|
+
}
|
|
1184
|
+
try { fs.rmSync(lockPath, { force: true }); } catch { /* retry */ }
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
return { ok: false, holder: null };
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
function releaseLock(config) {
|
|
1191
|
+
try {
|
|
1192
|
+
const holder = Number.parseInt(readText(config.lockPath).trim(), 10);
|
|
1193
|
+
if (holder === process.pid) fs.rmSync(config.lockPath, { force: true });
|
|
1194
|
+
} catch { /* no lock */ }
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
async function loop(configPath, options) {
|
|
1198
|
+
let stop = false;
|
|
1199
|
+
const onSignal = () => { stop = true; };
|
|
1200
|
+
process.on('SIGINT', onSignal);
|
|
1201
|
+
process.on('SIGTERM', onSignal);
|
|
1202
|
+
let lastScanAt = 0;
|
|
1203
|
+
let lastDisabledLogAt = 0;
|
|
1204
|
+
let lastErrorLogAt = 0;
|
|
1205
|
+
let config = null;
|
|
1206
|
+
let lock = null;
|
|
1207
|
+
try {
|
|
1208
|
+
config = loadConfig(configPath);
|
|
1209
|
+
lock = acquireLock(config);
|
|
1210
|
+
if (!lock.ok) {
|
|
1211
|
+
process.stderr.write(`session-watch: another watcher holds ${config.lockPath} (pid ${lock.holder ?? 'unknown'}); exiting\n`);
|
|
1212
|
+
return 0;
|
|
1213
|
+
}
|
|
1214
|
+
log(config, { event: 'loop-start', version: WATCH_VERSION, configPath: config.configPath, mode: config.mode });
|
|
1215
|
+
while (!stop) {
|
|
1216
|
+
let current;
|
|
1217
|
+
try {
|
|
1218
|
+
current = loadConfig(configPath, { checkOnly: true });
|
|
1219
|
+
} catch (error) {
|
|
1220
|
+
if (Date.now() - lastErrorLogAt > DISABLED_LOG_EVERY_MS) {
|
|
1221
|
+
lastErrorLogAt = Date.now();
|
|
1222
|
+
process.stderr.write(`session-watch: config error, not acting: ${error?.message ?? error}\n`);
|
|
1223
|
+
if (config) log(config, { event: 'config-error', error: stringifyError(error) });
|
|
1224
|
+
}
|
|
1225
|
+
await sleep(STOP_CHECK_MS);
|
|
1226
|
+
continue;
|
|
1227
|
+
}
|
|
1228
|
+
if (stopRequested(current)) {
|
|
1229
|
+
log(current, { event: 'stop-flag', path: current.stopFlag });
|
|
1230
|
+
return 0;
|
|
1231
|
+
}
|
|
1232
|
+
if (!current.enabled) {
|
|
1233
|
+
if (Date.now() - lastDisabledLogAt > DISABLED_LOG_EVERY_MS) {
|
|
1234
|
+
lastDisabledLogAt = Date.now();
|
|
1235
|
+
log(current, { event: 'disabled', mode: current.mode, modeSource: current.modeSource });
|
|
1236
|
+
}
|
|
1237
|
+
await sleep(STOP_CHECK_MS);
|
|
1238
|
+
continue;
|
|
1239
|
+
}
|
|
1240
|
+
const intervalMs = current.intervalSeconds * 1000;
|
|
1241
|
+
if (Date.now() - lastScanAt >= intervalMs) {
|
|
1242
|
+
const summary = tick(current, { verbose: options.verbose });
|
|
1243
|
+
lastScanAt = Date.now();
|
|
1244
|
+
log(current, { event: 'tick', ...summary }, { alsoStderr: options.verbose });
|
|
1245
|
+
if (summary.stop) return 0;
|
|
1246
|
+
}
|
|
1247
|
+
const wait = Math.max(1_000, Math.min(STOP_CHECK_MS, intervalMs - (Date.now() - lastScanAt)));
|
|
1248
|
+
await sleep(wait);
|
|
1249
|
+
}
|
|
1250
|
+
return 0;
|
|
1251
|
+
} finally {
|
|
1252
|
+
if (lock?.ok) {
|
|
1253
|
+
releaseLock(config);
|
|
1254
|
+
log(config, { event: 'loop-stop', version: WATCH_VERSION });
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
// --------------------------------------------------------------------- main
|
|
1260
|
+
function parseArgs(argv) {
|
|
1261
|
+
const options = {
|
|
1262
|
+
configPath: path.resolve(scriptDir(), '..', 'session-watch.config.json'),
|
|
1263
|
+
once: false,
|
|
1264
|
+
loop: false,
|
|
1265
|
+
dryRun: false,
|
|
1266
|
+
check: false,
|
|
1267
|
+
verbose: false,
|
|
1268
|
+
help: false,
|
|
1269
|
+
};
|
|
1270
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
1271
|
+
const arg = argv[i];
|
|
1272
|
+
const take = () => {
|
|
1273
|
+
const value = argv[i + 1];
|
|
1274
|
+
if (value === undefined || value.startsWith('--')) throw argError(`${arg} needs a value`);
|
|
1275
|
+
i += 1;
|
|
1276
|
+
return value;
|
|
1277
|
+
};
|
|
1278
|
+
if (arg === '--config') options.configPath = path.resolve(take());
|
|
1279
|
+
else if (arg === '--once') options.once = true;
|
|
1280
|
+
else if (arg === '--loop') options.loop = true;
|
|
1281
|
+
else if (arg === '--dry-run') options.dryRun = true;
|
|
1282
|
+
else if (arg === '--check') options.check = true;
|
|
1283
|
+
else if (arg === '--verbose') options.verbose = true;
|
|
1284
|
+
else if (arg === '--help' || arg === '-h') options.help = true;
|
|
1285
|
+
else throw argError(`unknown argument: ${arg}`);
|
|
1286
|
+
}
|
|
1287
|
+
if (options.once && options.loop) throw argError('--once and --loop are mutually exclusive');
|
|
1288
|
+
if (!options.once && !options.loop && !options.check && !options.help) options.once = true;
|
|
1289
|
+
return options;
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
function usage() {
|
|
1293
|
+
return [
|
|
1294
|
+
'session-watch: resident threshold watchdog for visible truncation',
|
|
1295
|
+
'',
|
|
1296
|
+
' node scripts/session-watch.mjs --config <config.json> --check',
|
|
1297
|
+
' node scripts/session-watch.mjs --config <config.json> --once [--dry-run]',
|
|
1298
|
+
' node scripts/session-watch.mjs --config <config.json> --loop',
|
|
1299
|
+
'',
|
|
1300
|
+
' --dry-run force mode=dryrun for this run (never upgrades to a write)',
|
|
1301
|
+
' --verbose mirror log lines to stderr',
|
|
1302
|
+
].join('\n');
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
async function main() {
|
|
1306
|
+
let options;
|
|
1307
|
+
try {
|
|
1308
|
+
options = parseArgs(process.argv.slice(2));
|
|
1309
|
+
} catch (error) {
|
|
1310
|
+
process.stderr.write(`${error.message}\n`);
|
|
1311
|
+
process.exitCode = 2;
|
|
1312
|
+
return;
|
|
1313
|
+
}
|
|
1314
|
+
if (options.help) {
|
|
1315
|
+
process.stdout.write(`${usage()}\n`);
|
|
1316
|
+
return;
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
let config;
|
|
1320
|
+
try {
|
|
1321
|
+
config = loadConfig(options.configPath, { checkOnly: options.check });
|
|
1322
|
+
} catch (error) {
|
|
1323
|
+
const body = { ok: false, code: error?.code ?? 'WATCH_CONFIG_FAILED', message: String(error?.message ?? error) };
|
|
1324
|
+
process.stdout.write(`${JSON.stringify(body)}\n`);
|
|
1325
|
+
process.exitCode = 3;
|
|
1326
|
+
return;
|
|
1327
|
+
}
|
|
1328
|
+
if (options.dryRun) {
|
|
1329
|
+
config.mode = 'dryrun';
|
|
1330
|
+
config.modeSource = `${config.modeSource}+cli:--dry-run`;
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
if (options.check) {
|
|
1334
|
+
const body = { ok: true, status: 'checked', ...configForCheck(config) };
|
|
1335
|
+
process.stdout.write(`${JSON.stringify(body, null, 2)}\n`);
|
|
1336
|
+
process.exitCode = 0;
|
|
1337
|
+
return;
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
if (options.loop) {
|
|
1341
|
+
const code = await loop(options.configPath, { verbose: options.verbose });
|
|
1342
|
+
process.exitCode = code;
|
|
1343
|
+
return;
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
// --once: one tick, fail-soft. A session-level failure is reported in the
|
|
1347
|
+
// JSON but does not become a non-zero exit, so a scheduler/manual run does
|
|
1348
|
+
// not conflate "the watcher is broken" with "one log is corrupt".
|
|
1349
|
+
const summary = tick(config, { verbose: options.verbose });
|
|
1350
|
+
const body = { ok: summary.ok, ...summary, configPath: config.configPath };
|
|
1351
|
+
log(config, { event: 'tick-once', ...body }, { alsoStderr: options.verbose });
|
|
1352
|
+
process.stdout.write(`${JSON.stringify(body, null, 2)}\n`);
|
|
1353
|
+
process.exitCode = 0;
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
const invokedDirectly = process.argv[1]
|
|
1357
|
+
&& path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
|
|
1358
|
+
|
|
1359
|
+
if (invokedDirectly) {
|
|
1360
|
+
main().catch((error) => {
|
|
1361
|
+
const body = { ok: false, code: error?.code ?? 'WATCH_FATAL', message: String(error?.message ?? error) };
|
|
1362
|
+
try { process.stderr.write(`${JSON.stringify(body)}\n`); } catch { /* ignore */ }
|
|
1363
|
+
process.exitCode = 3;
|
|
1364
|
+
});
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
export { DEFAULTS, MODES, tick, decisionFor, healthCheck, cooldownWait };
|