@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,1233 @@
|
|
|
1
|
+
// src/handoff/store.js — the handoff card's file layer (02, v4).
|
|
2
|
+
//
|
|
3
|
+
// Two derived areas under <memoryRoot>/.longlive (no new top-level directory):
|
|
4
|
+
// bridge/<safeSrc>.handoff-card.json per-session latest card
|
|
5
|
+
// bridge/<safeSelf>.handoff.json per-session O_EXCL claim (unique gate)
|
|
6
|
+
// bridge/handoff-claim-<cardId>.json per-card claim (pid-recoverable)
|
|
7
|
+
// board/handoff.jsonl (+ handoff-YYYYMM.jsonl) append-only audit board
|
|
8
|
+
//
|
|
9
|
+
// Boundedness (N6/M4): every audit append is followed by a throttled trim
|
|
10
|
+
// (`maybeTrimAuditBoard`); once the board exceeds 256 KiB it is streamed from
|
|
11
|
+
// the *head*, the rows that roll out of a 500-row window are archived by month
|
|
12
|
+
// with an idempotency key (`h`), and the line count is proven conserved before
|
|
13
|
+
// the main file is rewritten (fail-closed: on any doubt, no rewrite).
|
|
14
|
+
//
|
|
15
|
+
// Nothing here throws for IO failures: every function returns {ok, code}.
|
|
16
|
+
// `readLiveRow` is the only cross-module reader (live.js `liveGet`), and it is
|
|
17
|
+
// wrapped so a corrupt/locked row becomes a fail-closed `unreadable`.
|
|
18
|
+
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import os from 'node:os';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
import { randomBytes } from 'node:crypto';
|
|
23
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
24
|
+
|
|
25
|
+
import { liveGet } from '../live.js';
|
|
26
|
+
import { isInsideRoot } from '../memory/paths.js';
|
|
27
|
+
import { safeSessionId } from '../identity/card-marker.js';
|
|
28
|
+
import { appendJsonLine } from '../util/append-store.js';
|
|
29
|
+
import {
|
|
30
|
+
AUDIT_SCHEMA,
|
|
31
|
+
HANDOFF_CARD_RETENTION_EXTRA_MS,
|
|
32
|
+
HANDOFF_CLAIM_GRACE_MS,
|
|
33
|
+
HANDOFF_DEFAULT_MAX_AGE_MS,
|
|
34
|
+
HANDOFF_MAX_CLAIM_ATTEMPTS,
|
|
35
|
+
HANDOFF_TRIM_ARCHIVE_TAIL_BYTES,
|
|
36
|
+
HANDOFF_TRIM_MIN_INTERVAL_MS,
|
|
37
|
+
charLengthOf,
|
|
38
|
+
cardIdOf,
|
|
39
|
+
hash8,
|
|
40
|
+
lineHashOf,
|
|
41
|
+
} from './model.js';
|
|
42
|
+
|
|
43
|
+
export const BUNDLE_DIR = path.join('.longlive', 'bridge');
|
|
44
|
+
export const BOARD_DIR = path.join('.longlive', 'board');
|
|
45
|
+
export const LATEST_CARD_SUFFIX = '.handoff-card.json';
|
|
46
|
+
export const SESSION_CLAIM_SUFFIX = '.handoff.json';
|
|
47
|
+
export const CARD_CLAIM_PREFIX = 'handoff-claim-';
|
|
48
|
+
export const AUDIT_FILE_NAME = 'handoff.jsonl';
|
|
49
|
+
export const ARCHIVE_FILE_RE = /^handoff-(\d{6})\.jsonl$/;
|
|
50
|
+
export const LATEST_CARD_MAX_BYTES = 16 * 1024;
|
|
51
|
+
export const TRIM_CHUNK_BYTES = 256 * 1024;
|
|
52
|
+
export const TRIM_MAX_BYTES = 256 * 1024;
|
|
53
|
+
export const TRIM_WINDOW_ROWS = 500;
|
|
54
|
+
export const ARCHIVE_MAX_BATCH = 200;
|
|
55
|
+
export const AUDIT_TAIL_BYTES = 64 * 1024;
|
|
56
|
+
export const AUDIT_TAIL_LIMIT = 50;
|
|
57
|
+
export const PRUNE_LIMIT = 128;
|
|
58
|
+
|
|
59
|
+
const trimThrottle = new Map(); // memoryRoot -> last trim attempt (ms)
|
|
60
|
+
|
|
61
|
+
function clampInt(value, fallback, min, max) {
|
|
62
|
+
const number = Number(value);
|
|
63
|
+
if (!Number.isFinite(number)) return fallback;
|
|
64
|
+
return Math.min(max, Math.max(min, Math.floor(number)));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function resolvedRoot(memoryRoot) {
|
|
68
|
+
const raw = typeof memoryRoot === 'string' ? memoryRoot.trim() : '';
|
|
69
|
+
if (raw === '') return null;
|
|
70
|
+
try {
|
|
71
|
+
return path.resolve(raw);
|
|
72
|
+
} catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Resolve one derived file and prove it stays inside <memoryRoot>/.longlive. */
|
|
78
|
+
function inside(root, file) {
|
|
79
|
+
if (root === null) return null;
|
|
80
|
+
const resolved = path.resolve(file);
|
|
81
|
+
try {
|
|
82
|
+
if (!isInsideRoot(root, resolved)) return null;
|
|
83
|
+
} catch {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
return resolved;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function handoffBoardDir(memoryRoot) {
|
|
90
|
+
const root = resolvedRoot(memoryRoot);
|
|
91
|
+
return root === null ? null : inside(root, path.join(root, BOARD_DIR));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function handoffAuditFile(memoryRoot) {
|
|
95
|
+
const root = resolvedRoot(memoryRoot);
|
|
96
|
+
return root === null ? null : inside(root, path.join(root, BOARD_DIR, AUDIT_FILE_NAME));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function handoffArchiveFile(memoryRoot, monthKey) {
|
|
100
|
+
const root = resolvedRoot(memoryRoot);
|
|
101
|
+
const month = /^\d{6}$/.test(String(monthKey ?? '')) ? String(monthKey) : '000000';
|
|
102
|
+
return root === null ? null : inside(root, path.join(root, BOARD_DIR, `handoff-${month}.jsonl`));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function latestCardFile(memoryRoot, sessionId) {
|
|
106
|
+
const root = resolvedRoot(memoryRoot);
|
|
107
|
+
if (root === null) return null;
|
|
108
|
+
const safe = safeSessionId(sessionId);
|
|
109
|
+
return inside(root, path.join(root, BUNDLE_DIR, `${safe}${LATEST_CARD_SUFFIX}`));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function sessionClaimFile(memoryRoot, sessionId) {
|
|
113
|
+
const root = resolvedRoot(memoryRoot);
|
|
114
|
+
if (root === null) return null;
|
|
115
|
+
const safe = safeSessionId(sessionId);
|
|
116
|
+
return inside(root, path.join(root, BUNDLE_DIR, `${safe}${SESSION_CLAIM_SUFFIX}`));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function cardClaimFile(memoryRoot, cardId) {
|
|
120
|
+
const root = resolvedRoot(memoryRoot);
|
|
121
|
+
if (root === null) return null;
|
|
122
|
+
const safe = String(cardId ?? '').replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 64);
|
|
123
|
+
return inside(root, path.join(root, BUNDLE_DIR, `${CARD_CLAIM_PREFIX}${safe}.json`));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function monthKeyOf(value) {
|
|
127
|
+
const date = value instanceof Date ? value : new Date(value ?? Date.now());
|
|
128
|
+
if (!Number.isFinite(date.getTime())) return '000000';
|
|
129
|
+
return `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function hostname() {
|
|
133
|
+
const name = os.hostname();
|
|
134
|
+
return typeof name === 'string' && name.trim() !== '' ? name.trim() : 'unknown-host';
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function sameHost(host) {
|
|
138
|
+
return typeof host === 'string' && host.trim().toLowerCase() === hostname().toLowerCase();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function pidAliveOf(pid) {
|
|
142
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
143
|
+
try {
|
|
144
|
+
process.kill(pid, 0);
|
|
145
|
+
return true;
|
|
146
|
+
} catch (error) {
|
|
147
|
+
return error?.code === 'EPERM';
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function isoOf(ms) {
|
|
152
|
+
return new Date(Number.isFinite(ms) ? ms : Date.now()).toISOString();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function ensureDir(dir) {
|
|
156
|
+
try {
|
|
157
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
158
|
+
return true;
|
|
159
|
+
} catch {
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function unlinkQuiet(file) {
|
|
165
|
+
try {
|
|
166
|
+
fs.unlinkSync(file);
|
|
167
|
+
return true;
|
|
168
|
+
} catch {
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function readText(file) {
|
|
174
|
+
try {
|
|
175
|
+
return fs.readFileSync(file, 'utf8');
|
|
176
|
+
} catch {
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function statOrNull(file) {
|
|
182
|
+
try {
|
|
183
|
+
return fs.statSync(file);
|
|
184
|
+
} catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* tmp + fsync + read-back + rename for one JSON document.
|
|
191
|
+
* Read-back happens on the tmp file, before the rename, so a short write never
|
|
192
|
+
* replaces the previous good file.
|
|
193
|
+
*/
|
|
194
|
+
function writeAtomicJson(file, value) {
|
|
195
|
+
const dir = path.dirname(file);
|
|
196
|
+
if (!ensureDir(dir)) return { ok: false, code: 'E_HANDOFF_WRITE' };
|
|
197
|
+
const text = `${JSON.stringify(value)}\n`;
|
|
198
|
+
const tmp = path.join(dir, `.${path.basename(file)}.tmp-${process.pid}-${Date.now()}-${randomBytes(4).toString('hex')}`);
|
|
199
|
+
let fd;
|
|
200
|
+
try {
|
|
201
|
+
fd = fs.openSync(tmp, 'wx', 0o600);
|
|
202
|
+
fs.writeSync(fd, text, null, 'utf8');
|
|
203
|
+
fs.fsyncSync(fd);
|
|
204
|
+
fs.closeSync(fd);
|
|
205
|
+
fd = undefined;
|
|
206
|
+
if (readText(tmp) !== text) {
|
|
207
|
+
unlinkQuiet(tmp);
|
|
208
|
+
return { ok: false, code: 'E_HANDOFF_WRITE_READBACK' };
|
|
209
|
+
}
|
|
210
|
+
fs.renameSync(tmp, file);
|
|
211
|
+
return { ok: true, path: file, bytes: Buffer.byteLength(text, 'utf8') };
|
|
212
|
+
} catch (error) {
|
|
213
|
+
if (fd !== undefined) {
|
|
214
|
+
try { fs.closeSync(fd); } catch { /* already closed */ }
|
|
215
|
+
}
|
|
216
|
+
unlinkQuiet(tmp);
|
|
217
|
+
return { ok: false, code: error?.code ?? 'E_HANDOFF_WRITE' };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ------------------------------------------------------------------ latest cards
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Read one per-session latest card. Bounded to 16 KiB; a missing file is
|
|
225
|
+
* `{ok:true, present:false}`, a malformed/oversized one is `{ok:false}`.
|
|
226
|
+
*/
|
|
227
|
+
export function readLatestCard(memoryRoot, sessionId) {
|
|
228
|
+
const file = latestCardFile(memoryRoot, sessionId);
|
|
229
|
+
if (file === null) return { ok: false, present: false, code: 'E_HANDOFF_NO_ROOT' };
|
|
230
|
+
const stat = statOrNull(file);
|
|
231
|
+
if (stat === null) return { ok: true, present: false, file };
|
|
232
|
+
if (!stat.isFile() || stat.size > LATEST_CARD_MAX_BYTES) {
|
|
233
|
+
return { ok: false, present: true, file, code: 'E_HANDOFF_CORRUPT' };
|
|
234
|
+
}
|
|
235
|
+
const text = readText(file);
|
|
236
|
+
if (text === null) return { ok: false, present: true, file, code: 'E_HANDOFF_READ' };
|
|
237
|
+
let card;
|
|
238
|
+
try {
|
|
239
|
+
card = JSON.parse(text.replace(/^\uFEFF/, ''));
|
|
240
|
+
} catch {
|
|
241
|
+
return { ok: false, present: true, file, code: 'E_HANDOFF_CORRUPT' };
|
|
242
|
+
}
|
|
243
|
+
return { ok: true, present: true, file, card, sessionId };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Read the newest N latest-card files. mtime-descending and bounded — the
|
|
248
|
+
* consumer never reads the audit board or an unbounded directory.
|
|
249
|
+
*/
|
|
250
|
+
export function readLatestCards(memoryRoot, options = {}) {
|
|
251
|
+
const root = resolvedRoot(memoryRoot);
|
|
252
|
+
const dir = root === null ? null : inside(root, path.join(root, BUNDLE_DIR));
|
|
253
|
+
if (dir === null) return { ok: false, code: 'E_HANDOFF_NO_ROOT', cards: [] };
|
|
254
|
+
const maxFiles = clampInt(options.maxFiles, 64, 8, 256);
|
|
255
|
+
let names;
|
|
256
|
+
try {
|
|
257
|
+
names = fs.readdirSync(dir, { withFileTypes: true });
|
|
258
|
+
} catch (error) {
|
|
259
|
+
if (error?.code === 'ENOENT') return { ok: true, cards: [], scanned: 0 };
|
|
260
|
+
return { ok: false, code: error?.code === 'ENOENT' ? 'E_HANDOFF_READ' : 'E_HANDOFF_READ', cards: [] };
|
|
261
|
+
}
|
|
262
|
+
const candidates = [];
|
|
263
|
+
for (const entry of names) {
|
|
264
|
+
if (!entry.isFile() || !entry.name.endsWith(LATEST_CARD_SUFFIX)) continue;
|
|
265
|
+
if (entry.name.startsWith('.')) continue;
|
|
266
|
+
const file = path.join(dir, entry.name);
|
|
267
|
+
const stat = statOrNull(file);
|
|
268
|
+
if (stat === null) continue;
|
|
269
|
+
candidates.push({ file, mtimeMs: stat.mtimeMs, size: stat.size });
|
|
270
|
+
}
|
|
271
|
+
candidates.sort((left, right) => right.mtimeMs - left.mtimeMs);
|
|
272
|
+
const cards = [];
|
|
273
|
+
let bad = 0;
|
|
274
|
+
for (const candidate of candidates.slice(0, maxFiles)) {
|
|
275
|
+
const fileSessionId = path.basename(candidate.file).slice(0, -LATEST_CARD_SUFFIX.length);
|
|
276
|
+
if (candidate.size > LATEST_CARD_MAX_BYTES) {
|
|
277
|
+
bad += 1;
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
const text = readText(candidate.file);
|
|
281
|
+
if (text === null) {
|
|
282
|
+
bad += 1;
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
let card;
|
|
286
|
+
try {
|
|
287
|
+
card = JSON.parse(text.replace(/^\uFEFF/, ''));
|
|
288
|
+
} catch {
|
|
289
|
+
bad += 1;
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
// gate 0's file-name check: the safe name we read must round-trip to the id
|
|
293
|
+
// stored inside the card (a copy of someone else's card is not a candidate).
|
|
294
|
+
if (safeSessionId(card?.source?.sessionId) !== fileSessionId) {
|
|
295
|
+
bad += 1;
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
cards.push({
|
|
299
|
+
card,
|
|
300
|
+
cardId: cardIdOf({ sessionId: card?.source?.sessionId, turn: card?.turn }),
|
|
301
|
+
file: candidate.file,
|
|
302
|
+
fileSessionId,
|
|
303
|
+
size: candidate.size,
|
|
304
|
+
mtimeMs: candidate.mtimeMs,
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
return { ok: true, cards, scanned: candidates.length, bad };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Atomic tmp+fsync+read-back+rename write of one latest card. */
|
|
311
|
+
export function writeLatestCardAtomic(memoryRoot, card) {
|
|
312
|
+
if (!card || typeof card !== 'object' || typeof card.source?.sessionId !== 'string') {
|
|
313
|
+
return { ok: false, code: 'E_HANDOFF_WRITE' };
|
|
314
|
+
}
|
|
315
|
+
const file = latestCardFile(memoryRoot, card.source.sessionId);
|
|
316
|
+
if (file === null) return { ok: false, code: 'E_HANDOFF_NO_ROOT' };
|
|
317
|
+
return writeAtomicJson(file, card);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ------------------------------------------------------------------ audit board
|
|
321
|
+
|
|
322
|
+
function appendRawLine(file, line) {
|
|
323
|
+
const dir = path.dirname(file);
|
|
324
|
+
if (!ensureDir(dir)) return { ok: false, code: 'E_HANDOFF_WRITE' };
|
|
325
|
+
const fd = fs.openSync(file, 'a');
|
|
326
|
+
try {
|
|
327
|
+
fs.writeSync(fd, `${line}\n`, null, 'utf8');
|
|
328
|
+
try { fs.fsyncSync(fd); } catch { /* best effort */ }
|
|
329
|
+
return { ok: true };
|
|
330
|
+
} catch (error) {
|
|
331
|
+
return { ok: false, code: error?.code ?? 'E_HANDOFF_WRITE' };
|
|
332
|
+
} finally {
|
|
333
|
+
try { fs.closeSync(fd); } catch { /* already closed */ }
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Append one audit row. No正文, no plaintext cwd — the caller builds the row.
|
|
339
|
+
* Adds the M4 idempotency key `h`, then runs the throttled boundedness trim.
|
|
340
|
+
*/
|
|
341
|
+
export function appendAudit(memoryRoot, row) {
|
|
342
|
+
const file = handoffAuditFile(memoryRoot);
|
|
343
|
+
if (file === null) return { ok: false, code: 'E_HANDOFF_NO_ROOT' };
|
|
344
|
+
let withHash;
|
|
345
|
+
try {
|
|
346
|
+
withHash = { ...row, h: lineHashOf(JSON.stringify(row)) };
|
|
347
|
+
} catch {
|
|
348
|
+
withHash = { ...row };
|
|
349
|
+
}
|
|
350
|
+
const result = appendJsonLine({ file, row: withHash, label: 'handoff', healthRoot: memoryRoot ?? undefined });
|
|
351
|
+
try {
|
|
352
|
+
maybeTrimAuditBoard(memoryRoot);
|
|
353
|
+
} catch {
|
|
354
|
+
/* trim is opportunistic; the append already happened */
|
|
355
|
+
}
|
|
356
|
+
return result;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function parseJsonLine(line) {
|
|
360
|
+
try {
|
|
361
|
+
return JSON.parse(line.replace(/^\uFEFF/, ''));
|
|
362
|
+
} catch {
|
|
363
|
+
return null;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** Read only the board's tail (panel/acceptance); never the whole file. */
|
|
368
|
+
export function readAuditTail(memoryRoot, options = {}) {
|
|
369
|
+
const file = handoffAuditFile(memoryRoot);
|
|
370
|
+
if (file === null) return { ok: false, present: false, rows: [], lines: 0, code: 'E_HANDOFF_NO_ROOT' };
|
|
371
|
+
const stat = statOrNull(file);
|
|
372
|
+
if (stat === null) return { ok: true, present: false, rows: [], lines: 0, file };
|
|
373
|
+
if (!stat.isFile()) return { ok: false, present: false, rows: [], lines: 0, code: 'E_HANDOFF_READ' };
|
|
374
|
+
const maxBytes = clampInt(options.maxBytes, AUDIT_TAIL_BYTES, 1024, 4 * 1024 * 1024);
|
|
375
|
+
const limit = clampInt(options.limit, AUDIT_TAIL_LIMIT, 1, 500);
|
|
376
|
+
const start = Math.max(0, stat.size - maxBytes);
|
|
377
|
+
const length = stat.size - start;
|
|
378
|
+
let fd;
|
|
379
|
+
try {
|
|
380
|
+
fd = fs.openSync(file, 'r');
|
|
381
|
+
} catch {
|
|
382
|
+
return { ok: false, present: false, rows: [], lines: 0, code: 'E_HANDOFF_READ' };
|
|
383
|
+
}
|
|
384
|
+
try {
|
|
385
|
+
const buffer = Buffer.alloc(length);
|
|
386
|
+
let read = 0;
|
|
387
|
+
while (read < length) {
|
|
388
|
+
const chunk = fs.readSync(fd, buffer, read, length - read, start + read);
|
|
389
|
+
if (chunk <= 0) break;
|
|
390
|
+
read += chunk;
|
|
391
|
+
}
|
|
392
|
+
let text = buffer.subarray(0, read).toString('utf8');
|
|
393
|
+
if (start > 0) {
|
|
394
|
+
const newline = text.indexOf('\n');
|
|
395
|
+
text = newline === -1 ? '' : text.slice(newline + 1);
|
|
396
|
+
}
|
|
397
|
+
const lines = text.split('\n').filter((line) => line.trim() !== '');
|
|
398
|
+
let bad = 0;
|
|
399
|
+
const rows = [];
|
|
400
|
+
for (const line of lines) {
|
|
401
|
+
const parsed = parseJsonLine(line);
|
|
402
|
+
if (parsed === null) bad += 1;
|
|
403
|
+
else rows.push(parsed);
|
|
404
|
+
}
|
|
405
|
+
return { ok: true, present: true, file, rows: rows.slice(-limit), lines: lines.length, bad, bytes: stat.size };
|
|
406
|
+
} catch {
|
|
407
|
+
return { ok: false, present: false, rows: [], lines: 0, code: 'E_HANDOFF_READ' };
|
|
408
|
+
} finally {
|
|
409
|
+
try { fs.closeSync(fd); } catch { /* already closed */ }
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** Read only the month archive's tail and rebuild its idempotency-key set. */
|
|
414
|
+
export function readArchiveTail(memoryRoot, monthKey, options = {}) {
|
|
415
|
+
const file = handoffArchiveFile(memoryRoot, monthKey);
|
|
416
|
+
if (file === null) return { ok: false, rows: [], count: 0, code: 'E_HANDOFF_NO_ROOT' };
|
|
417
|
+
const stat = statOrNull(file);
|
|
418
|
+
if (stat === null) return { ok: true, file, rows: [], count: 0 };
|
|
419
|
+
if (!stat.isFile()) return { ok: false, file, rows: [], count: 0, code: 'E_HANDOFF_READ' };
|
|
420
|
+
const maxBytes = clampInt(options.maxBytes, HANDOFF_TRIM_ARCHIVE_TAIL_BYTES, 1024, 4 * 1024 * 1024);
|
|
421
|
+
const start = Math.max(0, stat.size - maxBytes);
|
|
422
|
+
const length = stat.size - start;
|
|
423
|
+
let fd;
|
|
424
|
+
try {
|
|
425
|
+
fd = fs.openSync(file, 'r');
|
|
426
|
+
} catch {
|
|
427
|
+
return { ok: false, file, rows: [], count: 0, code: 'E_HANDOFF_READ' };
|
|
428
|
+
}
|
|
429
|
+
try {
|
|
430
|
+
const buffer = Buffer.alloc(length);
|
|
431
|
+
let read = 0;
|
|
432
|
+
while (read < length) {
|
|
433
|
+
const chunk = fs.readSync(fd, buffer, read, length - read, start + read);
|
|
434
|
+
if (chunk <= 0) break;
|
|
435
|
+
read += chunk;
|
|
436
|
+
}
|
|
437
|
+
let text = buffer.subarray(0, read).toString('utf8');
|
|
438
|
+
if (start > 0) {
|
|
439
|
+
const newline = text.indexOf('\n');
|
|
440
|
+
text = newline === -1 ? '' : text.slice(newline + 1);
|
|
441
|
+
}
|
|
442
|
+
const lines = text.split('\n').filter((line) => line.trim() !== '');
|
|
443
|
+
let count = 0;
|
|
444
|
+
const rows = [];
|
|
445
|
+
for (const line of lines) {
|
|
446
|
+
count += 1;
|
|
447
|
+
const parsed = parseJsonLine(line);
|
|
448
|
+
const h = parsed && typeof parsed.h === 'string' && parsed.h !== '' ? parsed.h : lineHashOf(line);
|
|
449
|
+
rows.push({ h });
|
|
450
|
+
}
|
|
451
|
+
return { ok: true, file, rows, count, bytes: stat.size };
|
|
452
|
+
} catch {
|
|
453
|
+
return { ok: false, file, rows: [], count: 0, code: 'E_HANDOFF_READ' };
|
|
454
|
+
} finally {
|
|
455
|
+
try { fs.closeSync(fd); } catch { /* already closed */ }
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Full-stream index of one month archive: total line count + the set of
|
|
461
|
+
* idempotency keys. Used when the cheap tail window cannot prove that a batch
|
|
462
|
+
* was already archived (the tail-only check in the v4 design cannot prove
|
|
463
|
+
* idempotency for batches older than the tail window, which is exactly the
|
|
464
|
+
* "archive append succeeded, main rename failed" crash case). Bounded by
|
|
465
|
+
* `maxBytes`; above it the caller must fail closed (no rewrite, retry later).
|
|
466
|
+
*/
|
|
467
|
+
export function readArchiveIndex(memoryRoot, monthKey, options = {}) {
|
|
468
|
+
const file = handoffArchiveFile(memoryRoot, monthKey);
|
|
469
|
+
if (file === null) return { ok: false, code: 'E_HANDOFF_NO_ROOT', keys: new Set(), count: 0 };
|
|
470
|
+
const stat = statOrNull(file);
|
|
471
|
+
if (stat === null) return { ok: true, file, keys: new Set(), count: 0, bytes: 0 };
|
|
472
|
+
if (!stat.isFile()) return { ok: false, code: 'E_HANDOFF_READ', keys: new Set(), count: 0, file };
|
|
473
|
+
const cap = clampInt(options.maxBytes, 32 * 1024 * 1024, 1024, 256 * 1024 * 1024);
|
|
474
|
+
if (stat.size > cap) return { ok: false, code: 'E_HANDOFF_TRIM_ARCHIVE_UNVERIFIED', keys: new Set(), count: 0, file };
|
|
475
|
+
let fd;
|
|
476
|
+
try {
|
|
477
|
+
fd = fs.openSync(file, 'r');
|
|
478
|
+
} catch {
|
|
479
|
+
return { ok: false, code: 'E_HANDOFF_READ', keys: new Set(), count: 0, file };
|
|
480
|
+
}
|
|
481
|
+
try {
|
|
482
|
+
const buffer = Buffer.allocUnsafe(TRIM_CHUNK_BYTES);
|
|
483
|
+
const decoder = new StringDecoder('utf8');
|
|
484
|
+
const keys = new Set();
|
|
485
|
+
let count = 0;
|
|
486
|
+
let carry = '';
|
|
487
|
+
const pushLine = (line) => {
|
|
488
|
+
const value = line.endsWith('\r') ? line.slice(0, -1) : line;
|
|
489
|
+
if (value.trim() === '') return;
|
|
490
|
+
count += 1;
|
|
491
|
+
const parsed = parseJsonLine(value);
|
|
492
|
+
keys.add(parsed && typeof parsed.h === 'string' && parsed.h !== '' ? parsed.h : lineHashOf(value));
|
|
493
|
+
};
|
|
494
|
+
let position = 0;
|
|
495
|
+
for (;;) {
|
|
496
|
+
const read = fs.readSync(fd, buffer, 0, buffer.length, position);
|
|
497
|
+
if (read <= 0) break;
|
|
498
|
+
position += read;
|
|
499
|
+
carry += decoder.write(buffer.subarray(0, read));
|
|
500
|
+
let newline = carry.indexOf('\n');
|
|
501
|
+
while (newline !== -1) {
|
|
502
|
+
pushLine(carry.slice(0, newline));
|
|
503
|
+
carry = carry.slice(newline + 1);
|
|
504
|
+
newline = carry.indexOf('\n');
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
carry += decoder.end();
|
|
508
|
+
if (carry.trim() !== '') pushLine(carry);
|
|
509
|
+
return { ok: true, file, keys, count, bytes: stat.size };
|
|
510
|
+
} catch {
|
|
511
|
+
return { ok: false, code: 'E_HANDOFF_READ', keys: new Set(), count: 0, file };
|
|
512
|
+
} finally {
|
|
513
|
+
try { fs.closeSync(fd); } catch { /* already closed */ }
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* Append archive lines with the M4 idempotency key. All keys already present →
|
|
519
|
+
* nothing written; some present → only the missing ones; if the proof of
|
|
520
|
+
* idempotency is unavailable → E_HANDOFF_TRIM_ARCHIVE_UNVERIFIED (the caller
|
|
521
|
+
* must not rewrite the main file).
|
|
522
|
+
*
|
|
523
|
+
* The v4 tail-window guard is kept as the cheap first check; when it cannot
|
|
524
|
+
* prove the batch (or cannot prove that new lines are really new), a bounded
|
|
525
|
+
* full-archive index decides instead, so the V15 "archive appended, rename
|
|
526
|
+
* crashed, re-run must not duplicate" case is genuinely idempotent.
|
|
527
|
+
*/
|
|
528
|
+
export function appendArchiveIdempotent(memoryRoot, monthKey, entries, options = {}) {
|
|
529
|
+
const list = Array.isArray(entries) ? entries : [];
|
|
530
|
+
if (list.length === 0) return { ok: true, appended: 0, idemSkipped: 0 };
|
|
531
|
+
const file = handoffArchiveFile(memoryRoot, monthKey);
|
|
532
|
+
if (file === null) return { ok: false, code: 'E_HANDOFF_NO_ROOT', appended: 0, idemSkipped: 0 };
|
|
533
|
+
const tail = readArchiveTail(memoryRoot, monthKey, { maxBytes: options.tailBytes ?? HANDOFF_TRIM_ARCHIVE_TAIL_BYTES });
|
|
534
|
+
if (!tail.ok) {
|
|
535
|
+
return { ok: false, code: 'E_HANDOFF_TRIM_ARCHIVE_UNVERIFIED', appended: 0, idemSkipped: 0, file };
|
|
536
|
+
}
|
|
537
|
+
let known = new Set(tail.rows.map((row) => row.h));
|
|
538
|
+
const allKnownByTail = list.every((entry) => known.has(entry.h));
|
|
539
|
+
if (allKnownByTail) {
|
|
540
|
+
return { ok: true, appended: 0, idemSkipped: list.length, file };
|
|
541
|
+
}
|
|
542
|
+
const index = readArchiveIndex(memoryRoot, monthKey, { maxBytes: options.fullScanMaxBytes });
|
|
543
|
+
if (!index.ok) {
|
|
544
|
+
return {
|
|
545
|
+
ok: false,
|
|
546
|
+
code: index.code === 'E_HANDOFF_READ' ? 'E_HANDOFF_TRIM_ARCHIVE_UNVERIFIED' : (index.code ?? 'E_HANDOFF_TRIM_ARCHIVE_UNVERIFIED'),
|
|
547
|
+
appended: 0,
|
|
548
|
+
idemSkipped: 0,
|
|
549
|
+
file,
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
known = index.keys;
|
|
553
|
+
const missing = list.filter((entry) => !known.has(entry.h));
|
|
554
|
+
if (missing.length === 0) {
|
|
555
|
+
return { ok: true, appended: 0, idemSkipped: list.length, file };
|
|
556
|
+
}
|
|
557
|
+
let appended = 0;
|
|
558
|
+
for (const chunk of chunkBy(missing, ARCHIVE_MAX_BATCH)) {
|
|
559
|
+
const text = chunk.map((entry) => `${entry.line}\n`).join('');
|
|
560
|
+
const fd = fs.openSync(file, 'a');
|
|
561
|
+
try {
|
|
562
|
+
fs.writeSync(fd, text, null, 'utf8');
|
|
563
|
+
try { fs.fsyncSync(fd); } catch { /* best effort */ }
|
|
564
|
+
appended += chunk.length;
|
|
565
|
+
} catch (error) {
|
|
566
|
+
return { ok: false, code: error?.code ?? 'E_HANDOFF_WRITE', appended, idemSkipped: list.length - missing.length, file };
|
|
567
|
+
} finally {
|
|
568
|
+
try { fs.closeSync(fd); } catch { /* already closed */ }
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
return { ok: true, appended, idemSkipped: list.length - missing.length, file };
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function chunkBy(list, size) {
|
|
575
|
+
const out = [];
|
|
576
|
+
for (let index = 0; index < list.length; index += size) out.push(list.slice(index, index + size));
|
|
577
|
+
return out;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* N6/M4 trim: stream the whole board from the head in fixed chunks, keep the
|
|
582
|
+
* last `windowRows` complete lines, archive the rolled-out lines by `at` month
|
|
583
|
+
* (idempotent by `h`), prove `completeLines === archivedRows + kept`, then
|
|
584
|
+
* tmp+fsync+read-back+rename the main file. Any doubt → no rewrite.
|
|
585
|
+
*/
|
|
586
|
+
export function trimAuditBoard(memoryRoot, options = {}) {
|
|
587
|
+
const file = handoffAuditFile(memoryRoot);
|
|
588
|
+
if (file === null) return { ok: false, trimmed: false, code: 'E_HANDOFF_NO_ROOT' };
|
|
589
|
+
const stat = statOrNull(file);
|
|
590
|
+
if (stat === null) return { ok: true, trimmed: false, skipped: true, reason: 'absent' };
|
|
591
|
+
if (!stat.isFile()) return { ok: false, trimmed: false, code: 'E_HANDOFF_READ' };
|
|
592
|
+
const windowRows = clampInt(options.windowRows, TRIM_WINDOW_ROWS, 100, 2000);
|
|
593
|
+
const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
|
|
594
|
+
|
|
595
|
+
let fd;
|
|
596
|
+
try {
|
|
597
|
+
fd = fs.openSync(file, 'r');
|
|
598
|
+
} catch {
|
|
599
|
+
return { ok: false, trimmed: false, code: 'E_HANDOFF_READ' };
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const ring = [];
|
|
603
|
+
const overflowByMonth = new Map();
|
|
604
|
+
let completeLines = 0;
|
|
605
|
+
let parsed = 0;
|
|
606
|
+
let bad = 0;
|
|
607
|
+
let carry = '';
|
|
608
|
+
const decoder = new StringDecoder('utf8');
|
|
609
|
+
|
|
610
|
+
const pushLine = (rawLine) => {
|
|
611
|
+
const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
|
|
612
|
+
if (line.trim() === '') return;
|
|
613
|
+
completeLines += 1;
|
|
614
|
+
const obj = parseJsonLine(line);
|
|
615
|
+
if (obj === null) bad += 1;
|
|
616
|
+
else parsed += 1;
|
|
617
|
+
const entry = {
|
|
618
|
+
line,
|
|
619
|
+
h: obj && typeof obj.h === 'string' && obj.h !== '' ? obj.h : lineHashOf(line),
|
|
620
|
+
};
|
|
621
|
+
ring.push(entry);
|
|
622
|
+
while (ring.length > windowRows) {
|
|
623
|
+
const out = ring.shift();
|
|
624
|
+
const month = monthKeyOf(objForMonth(out.line, nowMs));
|
|
625
|
+
if (!overflowByMonth.has(month)) overflowByMonth.set(month, []);
|
|
626
|
+
overflowByMonth.get(month).push(out);
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
|
|
630
|
+
try {
|
|
631
|
+
const buffer = Buffer.allocUnsafe(TRIM_CHUNK_BYTES);
|
|
632
|
+
let position = 0;
|
|
633
|
+
for (;;) {
|
|
634
|
+
const read = fs.readSync(fd, buffer, 0, buffer.length, position);
|
|
635
|
+
if (read <= 0) break;
|
|
636
|
+
position += read;
|
|
637
|
+
carry += decoder.write(buffer.subarray(0, read));
|
|
638
|
+
let newline = carry.indexOf('\n');
|
|
639
|
+
while (newline !== -1) {
|
|
640
|
+
const line = carry.slice(0, newline);
|
|
641
|
+
carry = carry.slice(newline + 1);
|
|
642
|
+
pushLine(line);
|
|
643
|
+
newline = carry.indexOf('\n');
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
carry += decoder.end();
|
|
647
|
+
} catch {
|
|
648
|
+
try { fs.closeSync(fd); } catch { /* already closed */ }
|
|
649
|
+
return { ok: false, trimmed: false, code: 'E_HANDOFF_READ' };
|
|
650
|
+
} finally {
|
|
651
|
+
try { fs.closeSync(fd); } catch { /* already closed */ }
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
const tailPartial = carry;
|
|
655
|
+
const months = [...overflowByMonth.keys()].sort();
|
|
656
|
+
let archivedRows = 0;
|
|
657
|
+
let idemSkipped = 0;
|
|
658
|
+
for (const month of months) {
|
|
659
|
+
const entries = overflowByMonth.get(month);
|
|
660
|
+
for (const batch of chunkBy(entries, ARCHIVE_MAX_BATCH)) {
|
|
661
|
+
const archived = appendArchiveIdempotent(memoryRoot, month, batch);
|
|
662
|
+
if (!archived.ok) {
|
|
663
|
+
return {
|
|
664
|
+
ok: false,
|
|
665
|
+
trimmed: false,
|
|
666
|
+
code: archived.code ?? 'E_HANDOFF_TRIM_ARCHIVE_UNVERIFIED',
|
|
667
|
+
lines: completeLines,
|
|
668
|
+
parsed,
|
|
669
|
+
bad,
|
|
670
|
+
archived: archivedRows,
|
|
671
|
+
kept: ring.length,
|
|
672
|
+
months,
|
|
673
|
+
tailPartial: tailPartial !== '',
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
archivedRows += batch.length;
|
|
677
|
+
idemSkipped += archived.idemSkipped ?? 0;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
if (completeLines !== archivedRows + ring.length) {
|
|
682
|
+
return {
|
|
683
|
+
ok: false,
|
|
684
|
+
trimmed: false,
|
|
685
|
+
code: 'E_HANDOFF_TRIM_MISMATCH',
|
|
686
|
+
lines: completeLines,
|
|
687
|
+
parsed,
|
|
688
|
+
bad,
|
|
689
|
+
archived: archivedRows,
|
|
690
|
+
kept: ring.length,
|
|
691
|
+
months,
|
|
692
|
+
tailPartial: tailPartial !== '',
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
const body = ring.map((entry) => entry.line).join('\n');
|
|
697
|
+
let expected = ring.length === 0
|
|
698
|
+
? tailPartial
|
|
699
|
+
: `${body}\n${tailPartial}`;
|
|
700
|
+
// The crashed tail is a half line. Terminate it before the `op:'trim'` audit
|
|
701
|
+
// row is appended, otherwise the two would fuse into one corrupt line. The
|
|
702
|
+
// partial bytes themselves are preserved exactly (newline appended after).
|
|
703
|
+
if (tailPartial !== '') expected = `${expected}\n`;
|
|
704
|
+
const dir = path.dirname(file);
|
|
705
|
+
const tmp = path.join(dir, `.${path.basename(file)}.trim-${process.pid}-${Date.now()}-${randomBytes(4).toString('hex')}`);
|
|
706
|
+
let tmpFd;
|
|
707
|
+
try {
|
|
708
|
+
tmpFd = fs.openSync(tmp, 'wx', 0o600);
|
|
709
|
+
fs.writeSync(tmpFd, expected, null, 'utf8');
|
|
710
|
+
fs.fsyncSync(tmpFd);
|
|
711
|
+
fs.closeSync(tmpFd);
|
|
712
|
+
tmpFd = undefined;
|
|
713
|
+
if (readText(tmp) !== expected) {
|
|
714
|
+
unlinkQuiet(tmp);
|
|
715
|
+
return { ok: false, trimmed: false, code: 'E_HANDOFF_TRIM_MISMATCH', lines: completeLines, parsed, bad, archived: archivedRows, kept: ring.length, months };
|
|
716
|
+
}
|
|
717
|
+
fs.renameSync(tmp, file);
|
|
718
|
+
} catch (error) {
|
|
719
|
+
if (tmpFd !== undefined) {
|
|
720
|
+
try { fs.closeSync(tmpFd); } catch { /* already closed */ }
|
|
721
|
+
}
|
|
722
|
+
unlinkQuiet(tmp);
|
|
723
|
+
return { ok: false, trimmed: false, code: error?.code ?? 'E_HANDOFF_WRITE', lines: completeLines, parsed, bad, archived: archivedRows, kept: ring.length, months };
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
const result = {
|
|
727
|
+
ok: true,
|
|
728
|
+
trimmed: true,
|
|
729
|
+
skipped: false,
|
|
730
|
+
lines: completeLines,
|
|
731
|
+
parsed,
|
|
732
|
+
bad,
|
|
733
|
+
archived: archivedRows,
|
|
734
|
+
kept: ring.length,
|
|
735
|
+
months,
|
|
736
|
+
tailPartial: tailPartial !== '',
|
|
737
|
+
idemSkipped,
|
|
738
|
+
droppedPrefixBytes: 0,
|
|
739
|
+
};
|
|
740
|
+
try {
|
|
741
|
+
appendAudit(memoryRoot, {
|
|
742
|
+
schema: AUDIT_SCHEMA,
|
|
743
|
+
op: 'trim',
|
|
744
|
+
at: isoOf(nowMs),
|
|
745
|
+
lines: completeLines,
|
|
746
|
+
parsed,
|
|
747
|
+
bad,
|
|
748
|
+
archived: archivedRows,
|
|
749
|
+
kept: ring.length,
|
|
750
|
+
months,
|
|
751
|
+
tailPartial: tailPartial !== '',
|
|
752
|
+
idemSkipped,
|
|
753
|
+
droppedPrefixBytes: 0,
|
|
754
|
+
});
|
|
755
|
+
} catch {
|
|
756
|
+
/* the trim itself succeeded; a failed trim-audit row is not fatal */
|
|
757
|
+
}
|
|
758
|
+
return result;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
function objForMonth(line, nowMs) {
|
|
762
|
+
const parsed = parseJsonLine(line);
|
|
763
|
+
if (parsed && typeof parsed.at === 'string') {
|
|
764
|
+
const at = Date.parse(parsed.at);
|
|
765
|
+
if (Number.isFinite(at)) return at;
|
|
766
|
+
}
|
|
767
|
+
return nowMs;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* Trigger point wired into every append (M4): only when the board exceeds
|
|
772
|
+
* 256 KiB, at most once per `minIntervalMs` per memoryRoot.
|
|
773
|
+
*/
|
|
774
|
+
export function maybeTrimAuditBoard(memoryRoot, options = {}) {
|
|
775
|
+
const file = handoffAuditFile(memoryRoot);
|
|
776
|
+
if (file === null) return { ok: false, trimmed: false, skipped: true, reason: 'no-root' };
|
|
777
|
+
const stat = statOrNull(file);
|
|
778
|
+
if (stat === null) return { ok: true, trimmed: false, skipped: true, reason: 'absent' };
|
|
779
|
+
if (stat.size <= TRIM_MAX_BYTES) return { ok: true, trimmed: false, skipped: true, reason: 'small' };
|
|
780
|
+
const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
|
|
781
|
+
const minInterval = clampInt(options.minIntervalMs, HANDOFF_TRIM_MIN_INTERVAL_MS, 0, 3_600_000);
|
|
782
|
+
const root = resolvedRoot(memoryRoot) ?? '';
|
|
783
|
+
const last = trimThrottle.get(root);
|
|
784
|
+
if (last !== undefined && nowMs - last < minInterval) {
|
|
785
|
+
return { ok: true, trimmed: false, skipped: true, reason: 'throttled' };
|
|
786
|
+
}
|
|
787
|
+
trimThrottle.set(root, nowMs);
|
|
788
|
+
return trimAuditBoard(memoryRoot, {
|
|
789
|
+
windowRows: options.windowRows,
|
|
790
|
+
now: nowMs,
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/** Test/acceptance helper: forget the in-process trim throttle. */
|
|
795
|
+
export function resetTrimThrottle() {
|
|
796
|
+
trimThrottle.clear();
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// ------------------------------------------------------------------ claims
|
|
800
|
+
|
|
801
|
+
function createExclusive(file, body) {
|
|
802
|
+
const dir = path.dirname(file);
|
|
803
|
+
if (!ensureDir(dir)) return { ok: false, code: 'E_HANDOFF_CLAIM' };
|
|
804
|
+
let fd;
|
|
805
|
+
try {
|
|
806
|
+
fd = fs.openSync(file, 'wx', 0o600);
|
|
807
|
+
} catch (error) {
|
|
808
|
+
if (error?.code === 'EEXIST') return { ok: false, code: 'E_ALREADY_CLAIMED' };
|
|
809
|
+
return { ok: false, code: error?.code ?? 'E_HANDOFF_CLAIM' };
|
|
810
|
+
}
|
|
811
|
+
try {
|
|
812
|
+
fs.writeSync(fd, `${JSON.stringify(body)}\n`, null, 'utf8');
|
|
813
|
+
fs.fsyncSync(fd);
|
|
814
|
+
return { ok: true, path: file };
|
|
815
|
+
} catch (error) {
|
|
816
|
+
unlinkQuiet(file);
|
|
817
|
+
return { ok: false, code: error?.code ?? 'E_HANDOFF_CLAIM' };
|
|
818
|
+
} finally {
|
|
819
|
+
try { fs.closeSync(fd); } catch { /* already closed */ }
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
function readClaim(file) {
|
|
824
|
+
const text = readText(file);
|
|
825
|
+
if (text === null) return { ok: false, code: 'E_HANDOFF_READ' };
|
|
826
|
+
try {
|
|
827
|
+
const value = JSON.parse(text);
|
|
828
|
+
if (!value || typeof value !== 'object') return { ok: false, code: 'E_HANDOFF_CORRUPT' };
|
|
829
|
+
return { ok: true, value };
|
|
830
|
+
} catch {
|
|
831
|
+
return { ok: false, code: 'E_HANDOFF_CORRUPT' };
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
function rewriteClaim(file, value) {
|
|
836
|
+
return writeAtomicJson(file, value);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/** Per-session claim (unique gate; never auto-reclaimed). */
|
|
840
|
+
export function claimSession(memoryRoot, sessionId, options = {}) {
|
|
841
|
+
const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
|
|
842
|
+
const file = sessionClaimFile(memoryRoot, sessionId);
|
|
843
|
+
if (file === null) return { ok: false, code: 'E_HANDOFF_NO_ROOT' };
|
|
844
|
+
const created = createExclusive(file, {
|
|
845
|
+
v: 3,
|
|
846
|
+
kind: 'session',
|
|
847
|
+
sessionId,
|
|
848
|
+
pid: process.pid,
|
|
849
|
+
host: hostname(),
|
|
850
|
+
state: 'claimed',
|
|
851
|
+
claimedAt: isoOf(nowMs),
|
|
852
|
+
});
|
|
853
|
+
if (!created.ok) return created;
|
|
854
|
+
return {
|
|
855
|
+
ok: true,
|
|
856
|
+
path: file,
|
|
857
|
+
sessionId,
|
|
858
|
+
pid: process.pid,
|
|
859
|
+
host: hostname(),
|
|
860
|
+
claimedAt: nowMs,
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
export function finalizeSessionClaim(claim, options = {}) {
|
|
865
|
+
if (!claim?.ok || typeof claim.path !== 'string') return { ok: false, code: 'E_HANDOFF_NO_CLAIM' };
|
|
866
|
+
const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
|
|
867
|
+
const body = {
|
|
868
|
+
v: 3,
|
|
869
|
+
kind: 'session',
|
|
870
|
+
sessionId: claim.sessionId,
|
|
871
|
+
pid: claim.pid ?? process.pid,
|
|
872
|
+
host: claim.host ?? hostname(),
|
|
873
|
+
state: 'injected',
|
|
874
|
+
cardId: options.cardId ?? null,
|
|
875
|
+
sourceSessionId: options.sourceSessionId ?? null,
|
|
876
|
+
chars: Number.isInteger(options.chars) ? options.chars : null,
|
|
877
|
+
claimedAt: isoOf(claim.claimedAt),
|
|
878
|
+
at: isoOf(nowMs),
|
|
879
|
+
};
|
|
880
|
+
const written = rewriteClaim(claim.path, body);
|
|
881
|
+
return written.ok ? { ok: true, path: claim.path } : { ok: false, code: written.code ?? 'E_HANDOFF_FINALIZE' };
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
export function releaseSessionClaim(claim) {
|
|
885
|
+
if (!claim?.ok || typeof claim.path !== 'string') return { ok: false, code: 'E_HANDOFF_NO_CLAIM' };
|
|
886
|
+
return { ok: unlinkQuiet(claim.path) };
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* M5 fallback for an unreadable (empty/half) per-card claim: the card is gone
|
|
891
|
+
* or expired, and the claim file is older than the grace window → reclaim it.
|
|
892
|
+
*/
|
|
893
|
+
export function recoverUnreadableCardClaim(file, options = {}) {
|
|
894
|
+
const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
|
|
895
|
+
const maxAgeMs = Number.isFinite(options.maxAgeMs) ? options.maxAgeMs : HANDOFF_DEFAULT_MAX_AGE_MS;
|
|
896
|
+
const cardAtMs = Number.isFinite(options.cardAtMs) ? options.cardAtMs : 0;
|
|
897
|
+
const cardFile = typeof options.cardFile === 'string' ? options.cardFile : null;
|
|
898
|
+
const stat = statOrNull(file);
|
|
899
|
+
if (stat === null) return { ok: true, deleted: false, reason: 'absent' };
|
|
900
|
+
if (nowMs - stat.mtimeMs <= HANDOFF_CLAIM_GRACE_MS) {
|
|
901
|
+
return { ok: true, deleted: false, reason: 'too-new' };
|
|
902
|
+
}
|
|
903
|
+
const cardGone = cardFile === null || statOrNull(cardFile) === null;
|
|
904
|
+
const cardExpired = cardAtMs + maxAgeMs + HANDOFF_CARD_RETENTION_EXTRA_MS < nowMs;
|
|
905
|
+
if (!cardGone && !cardExpired) {
|
|
906
|
+
return { ok: true, deleted: false, reason: 'card-valid' };
|
|
907
|
+
}
|
|
908
|
+
return { ok: unlinkQuiet(file), deleted: true, reason: cardGone ? 'card-gone' : 'card-expired' };
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/** Per-card claim with pid/empty-body recovery (N2 + M5). */
|
|
912
|
+
export function claimCard(memoryRoot, cardId, options = {}) {
|
|
913
|
+
const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
|
|
914
|
+
let file = cardClaimFile(memoryRoot, cardId);
|
|
915
|
+
if (file === null) return { ok: false, code: 'E_HANDOFF_NO_ROOT' };
|
|
916
|
+
const bodyOf = (sessionId) => ({
|
|
917
|
+
v: 3,
|
|
918
|
+
kind: 'card',
|
|
919
|
+
cardId,
|
|
920
|
+
sessionId,
|
|
921
|
+
pid: process.pid,
|
|
922
|
+
host: hostname(),
|
|
923
|
+
state: 'claimed',
|
|
924
|
+
claimedAt: isoOf(nowMs),
|
|
925
|
+
});
|
|
926
|
+
const created = createExclusive(file, bodyOf(options.sessionId ?? null));
|
|
927
|
+
if (created.ok) {
|
|
928
|
+
return { ok: true, path: file, cardId, pid: process.pid, host: hostname(), claimedAt: nowMs };
|
|
929
|
+
}
|
|
930
|
+
if (created.code !== 'E_ALREADY_CLAIMED') return created;
|
|
931
|
+
|
|
932
|
+
const existing = readClaim(file);
|
|
933
|
+
if (!existing.ok) {
|
|
934
|
+
const recovered = recoverUnreadableCardClaim(file, {
|
|
935
|
+
now: nowMs,
|
|
936
|
+
cardAtMs: options.cardAtMs,
|
|
937
|
+
maxAgeMs: options.maxAgeMs,
|
|
938
|
+
cardFile: options.cardFile,
|
|
939
|
+
});
|
|
940
|
+
if (!recovered.deleted) return { ok: false, code: 'E_ALREADY_CLAIMED' };
|
|
941
|
+
const retried = createExclusive(file, bodyOf(options.sessionId ?? null));
|
|
942
|
+
if (!retried.ok) return retried;
|
|
943
|
+
return { ok: true, path: file, cardId, pid: process.pid, host: hostname(), claimedAt: nowMs };
|
|
944
|
+
}
|
|
945
|
+
const value = existing.value;
|
|
946
|
+
if (value.state === 'injected') return { ok: false, code: 'E_ALREADY_CLAIMED' };
|
|
947
|
+
const claimedAtMs = Date.parse(String(value.claimedAt ?? ''));
|
|
948
|
+
if (value.state === 'claimed'
|
|
949
|
+
&& sameHost(value.host)
|
|
950
|
+
&& pidAliveOf(value.pid) === false
|
|
951
|
+
&& Number.isFinite(claimedAtMs)
|
|
952
|
+
&& nowMs - claimedAtMs > HANDOFF_CLAIM_GRACE_MS) {
|
|
953
|
+
if (unlinkQuiet(file)) {
|
|
954
|
+
const retried = createExclusive(file, bodyOf(options.sessionId ?? null));
|
|
955
|
+
if (!retried.ok) return retried;
|
|
956
|
+
return { ok: true, path: file, cardId, pid: process.pid, host: hostname(), claimedAt: nowMs };
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
return { ok: false, code: 'E_ALREADY_CLAIMED' };
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/** Before splicing: record that the message may already be in the payload. */
|
|
963
|
+
export function markCardSpliced(claim, options = {}) {
|
|
964
|
+
if (!claim?.ok || typeof claim.path !== 'string') return { ok: false, code: 'E_HANDOFF_NO_CLAIM' };
|
|
965
|
+
const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
|
|
966
|
+
const body = {
|
|
967
|
+
v: 3,
|
|
968
|
+
kind: 'card',
|
|
969
|
+
cardId: claim.cardId,
|
|
970
|
+
sessionId: claim.sessionId ?? options.sessionId ?? null,
|
|
971
|
+
pid: claim.pid ?? process.pid,
|
|
972
|
+
host: claim.host ?? hostname(),
|
|
973
|
+
state: 'spliced',
|
|
974
|
+
claimedAt: isoOf(claim.claimedAt),
|
|
975
|
+
splicedAt: isoOf(nowMs),
|
|
976
|
+
};
|
|
977
|
+
const written = rewriteClaim(claim.path, body);
|
|
978
|
+
return written.ok ? { ok: true, path: claim.path } : { ok: false, code: written.code ?? 'E_HANDOFF_WRITE' };
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
export function finalizeCardClaim(claim, options = {}) {
|
|
982
|
+
if (!claim?.ok || typeof claim.path !== 'string') return { ok: false, code: 'E_HANDOFF_NO_CLAIM' };
|
|
983
|
+
const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
|
|
984
|
+
const body = {
|
|
985
|
+
v: 3,
|
|
986
|
+
kind: 'card',
|
|
987
|
+
cardId: claim.cardId,
|
|
988
|
+
sessionId: claim.sessionId ?? options.sessionId ?? null,
|
|
989
|
+
pid: claim.pid ?? process.pid,
|
|
990
|
+
host: claim.host ?? hostname(),
|
|
991
|
+
state: 'injected',
|
|
992
|
+
claimedAt: isoOf(claim.claimedAt),
|
|
993
|
+
at: isoOf(nowMs),
|
|
994
|
+
};
|
|
995
|
+
const written = rewriteClaim(claim.path, body);
|
|
996
|
+
return written.ok ? { ok: true, path: claim.path } : { ok: false, code: written.code ?? 'E_HANDOFF_FINALIZE' };
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
export function releaseCardClaim(claim) {
|
|
1000
|
+
if (!claim?.ok || typeof claim.path !== 'string') return { ok: false, code: 'E_HANDOFF_NO_CLAIM' };
|
|
1001
|
+
return { ok: unlinkQuiet(claim.path) };
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
// ------------------------------------------------------------------ prune
|
|
1005
|
+
|
|
1006
|
+
function listClaimFiles(memoryRoot) {
|
|
1007
|
+
const root = resolvedRoot(memoryRoot);
|
|
1008
|
+
const dir = root === null ? null : inside(root, path.join(root, BUNDLE_DIR));
|
|
1009
|
+
if (dir === null) return { card: [], session: [], dir: null };
|
|
1010
|
+
let entries;
|
|
1011
|
+
try {
|
|
1012
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
1013
|
+
} catch {
|
|
1014
|
+
return { card: [], session: [], dir };
|
|
1015
|
+
}
|
|
1016
|
+
const card = [];
|
|
1017
|
+
const session = [];
|
|
1018
|
+
for (const entry of entries) {
|
|
1019
|
+
if (!entry.isFile() || entry.name.startsWith('.')) continue;
|
|
1020
|
+
if (entry.name.startsWith(CARD_CLAIM_PREFIX) && entry.name.endsWith('.json')) {
|
|
1021
|
+
card.push(path.join(dir, entry.name));
|
|
1022
|
+
} else if (entry.name.endsWith(SESSION_CLAIM_SUFFIX)) {
|
|
1023
|
+
session.push(path.join(dir, entry.name));
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
return { card, session, dir };
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
/** Collect the card ids that still have a readable latest card on disk. */
|
|
1030
|
+
function existingCardIds(memoryRoot) {
|
|
1031
|
+
const root = resolvedRoot(memoryRoot);
|
|
1032
|
+
const bundle = root === null ? null : inside(root, path.join(root, BUNDLE_DIR));
|
|
1033
|
+
const ids = new Set();
|
|
1034
|
+
if (bundle === null) return ids;
|
|
1035
|
+
let entries;
|
|
1036
|
+
try {
|
|
1037
|
+
entries = fs.readdirSync(bundle, { withFileTypes: true });
|
|
1038
|
+
} catch {
|
|
1039
|
+
return ids;
|
|
1040
|
+
}
|
|
1041
|
+
for (const entry of entries) {
|
|
1042
|
+
if (!entry.isFile() || !entry.name.endsWith(LATEST_CARD_SUFFIX) || entry.name.startsWith('.')) continue;
|
|
1043
|
+
const file = path.join(bundle, entry.name);
|
|
1044
|
+
const stat = statOrNull(file);
|
|
1045
|
+
if (stat === null || stat.size > LATEST_CARD_MAX_BYTES) continue;
|
|
1046
|
+
const text = readText(file);
|
|
1047
|
+
if (text === null) continue;
|
|
1048
|
+
try {
|
|
1049
|
+
const card = JSON.parse(text);
|
|
1050
|
+
ids.add(cardIdOf({ sessionId: card?.source?.sessionId, turn: card?.turn }));
|
|
1051
|
+
} catch {
|
|
1052
|
+
/* corrupt card: no id */
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
return ids;
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/**
|
|
1059
|
+
* Clean per-card claims for expired cards / dead owners; per-session claims are
|
|
1060
|
+
* reported only (never auto-deleted). Unreadable card claims follow the M5 rule.
|
|
1061
|
+
*/
|
|
1062
|
+
export function pruneClaims(memoryRoot, options = {}) {
|
|
1063
|
+
const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
|
|
1064
|
+
const maxAgeMs = Number.isFinite(options.maxAgeMs) ? options.maxAgeMs : HANDOFF_DEFAULT_MAX_AGE_MS;
|
|
1065
|
+
const limit = clampInt(options.limit, PRUNE_LIMIT, 1, 500);
|
|
1066
|
+
const { card: cardFiles, session: sessionFiles } = listClaimFiles(memoryRoot);
|
|
1067
|
+
const liveIds = existingCardIds(memoryRoot);
|
|
1068
|
+
let scanned = 0;
|
|
1069
|
+
let deleted = 0;
|
|
1070
|
+
let errors = 0;
|
|
1071
|
+
let reported = 0;
|
|
1072
|
+
for (const file of cardFiles) {
|
|
1073
|
+
if (scanned >= limit) break;
|
|
1074
|
+
scanned += 1;
|
|
1075
|
+
const stat = statOrNull(file);
|
|
1076
|
+
if (stat === null) continue;
|
|
1077
|
+
const cardId = path.basename(file).slice(CARD_CLAIM_PREFIX.length, -'.json'.length);
|
|
1078
|
+
const existing = readClaim(file);
|
|
1079
|
+
if (!existing.ok) {
|
|
1080
|
+
const expired = stat.mtimeMs + maxAgeMs + HANDOFF_CARD_RETENTION_EXTRA_MS < nowMs;
|
|
1081
|
+
if (!liveIds.has(cardId) || expired) {
|
|
1082
|
+
if (unlinkQuiet(file)) deleted += 1;
|
|
1083
|
+
else errors += 1;
|
|
1084
|
+
}
|
|
1085
|
+
continue;
|
|
1086
|
+
}
|
|
1087
|
+
const value = existing.value;
|
|
1088
|
+
const claimedAtMs = Date.parse(String(value.claimedAt ?? ''));
|
|
1089
|
+
const expired = Number.isFinite(claimedAtMs) && claimedAtMs + maxAgeMs + HANDOFF_CARD_RETENTION_EXTRA_MS < nowMs;
|
|
1090
|
+
const deadOwner = value.state === 'claimed' && sameHost(value.host) && pidAliveOf(value.pid) === false;
|
|
1091
|
+
if (value.state === 'claimed' && (expired || deadOwner)) {
|
|
1092
|
+
if (unlinkQuiet(file)) deleted += 1;
|
|
1093
|
+
else errors += 1;
|
|
1094
|
+
} else if (value.state === 'spliced' || value.state === 'injected') {
|
|
1095
|
+
reported += 1;
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
reported += sessionFiles.length;
|
|
1099
|
+
return { ok: true, kind: 'claims', scanned, deleted, errors, reported };
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
/** Delete latest cards past `maxAge + 24h` (and their per-card claim). */
|
|
1103
|
+
export function pruneCards(memoryRoot, options = {}) {
|
|
1104
|
+
const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
|
|
1105
|
+
const maxAgeMs = Number.isFinite(options.maxAgeMs) ? options.maxAgeMs : HANDOFF_DEFAULT_MAX_AGE_MS;
|
|
1106
|
+
const limit = clampInt(options.limit, PRUNE_LIMIT, 1, 500);
|
|
1107
|
+
const root = resolvedRoot(memoryRoot);
|
|
1108
|
+
const bundle = root === null ? null : inside(root, path.join(root, BUNDLE_DIR));
|
|
1109
|
+
if (bundle === null) return { ok: true, kind: 'cards', scanned: 0, deleted: 0, errors: 0 };
|
|
1110
|
+
let entries;
|
|
1111
|
+
try {
|
|
1112
|
+
entries = fs.readdirSync(bundle, { withFileTypes: true });
|
|
1113
|
+
} catch {
|
|
1114
|
+
return { ok: true, kind: 'cards', scanned: 0, deleted: 0, errors: 0 };
|
|
1115
|
+
}
|
|
1116
|
+
let scanned = 0;
|
|
1117
|
+
let deleted = 0;
|
|
1118
|
+
let errors = 0;
|
|
1119
|
+
for (const entry of entries) {
|
|
1120
|
+
if (scanned >= limit) break;
|
|
1121
|
+
if (!entry.isFile() || !entry.name.endsWith(LATEST_CARD_SUFFIX) || entry.name.startsWith('.')) continue;
|
|
1122
|
+
scanned += 1;
|
|
1123
|
+
const file = path.join(bundle, entry.name);
|
|
1124
|
+
const stat = statOrNull(file);
|
|
1125
|
+
if (stat === null) continue;
|
|
1126
|
+
const text = readText(file);
|
|
1127
|
+
let card = null;
|
|
1128
|
+
if (text !== null) {
|
|
1129
|
+
try {
|
|
1130
|
+
card = JSON.parse(text);
|
|
1131
|
+
} catch {
|
|
1132
|
+
card = null;
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
const atMs = Date.parse(String(card?.at ?? ''));
|
|
1136
|
+
const expired = !Number.isFinite(atMs) || atMs + maxAgeMs + HANDOFF_CARD_RETENTION_EXTRA_MS < nowMs;
|
|
1137
|
+
if (!expired) continue;
|
|
1138
|
+
if (!unlinkQuiet(file)) {
|
|
1139
|
+
errors += 1;
|
|
1140
|
+
continue;
|
|
1141
|
+
}
|
|
1142
|
+
deleted += 1;
|
|
1143
|
+
if (card && typeof card.source?.sessionId === 'string') {
|
|
1144
|
+
const claim = cardClaimFile(memoryRoot, cardIdOf({ sessionId: card.source.sessionId, turn: card.turn }));
|
|
1145
|
+
if (claim !== null) unlinkQuiet(claim);
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
return { ok: true, kind: 'cards', scanned, deleted, errors };
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
// ------------------------------------------------------------------ live row
|
|
1152
|
+
|
|
1153
|
+
/**
|
|
1154
|
+
* Read one session's live row for the liveness gate. Everything that cannot be
|
|
1155
|
+
* read (corrupt JSON, symlink, locked file) becomes `unreadable` → skip.
|
|
1156
|
+
*/
|
|
1157
|
+
export function readLiveRow(memoryRoot, sessionId, options = {}) {
|
|
1158
|
+
const root = resolvedRoot(memoryRoot);
|
|
1159
|
+
if (root === null) return { status: 'unreadable', code: 'E_HANDOFF_NO_ROOT' };
|
|
1160
|
+
const canonical = String(sessionId ?? '').trim().toLowerCase();
|
|
1161
|
+
if (canonical === '') return { status: 'unreadable', code: 'E_HANDOFF_LIVE_UNREADABLE' };
|
|
1162
|
+
const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
|
|
1163
|
+
try {
|
|
1164
|
+
const got = liveGet({ sessionId: canonical }, { memoryRoot: root, now: new Date(nowMs) });
|
|
1165
|
+
if (got?.status === 'absent') return { status: 'absent', file: got.file ?? null };
|
|
1166
|
+
if (!got?.ok || !got.live) {
|
|
1167
|
+
return { status: 'unreadable', code: 'E_HANDOFF_LIVE_UNREADABLE' };
|
|
1168
|
+
}
|
|
1169
|
+
return { status: 'ok', live: got.live, file: got.file ?? null };
|
|
1170
|
+
} catch (error) {
|
|
1171
|
+
return { status: 'unreadable', code: error?.code ?? 'E_HANDOFF_LIVE_UNREADABLE', message: String(error?.message ?? error) };
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
// ------------------------------------------------------------------ board read model (§10)
|
|
1176
|
+
|
|
1177
|
+
function within24h(row, nowMs) {
|
|
1178
|
+
const at = Date.parse(String(row?.at ?? ''));
|
|
1179
|
+
return Number.isFinite(at) && nowMs - at <= 24 * 3600 * 1000 && nowMs - at >= -60_000;
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
/**
|
|
1183
|
+
* The `/api/longlive/board` handoff segment: tail rows (no prose), 24h counters
|
|
1184
|
+
* and a card summary. Never returns goal text or a plaintext cwd.
|
|
1185
|
+
*/
|
|
1186
|
+
export function readHandoffBoard(memoryRoot, options = {}) {
|
|
1187
|
+
const nowMs = Number.isFinite(options.now) ? options.now : Date.now();
|
|
1188
|
+
const limit = clampInt(options.limit, AUDIT_TAIL_LIMIT, 1, 200);
|
|
1189
|
+
const tail = readAuditTail(memoryRoot, { limit, maxBytes: AUDIT_TAIL_BYTES });
|
|
1190
|
+
const rows = Array.isArray(tail.rows) ? tail.rows : [];
|
|
1191
|
+
const counts = { written24h: 0, injected24h: 0, skipped24h: 0, claims24h: 0, intentInjected24h: 0 };
|
|
1192
|
+
for (const row of rows) {
|
|
1193
|
+
if (!within24h(row, nowMs)) continue;
|
|
1194
|
+
if (row.op === 'write') counts.written24h += 1;
|
|
1195
|
+
else if (row.op === 'inject') {
|
|
1196
|
+
counts.injected24h += 1;
|
|
1197
|
+
if (row?.gates?.relevance?.kind === 'intent') counts.intentInjected24h += 1;
|
|
1198
|
+
} else if (row.op === 'skip') counts.skipped24h += 1;
|
|
1199
|
+
else if (row.op === 'claim') counts.claims24h += 1;
|
|
1200
|
+
}
|
|
1201
|
+
const listed = readLatestCards(memoryRoot, { maxFiles: 64 });
|
|
1202
|
+
const cards = (listed.ok ? listed.cards : []).map((entry) => {
|
|
1203
|
+
const card = entry.card;
|
|
1204
|
+
const goal = typeof card?.goal === 'string' ? card.goal : '';
|
|
1205
|
+
return {
|
|
1206
|
+
sessionId: card?.source?.sessionId ?? '',
|
|
1207
|
+
cardId: entry.cardId,
|
|
1208
|
+
at: card?.at ?? null,
|
|
1209
|
+
turn: Number.isInteger(card?.turn) ? card.turn : null,
|
|
1210
|
+
cwdHash: typeof card?.source?.cwdHash === 'string' ? card.source.cwdHash : '',
|
|
1211
|
+
goalChars: charLengthOf(goal),
|
|
1212
|
+
goalHash: hash8(goal),
|
|
1213
|
+
decidedN: Array.isArray(card?.decided) ? card.decided.length : 0,
|
|
1214
|
+
};
|
|
1215
|
+
});
|
|
1216
|
+
return {
|
|
1217
|
+
present: tail.present === true || cards.length > 0,
|
|
1218
|
+
rows: rows.map(stripRowForPanel),
|
|
1219
|
+
counts,
|
|
1220
|
+
cards,
|
|
1221
|
+
badLines: Number.isInteger(tail.bad) ? tail.bad : 0,
|
|
1222
|
+
};
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
/** Defense in depth: the panel/API never receives prose or a plaintext cwd. */
|
|
1226
|
+
function stripRowForPanel(row) {
|
|
1227
|
+
if (!row || typeof row !== 'object') return row;
|
|
1228
|
+
const { goal, goalPreview, cwd, text, ...rest } = row;
|
|
1229
|
+
void goal; void goalPreview; void cwd; void text;
|
|
1230
|
+
return rest;
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
export { HANDOFF_MAX_CLAIM_ATTEMPTS };
|