ctxtop 0.0.0-stage → 4.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/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +149 -0
- package/LICENSE +27 -0
- package/README.md +330 -3
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +145 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1474 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +114 -0
- package/config/modelCatalog.json +620 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +262 -0
- package/hooks/handlers/hookIo.mjs +255 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-tool-use.mjs +265 -0
- package/hooks/handlers/pre-model-switch.mjs +249 -0
- package/hooks/handlers/pre-tool-use.mjs +365 -0
- package/hooks/handlers/stop-gate.mjs +240 -0
- package/hooks/handlers/user-prompt-submit.mjs +143 -0
- package/hooks/hooks.json +81 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +17 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +687 -0
- package/hooks/session_start.mjs +14 -0
- package/hooks/stop.mjs +13 -0
- package/hooks.json +56 -0
- package/package.json +103 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2002 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +42 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +79 -0
- package/src/adapters/claude-code/index.mjs +155 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +686 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +620 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1800 -0
- package/src/core/detectors_det01_to_16.mjs +1474 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +966 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1996 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +310 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
- package/src/core-isomorphic/index.js +26 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
- package/src/core-isomorphic/ui/modViews.mjs +1478 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/doctorEngine.mjs +203 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +110 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +9 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +369 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +419 -0
- package/src/hooks/pre_invocation.mjs +1015 -0
- package/src/hooks/session_start.mjs +161 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +11389 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,810 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/coach/stateBatonHydrator.mjs
|
|
3
|
+
* Deterministic ~300-token Durable Fact Schema (`StateBaton`), `PreCompact` portable Markdown
|
|
4
|
+
* handoff generator (`docs/HANDOFF_<timestamp>.md`), `SessionStart` `additionalContext`
|
|
5
|
+
* injector, and `PostCompact` mutation queue + `SavedQuotaReceiptLedger` flusher.
|
|
6
|
+
*
|
|
7
|
+
* Strictly zero background LLM summarization workers ($0.00 worker cost).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
path,
|
|
12
|
+
getCwd,
|
|
13
|
+
fileExists,
|
|
14
|
+
getFileMtimeMsSafe,
|
|
15
|
+
readdirSafe,
|
|
16
|
+
readTextSafe,
|
|
17
|
+
writeTextAtomic,
|
|
18
|
+
writeJsonAtomic,
|
|
19
|
+
recordRuntimeDiagnostic
|
|
20
|
+
} from '../utils/runtime.mjs';
|
|
21
|
+
import { sanitizeSessionId } from '../telemetry/telemetryBridge.mjs';
|
|
22
|
+
import { PostCompactMutationQueue } from './cacheGravityRouter.mjs';
|
|
23
|
+
import { recordSavingsReceipt } from './savedQuotaLedger.mjs';
|
|
24
|
+
|
|
25
|
+
export const MAX_BATON_TOKEN_BUDGET = 300; // ~1,200 characters
|
|
26
|
+
|
|
27
|
+
// In-memory fallback set to guarantee idempotent compaction receipts even when disk I/O is disabled
|
|
28
|
+
const inMemoryRecordedCompactionKeys = new Set();
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Reads and parses a persisted State Baton JSON file, recording a structured diagnostic if corrupted (`ISS-065`).
|
|
32
|
+
*
|
|
33
|
+
* @param {string} targetPath
|
|
34
|
+
* @param {string} operation
|
|
35
|
+
* @param {object} [ioOpts={}]
|
|
36
|
+
* @param {object} [diagOpts={}]
|
|
37
|
+
* @returns {any}
|
|
38
|
+
*/
|
|
39
|
+
function readBatonJsonWithDiagnostics(targetPath, operation, ioOpts = {}, diagOpts = {}) {
|
|
40
|
+
const raw = readTextSafe(targetPath, null, ioOpts);
|
|
41
|
+
if (raw === null) return null;
|
|
42
|
+
try {
|
|
43
|
+
return JSON.parse(raw);
|
|
44
|
+
} catch (err) {
|
|
45
|
+
recordRuntimeDiagnostic('stateBatonHydrator', operation, err, diagOpts);
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Resolves the State Baton persistence path `.claude/cache/state_baton_<sessionId>.json`.
|
|
52
|
+
* @param {string} [sessionId='default']
|
|
53
|
+
* @param {object} [options={}]
|
|
54
|
+
* @returns {string}
|
|
55
|
+
*/
|
|
56
|
+
export function getStateBatonFilePath(sessionId = 'default', options = {}) {
|
|
57
|
+
const cwd = getCwd(options);
|
|
58
|
+
const safeId = sanitizeSessionId(sessionId);
|
|
59
|
+
return path.join(cwd, '.claude', 'cache', `state_baton_${safeId}.json`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Builds or updates a deterministic Durable Fact Schema (`StateBaton`) bounded to ~300 tokens.
|
|
64
|
+
*
|
|
65
|
+
* @param {object} [input={}]
|
|
66
|
+
* @param {string} [input.sessionId='default']
|
|
67
|
+
* @param {string} [input.modelId='claude-sonnet-5-5']
|
|
68
|
+
* @param {string} [input.activeGoal]
|
|
69
|
+
* @param {Array<string>} [input.workingSetFiles]
|
|
70
|
+
* @param {Array<string>} [input.verifiedInvariants]
|
|
71
|
+
* @param {Array<string>} [input.deadEndsAndFailures]
|
|
72
|
+
* @param {Array<object>} [input.queuedCacheMutations]
|
|
73
|
+
* @param {number} [input.savedTokensBeforeCompact=0]
|
|
74
|
+
* @param {number} [input.savedUSDBeforeCompact=0]
|
|
75
|
+
* @param {number} [input.nowMs=Date.now()]
|
|
76
|
+
*/
|
|
77
|
+
export function buildDurableStateBaton(input = {}) {
|
|
78
|
+
const nowMs = input.nowMs ?? Date.now();
|
|
79
|
+
const activeGoal = String(
|
|
80
|
+
input.activeGoal || 'Maintain active implementation progress and verified invariants across compaction'
|
|
81
|
+
)
|
|
82
|
+
.trim()
|
|
83
|
+
.slice(0, 240);
|
|
84
|
+
|
|
85
|
+
const workingSetFiles = Array.from(new Set(input.workingSetFiles || []))
|
|
86
|
+
.map((f) => String(f).trim())
|
|
87
|
+
.filter(Boolean)
|
|
88
|
+
.slice(0, 12);
|
|
89
|
+
|
|
90
|
+
const verifiedInvariants = Array.from(new Set(input.verifiedInvariants || []))
|
|
91
|
+
.map((inv) => String(inv).trim().slice(0, 140))
|
|
92
|
+
.filter(Boolean)
|
|
93
|
+
.slice(0, 6);
|
|
94
|
+
|
|
95
|
+
const deadEndsAndFailures = Array.from(new Set(input.deadEndsAndFailures || []))
|
|
96
|
+
.map((err) => String(err).trim().slice(0, 140))
|
|
97
|
+
.filter(Boolean)
|
|
98
|
+
.slice(0, 5);
|
|
99
|
+
|
|
100
|
+
const queuedCacheMutations = Array.isArray(input.queuedCacheMutations)
|
|
101
|
+
? input.queuedCacheMutations.slice(0, 8)
|
|
102
|
+
: [];
|
|
103
|
+
|
|
104
|
+
const sessionId = sanitizeSessionId(input.sessionId || input.session_id || 'default');
|
|
105
|
+
const explicitCycle =
|
|
106
|
+
input.compactionId || input.compaction_id || input.compactionEpoch || input.turnId || null;
|
|
107
|
+
const compactionId = explicitCycle
|
|
108
|
+
? `${sessionId}:${String(explicitCycle)}`
|
|
109
|
+
: `${sessionId}:compact:${nowMs}`;
|
|
110
|
+
|
|
111
|
+
return {
|
|
112
|
+
schemaVersion: '2026.11.1',
|
|
113
|
+
createdAt: nowMs,
|
|
114
|
+
sessionId,
|
|
115
|
+
compactionId,
|
|
116
|
+
ledgerReceiptRecorded: false,
|
|
117
|
+
lastRecordedCompactionId: null,
|
|
118
|
+
modelId: String(input.modelId || input.model_id || input.model || 'claude-sonnet-5-5'),
|
|
119
|
+
activeGoal,
|
|
120
|
+
workingSetFiles,
|
|
121
|
+
verifiedInvariants,
|
|
122
|
+
deadEndsAndFailures,
|
|
123
|
+
queuedCacheMutations,
|
|
124
|
+
metricsSnapshot: {
|
|
125
|
+
savedTokensBeforeCompact: Math.max(0, Math.round(Number(input.savedTokensBeforeCompact || 0))),
|
|
126
|
+
savedUSDBeforeCompact: Math.max(0, Number(Number(input.savedUSDBeforeCompact || 0).toFixed(6)))
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Formats the Durable State Baton into a compact ~300-token `additionalContext` string
|
|
133
|
+
* for injection on `SessionStart[compact|resume|startup|clear|fork]`.
|
|
134
|
+
*
|
|
135
|
+
* @param {object} baton
|
|
136
|
+
* @returns {string}
|
|
137
|
+
*/
|
|
138
|
+
export function formatBatonAdditionalContext(baton = {}) {
|
|
139
|
+
if (!baton || typeof baton !== 'object') return '';
|
|
140
|
+
const files =
|
|
141
|
+
Array.isArray(baton.workingSetFiles) && baton.workingSetFiles.length > 0
|
|
142
|
+
? baton.workingSetFiles.join(', ')
|
|
143
|
+
: 'none recorded';
|
|
144
|
+
const invariants =
|
|
145
|
+
Array.isArray(baton.verifiedInvariants) && baton.verifiedInvariants.length > 0
|
|
146
|
+
? baton.verifiedInvariants.map((i) => `- ${i}`).join('\n')
|
|
147
|
+
: '- Keep existing tests green and preserve cache prefix stability';
|
|
148
|
+
const deadEnds =
|
|
149
|
+
Array.isArray(baton.deadEndsAndFailures) && baton.deadEndsAndFailures.length > 0
|
|
150
|
+
? baton.deadEndsAndFailures.map((d) => `- ${d}`).join('\n')
|
|
151
|
+
: '- None';
|
|
152
|
+
const mutations =
|
|
153
|
+
Array.isArray(baton.queuedCacheMutations) && baton.queuedCacheMutations.length > 0
|
|
154
|
+
? baton.queuedCacheMutations.map((m) => `${m.type}=${JSON.stringify(m.value)}`).join(', ')
|
|
155
|
+
: 'none';
|
|
156
|
+
|
|
157
|
+
const block = [
|
|
158
|
+
`<attention_horizon_state_baton session="${baton.sessionId || 'default'}" model="${baton.modelId || 'claude-sonnet-5-5'}">`,
|
|
159
|
+
`Active Goal: ${baton.activeGoal || 'Continue active task'}`,
|
|
160
|
+
`Working Set Files: ${files}`,
|
|
161
|
+
`Verified Invariants:\n${invariants}`,
|
|
162
|
+
`Avoid Dead Ends / Prior Failures:\n${deadEnds}`,
|
|
163
|
+
`Post-Compaction Applied Mutations: ${mutations}`,
|
|
164
|
+
`</attention_horizon_state_baton>`
|
|
165
|
+
].join('\n');
|
|
166
|
+
|
|
167
|
+
// Hard cap at ~1,200 chars (~300 tokens)
|
|
168
|
+
return block.length <= 1250 ? block : `${block.slice(0, 1210)}\n</attention_horizon_state_baton>`;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Renders a cross-tool portable Markdown handoff document (`docs/HANDOFF_<timestamp>.md`).
|
|
173
|
+
*
|
|
174
|
+
* @param {object} baton
|
|
175
|
+
* @returns {string}
|
|
176
|
+
*/
|
|
177
|
+
export function renderPortableHandoffMarkdown(baton = {}) {
|
|
178
|
+
const isoDate = new Date(baton.createdAt || Date.now()).toISOString();
|
|
179
|
+
const filesList =
|
|
180
|
+
Array.isArray(baton.workingSetFiles) && baton.workingSetFiles.length > 0
|
|
181
|
+
? baton.workingSetFiles.map((f) => `- \`${f}\``).join('\n')
|
|
182
|
+
: '- *(none recorded)*';
|
|
183
|
+
const invariantsList =
|
|
184
|
+
Array.isArray(baton.verifiedInvariants) && baton.verifiedInvariants.length > 0
|
|
185
|
+
? baton.verifiedInvariants.map((i) => `- [x] ${i}`).join('\n')
|
|
186
|
+
: '- [x] Maintain existing test suite pass rate';
|
|
187
|
+
const deadEndsList =
|
|
188
|
+
Array.isArray(baton.deadEndsAndFailures) && baton.deadEndsAndFailures.length > 0
|
|
189
|
+
? baton.deadEndsAndFailures.map((d) => `- ${d}`).join('\n')
|
|
190
|
+
: '- *(none recorded)*';
|
|
191
|
+
const mutationsList =
|
|
192
|
+
Array.isArray(baton.queuedCacheMutations) && baton.queuedCacheMutations.length > 0
|
|
193
|
+
? baton.queuedCacheMutations
|
|
194
|
+
.map((m) => `- **${m.type}** (\`${m.key}\`): \`${JSON.stringify(m.value)}\` — ${m.reason || ''}`)
|
|
195
|
+
.join('\n')
|
|
196
|
+
: '- *(no deferred cache mutations)*';
|
|
197
|
+
|
|
198
|
+
return [
|
|
199
|
+
`# Highbeam State Baton Handoff`,
|
|
200
|
+
``,
|
|
201
|
+
`- **Session ID:** \`${baton.sessionId || 'default'}\``,
|
|
202
|
+
`- **Active Model:** \`${baton.modelId || 'claude-sonnet-5-5'}\``,
|
|
203
|
+
`- **Captured At:** \`${isoDate}\``,
|
|
204
|
+
``,
|
|
205
|
+
`## 1. Active Goal`,
|
|
206
|
+
`${baton.activeGoal || 'Continue active task'}`,
|
|
207
|
+
``,
|
|
208
|
+
`## 2. Working Set Files`,
|
|
209
|
+
filesList,
|
|
210
|
+
``,
|
|
211
|
+
`## 3. Verified Invariants`,
|
|
212
|
+
invariantsList,
|
|
213
|
+
``,
|
|
214
|
+
`## 4. Dead Ends & Failures to Avoid`,
|
|
215
|
+
deadEndsList,
|
|
216
|
+
``,
|
|
217
|
+
`## 5. Queued Cache-Prefix Mutations (Released on PostCompact)`,
|
|
218
|
+
mutationsList,
|
|
219
|
+
``
|
|
220
|
+
].join('\n');
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Formats an epoch-ms timestamp as UTC `YYYYMMDD_HHMMSS` for shared cross-edition
|
|
225
|
+
* `HANDOFF_<YYYYMMDD_HHMMSS>.md` filenames (`ISS-055`).
|
|
226
|
+
*
|
|
227
|
+
* @param {number} [nowMs=Date.now()]
|
|
228
|
+
* @returns {string}
|
|
229
|
+
*/
|
|
230
|
+
export function formatUtcHandoffTimestamp(nowMs = Date.now()) {
|
|
231
|
+
const numeric = Number(nowMs);
|
|
232
|
+
const d = new Date(Number.isFinite(numeric) ? numeric : Date.now());
|
|
233
|
+
const pad2 = (n) => String(n).padStart(2, '0');
|
|
234
|
+
return (
|
|
235
|
+
`${d.getUTCFullYear()}${pad2(d.getUTCMonth() + 1)}${pad2(d.getUTCDate())}_` +
|
|
236
|
+
`${pad2(d.getUTCHours())}${pad2(d.getUTCMinutes())}${pad2(d.getUTCSeconds())}`
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Extracts a UTC epoch-ms timestamp from `HANDOFF_YYYYMMDD_HHMMSS.md` (or legacy `HANDOFF_<epochMs>.md`).
|
|
242
|
+
* @param {string} [filename='']
|
|
243
|
+
* @returns {number}
|
|
244
|
+
*/
|
|
245
|
+
export function parseHandoffFilenameTimestampMs(filename = '') {
|
|
246
|
+
const base = path.basename(String(filename || ''));
|
|
247
|
+
const utcMatch = base.match(/^HANDOFF_(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})\.md$/i);
|
|
248
|
+
if (utcMatch) {
|
|
249
|
+
return Date.UTC(
|
|
250
|
+
Number(utcMatch[1]),
|
|
251
|
+
Number(utcMatch[2]) - 1,
|
|
252
|
+
Number(utcMatch[3]),
|
|
253
|
+
Number(utcMatch[4]),
|
|
254
|
+
Number(utcMatch[5]),
|
|
255
|
+
Number(utcMatch[6])
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
const epochMatch = base.match(/^HANDOFF_(\d{10,15})\.md$/i);
|
|
259
|
+
if (epochMatch) {
|
|
260
|
+
const ms = Number(epochMatch[1]);
|
|
261
|
+
return ms < 1e11 ? ms * 1000 : ms;
|
|
262
|
+
}
|
|
263
|
+
return 0;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Parses a portable Markdown handoff document (from either Claude Code `State Baton Handoff`,
|
|
268
|
+
* Antigravity `Baton-Pass Handoff Bundle`, or `/handoff` markdown) into a `StateBaton` object (`ISS-055`).
|
|
269
|
+
*
|
|
270
|
+
* @param {string} markdownText
|
|
271
|
+
* @param {object} [defaults={}]
|
|
272
|
+
* @returns {object | null}
|
|
273
|
+
*/
|
|
274
|
+
export function parsePortableHandoffMarkdown(markdownText = '', defaults = {}) {
|
|
275
|
+
const raw = String(markdownText || '').trim();
|
|
276
|
+
if (!raw) return null;
|
|
277
|
+
|
|
278
|
+
const lines = raw.split(/\r?\n/);
|
|
279
|
+
let sessionId = defaults.sessionId || '';
|
|
280
|
+
let modelId = defaults.modelId || 'claude-sonnet-5-5';
|
|
281
|
+
let parsedCreatedAt = 0;
|
|
282
|
+
|
|
283
|
+
const goalLines = [];
|
|
284
|
+
const workingSetFiles = [];
|
|
285
|
+
const verifiedInvariants = [];
|
|
286
|
+
const deadEndsAndFailures = [];
|
|
287
|
+
const queuedCacheMutations = [];
|
|
288
|
+
const topSummaryLines = [];
|
|
289
|
+
|
|
290
|
+
let currentSection = 'preamble';
|
|
291
|
+
|
|
292
|
+
const classifyHeading = (headingText) => {
|
|
293
|
+
const h = headingText.toLowerCase();
|
|
294
|
+
if (
|
|
295
|
+
/(?:active\s+goal|resume\s+contract|active\s+step|objective|current\s+goal|active\s+task|next\s+step|next\s+action)/i.test(
|
|
296
|
+
h
|
|
297
|
+
)
|
|
298
|
+
) {
|
|
299
|
+
return 'goal';
|
|
300
|
+
}
|
|
301
|
+
if (/(?:working\s+set|owned\s+scope|modified\s+files|active\s+files|files\s+locked|scope\s+paths|^files$)/i.test(h)) {
|
|
302
|
+
return 'files';
|
|
303
|
+
}
|
|
304
|
+
if (/(?:verified\s+invariant|verified\s+unchanged|invariant|architectural|file\s+schema|decision)/i.test(h)) {
|
|
305
|
+
return 'invariants';
|
|
306
|
+
}
|
|
307
|
+
if (/(?:dead\s+end|negative\s+constraint|failure|failed|avoid|do\s+not\s+repeat)/i.test(h)) {
|
|
308
|
+
return 'dead_ends';
|
|
309
|
+
}
|
|
310
|
+
if (/(?:queued\s+cache|deferred.*mutation|cache-prefix\s+mutation)/i.test(h)) {
|
|
311
|
+
return 'mutations';
|
|
312
|
+
}
|
|
313
|
+
return 'other';
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
const cleanBulletItem = (line) =>
|
|
317
|
+
line
|
|
318
|
+
.replace(/^\s*(?:[-*+]|\d+\.)\s*(?:\[[ xX]\]\s*)?/, '')
|
|
319
|
+
.trim();
|
|
320
|
+
|
|
321
|
+
const isPlaceholderBullet = (item) =>
|
|
322
|
+
!item ||
|
|
323
|
+
/^\*\(.*\)\*$/i.test(item) ||
|
|
324
|
+
/^(?:none|none\s+recorded|n\/a|no\s+deferred\s+cache\s+mutations)$/i.test(item);
|
|
325
|
+
|
|
326
|
+
for (const rawLine of lines) {
|
|
327
|
+
const trimmed = rawLine.trim();
|
|
328
|
+
if (!trimmed) continue;
|
|
329
|
+
|
|
330
|
+
// Top-level title
|
|
331
|
+
if (/^#\s+/.test(trimmed) && !/^##/.test(trimmed)) {
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Section heading
|
|
336
|
+
const headingMatch = trimmed.match(/^#{2,4}\s+(?:\d+\.\s*)?(.+)$/);
|
|
337
|
+
if (headingMatch) {
|
|
338
|
+
currentSection = classifyHeading(headingMatch[1]);
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// Metadata extraction in preamble or anywhere near top
|
|
343
|
+
const sessionMeta = trimmed.match(
|
|
344
|
+
/(?:Session\s*ID|Trajectory(?:\s*\/\s*Session)?|Session)\s*:\**\s*`?([^`|*]+)`?/i
|
|
345
|
+
);
|
|
346
|
+
if (sessionMeta && currentSection === 'preamble') {
|
|
347
|
+
sessionId = sessionMeta[1].trim();
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const modelMeta = trimmed.match(/(?:Active\s*Model|Model)\s*:\**\s*`?([^`|*]+)`?/i);
|
|
352
|
+
if (modelMeta && currentSection === 'preamble') {
|
|
353
|
+
modelId = modelMeta[1].trim();
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const dateMeta = trimmed.match(
|
|
358
|
+
/(?:Captured\s*At|Generated(?:\s*At)?|Created(?:\s*At)?|Timestamp)\s*:\**\s*`?([^`]+)`?/i
|
|
359
|
+
);
|
|
360
|
+
if (dateMeta && currentSection === 'preamble') {
|
|
361
|
+
const ts = Date.parse(dateMeta[1].trim());
|
|
362
|
+
if (!Number.isNaN(ts)) parsedCreatedAt = ts;
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
if (currentSection === 'preamble') {
|
|
367
|
+
if (!trimmed.startsWith('>') && !trimmed.startsWith('---')) {
|
|
368
|
+
topSummaryLines.push(cleanBulletItem(trimmed));
|
|
369
|
+
}
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (currentSection === 'goal') {
|
|
374
|
+
const cleaned = cleanBulletItem(trimmed);
|
|
375
|
+
if (!isPlaceholderBullet(cleaned)) {
|
|
376
|
+
goalLines.push(cleaned);
|
|
377
|
+
}
|
|
378
|
+
} else if (currentSection === 'files') {
|
|
379
|
+
const cleaned = cleanBulletItem(trimmed);
|
|
380
|
+
if (!isPlaceholderBullet(cleaned)) {
|
|
381
|
+
const backtickMatch = cleaned.match(/^`([^`]+)`/);
|
|
382
|
+
const fileCandidate = (backtickMatch ? backtickMatch[1] : cleaned.split(/\s+[—–-]\s+/)[0]).trim();
|
|
383
|
+
if (fileCandidate && !isPlaceholderBullet(fileCandidate)) {
|
|
384
|
+
workingSetFiles.push(fileCandidate.replace(/^`|`$/g, ''));
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
} else if (currentSection === 'invariants') {
|
|
388
|
+
const cleaned = cleanBulletItem(trimmed);
|
|
389
|
+
if (!isPlaceholderBullet(cleaned)) {
|
|
390
|
+
verifiedInvariants.push(cleaned);
|
|
391
|
+
}
|
|
392
|
+
} else if (currentSection === 'dead_ends') {
|
|
393
|
+
const cleaned = cleanBulletItem(trimmed);
|
|
394
|
+
if (!isPlaceholderBullet(cleaned)) {
|
|
395
|
+
deadEndsAndFailures.push(cleaned);
|
|
396
|
+
}
|
|
397
|
+
} else if (currentSection === 'mutations') {
|
|
398
|
+
const mutMatch = trimmed.match(
|
|
399
|
+
/[-*]\s*\*\*([^*]+)\*\*\s*\(`([^`]+)`\)\s*:\s*`([^`]+)`(?:\s*[—-]\s*(.*))?/
|
|
400
|
+
);
|
|
401
|
+
if (mutMatch) {
|
|
402
|
+
let parsedVal = mutMatch[3];
|
|
403
|
+
if (/^(?:["{[\d-]|true$|false$|null$)/.test(parsedVal.trim())) {
|
|
404
|
+
try {
|
|
405
|
+
parsedVal = JSON.parse(mutMatch[3]);
|
|
406
|
+
} catch (err) {
|
|
407
|
+
recordRuntimeDiagnostic(
|
|
408
|
+
'stateBatonHydrator',
|
|
409
|
+
'parsePortableHandoffMarkdown.mutationValue',
|
|
410
|
+
err,
|
|
411
|
+
defaults
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
queuedCacheMutations.push({
|
|
416
|
+
type: mutMatch[1].trim(),
|
|
417
|
+
key: mutMatch[2].trim(),
|
|
418
|
+
value: parsedVal,
|
|
419
|
+
reason: (mutMatch[4] || '').trim()
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const activeGoal =
|
|
426
|
+
goalLines.join(' ').trim() ||
|
|
427
|
+
topSummaryLines.join(' ').trim() ||
|
|
428
|
+
'Continue active implementation from portable handoff baton';
|
|
429
|
+
|
|
430
|
+
const built = buildDurableStateBaton({
|
|
431
|
+
sessionId: sessionId || defaults.fallbackSessionId || 'default',
|
|
432
|
+
modelId,
|
|
433
|
+
activeGoal,
|
|
434
|
+
workingSetFiles,
|
|
435
|
+
verifiedInvariants,
|
|
436
|
+
deadEndsAndFailures,
|
|
437
|
+
queuedCacheMutations,
|
|
438
|
+
nowMs: parsedCreatedAt || defaults.nowMs || Date.now()
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
return {
|
|
442
|
+
...built,
|
|
443
|
+
source: 'portable_markdown',
|
|
444
|
+
parsedCreatedAt
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Executes `PreCompact` hydration:
|
|
450
|
+
* 1. Builds and persists the Durable State Baton to `.claude/cache/state_baton_<sessionId>.json`
|
|
451
|
+
* 2. Writes portable Markdown handoff to `HANDOFF_<YYYYMMDD_HHMMSS>.md` + `HANDOFF_LATEST.md`
|
|
452
|
+
* inside `.claude/cache/` (or explicit `options.handoffDir` when configured — keeping git-tracked `docs/` clean by default) (`ISS-055`).
|
|
453
|
+
*
|
|
454
|
+
* @param {object} [input={}]
|
|
455
|
+
* @param {object} [options={}]
|
|
456
|
+
* @returns {{ ok: boolean, baton: object, batonFilePath: string, handoffMarkdownPath: string, handoffLatestPath: string }}
|
|
457
|
+
*/
|
|
458
|
+
export function handlePreCompactBatonFlush(input = {}, options = {}) {
|
|
459
|
+
const nowMs = options.nowMs ?? input.nowMs ?? Date.now();
|
|
460
|
+
const explicitCwd = options.cwd || input.cwd || null;
|
|
461
|
+
const cwd = getCwd(explicitCwd ? { ...options, cwd: explicitCwd } : options);
|
|
462
|
+
const ioOpts = { ...options, cwd };
|
|
463
|
+
const diagOpts = explicitCwd ? ioOpts : { ...options, cwd: undefined };
|
|
464
|
+
const baton = buildDurableStateBaton({ ...input, nowMs });
|
|
465
|
+
|
|
466
|
+
const batonFilePath = getStateBatonFilePath(baton.sessionId, ioOpts);
|
|
467
|
+
const existingBaton = readBatonJsonWithDiagnostics(
|
|
468
|
+
batonFilePath,
|
|
469
|
+
'handlePreCompactBatonFlush.readBaton',
|
|
470
|
+
ioOpts,
|
|
471
|
+
diagOpts
|
|
472
|
+
);
|
|
473
|
+
|
|
474
|
+
// Deduplicate concurrent Tier-1 Mod + Tier-2 CLI PreCompact flushes on the same compaction cycle (ISS-036)
|
|
475
|
+
const hasExplicitId = Boolean(
|
|
476
|
+
input.compactionId || input.compaction_id || input.compactionEpoch || input.turnId
|
|
477
|
+
);
|
|
478
|
+
if (
|
|
479
|
+
!hasExplicitId &&
|
|
480
|
+
existingBaton &&
|
|
481
|
+
existingBaton.compactionId &&
|
|
482
|
+
existingBaton.ledgerReceiptRecorded === false &&
|
|
483
|
+
Math.abs(nowMs - Number(existingBaton.createdAt || 0)) <= 5000
|
|
484
|
+
) {
|
|
485
|
+
baton.compactionId = existingBaton.compactionId;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
writeJsonAtomic(batonFilePath, baton, ioOpts);
|
|
489
|
+
|
|
490
|
+
const cacheDir = path.join(cwd, '.claude', 'cache');
|
|
491
|
+
const defaultBatonPath = path.join(cacheDir, 'state_baton.json');
|
|
492
|
+
writeJsonAtomic(defaultBatonPath, baton, ioOpts);
|
|
493
|
+
|
|
494
|
+
const utcStamp = formatUtcHandoffTimestamp(nowMs);
|
|
495
|
+
const targetHandoffDir = options.handoffDir || input.handoffDir || cacheDir;
|
|
496
|
+
const handoffMarkdownPath = path.join(targetHandoffDir, `HANDOFF_${utcStamp}.md`);
|
|
497
|
+
const handoffLatestPath = path.join(targetHandoffDir, 'HANDOFF_LATEST.md');
|
|
498
|
+
const cacheLatestPath = path.join(cacheDir, 'HANDOFF_LATEST.md');
|
|
499
|
+
|
|
500
|
+
if (options.writeMarkdown !== false) {
|
|
501
|
+
const markdownContent = renderPortableHandoffMarkdown(baton);
|
|
502
|
+
writeTextAtomic(handoffMarkdownPath, markdownContent, ioOpts);
|
|
503
|
+
writeTextAtomic(handoffLatestPath, markdownContent, ioOpts);
|
|
504
|
+
if (cacheLatestPath !== handoffLatestPath) {
|
|
505
|
+
writeTextAtomic(cacheLatestPath, markdownContent, ioOpts);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
return {
|
|
510
|
+
ok: true,
|
|
511
|
+
baton,
|
|
512
|
+
compactionKey: `${baton.sessionId}:${baton.compactionId}`,
|
|
513
|
+
batonFilePath,
|
|
514
|
+
handoffMarkdownPath,
|
|
515
|
+
handoffLatestPath
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* Discovers the newest valid portable Markdown handoff artifact across `.agents/horizon/`,
|
|
521
|
+
* `.claude/cache/`, and `docs/` (`ISS-055`).
|
|
522
|
+
*
|
|
523
|
+
* @param {string} cwd
|
|
524
|
+
* @param {string} sessionId
|
|
525
|
+
* @param {object} ioOpts
|
|
526
|
+
* @returns {{ baton: object, path: string, effectiveTs: number, isExternal: boolean } | null}
|
|
527
|
+
*/
|
|
528
|
+
function findNewestMarkdownHandoffCandidate(cwd, sessionId, ioOpts = {}) {
|
|
529
|
+
const candidates = [];
|
|
530
|
+
|
|
531
|
+
const pushCandidatePath = (filePath, isExternal) => {
|
|
532
|
+
if (!filePath || !fileExists(filePath, ioOpts)) return;
|
|
533
|
+
candidates.push({ filePath, isExternal });
|
|
534
|
+
};
|
|
535
|
+
|
|
536
|
+
if (ioOpts.handoffMarkdownPath) {
|
|
537
|
+
pushCandidatePath(ioOpts.handoffMarkdownPath, true);
|
|
538
|
+
}
|
|
539
|
+
pushCandidatePath(path.join(cwd, '.agents', 'horizon', 'HANDOFF_LATEST.md'), true);
|
|
540
|
+
pushCandidatePath(path.join(cwd, '.claude', 'cache', 'HANDOFF_LATEST.md'), false);
|
|
541
|
+
|
|
542
|
+
const scanDirs = [
|
|
543
|
+
{ dir: path.join(cwd, '.agents', 'horizon'), isExternal: true },
|
|
544
|
+
{ dir: path.join(cwd, 'docs'), isExternal: true }
|
|
545
|
+
];
|
|
546
|
+
if (ioOpts.handoffDir) {
|
|
547
|
+
scanDirs.push({ dir: ioOpts.handoffDir, isExternal: true });
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
for (const { dir, isExternal } of scanDirs) {
|
|
551
|
+
const entries = readdirSafe(dir, ioOpts);
|
|
552
|
+
for (const entry of entries) {
|
|
553
|
+
if (/^HANDOFF_.*\.md$/i.test(entry)) {
|
|
554
|
+
pushCandidatePath(path.join(dir, entry), isExternal);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
let best = null;
|
|
560
|
+
const visited = new Set();
|
|
561
|
+
for (const { filePath, isExternal } of candidates) {
|
|
562
|
+
if (visited.has(filePath)) continue;
|
|
563
|
+
visited.add(filePath);
|
|
564
|
+
const mdText = readTextSafe(filePath, null, ioOpts);
|
|
565
|
+
if (!mdText) continue;
|
|
566
|
+
const parsed = parsePortableHandoffMarkdown(mdText, { fallbackSessionId: sessionId });
|
|
567
|
+
if (!parsed) continue;
|
|
568
|
+
const mtimeMs = getFileMtimeMsSafe(filePath, ioOpts);
|
|
569
|
+
const nameTs = parseHandoffFilenameTimestampMs(filePath);
|
|
570
|
+
const effectiveTs = Math.max(mtimeMs, Number(parsed.parsedCreatedAt || 0), nameTs);
|
|
571
|
+
if (
|
|
572
|
+
!best ||
|
|
573
|
+
effectiveTs > best.effectiveTs ||
|
|
574
|
+
(effectiveTs === best.effectiveTs && isExternal && !best.isExternal)
|
|
575
|
+
) {
|
|
576
|
+
best = {
|
|
577
|
+
baton: parsed,
|
|
578
|
+
path: filePath,
|
|
579
|
+
effectiveTs,
|
|
580
|
+
isExternal
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
return best;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/**
|
|
589
|
+
* Executes `SessionStart` (`startup|resume|clear|compact|fork`) State Baton hydration,
|
|
590
|
+
* returning the ~300-token `additionalContext` payload for Claude Code.
|
|
591
|
+
* Supports both `.claude/cache/state_baton*.json` AND cross-tool portable Markdown handoffs
|
|
592
|
+
* (`.agents/horizon/HANDOFF_LATEST.md`, `.claude/cache/HANDOFF_LATEST.md`, `docs/HANDOFF_*.md`) (`ISS-055`).
|
|
593
|
+
*
|
|
594
|
+
* @param {object} [event={}]
|
|
595
|
+
* @param {object} [options={}]
|
|
596
|
+
* @returns {{ hydrated: boolean, hydratedFrom?: string, baton: object | null, additionalContext: string, hookSpecificOutput: object | null }}
|
|
597
|
+
*/
|
|
598
|
+
export function handleSessionStartHydration(event = {}, options = {}) {
|
|
599
|
+
const explicitCwd = options.cwd || event.cwd || null;
|
|
600
|
+
const cwd = getCwd(explicitCwd ? { ...options, cwd: explicitCwd } : options);
|
|
601
|
+
const ioOpts = { ...options, cwd };
|
|
602
|
+
const diagOpts = explicitCwd ? ioOpts : { ...options, cwd: undefined };
|
|
603
|
+
const sessionId = sanitizeSessionId(event.session_id || event.sessionId || 'default');
|
|
604
|
+
|
|
605
|
+
const sessionBatonPath = getStateBatonFilePath(sessionId, ioOpts);
|
|
606
|
+
let jsonBaton = readBatonJsonWithDiagnostics(
|
|
607
|
+
sessionBatonPath,
|
|
608
|
+
'handleSessionStartHydration.readSessionBaton',
|
|
609
|
+
ioOpts,
|
|
610
|
+
diagOpts
|
|
611
|
+
);
|
|
612
|
+
let jsonBatonPath = sessionBatonPath;
|
|
613
|
+
|
|
614
|
+
if (!jsonBaton) {
|
|
615
|
+
const fallbackPath = path.join(cwd, '.claude', 'cache', 'state_baton.json');
|
|
616
|
+
jsonBaton = readBatonJsonWithDiagnostics(
|
|
617
|
+
fallbackPath,
|
|
618
|
+
'handleSessionStartHydration.readFallbackBaton',
|
|
619
|
+
ioOpts,
|
|
620
|
+
diagOpts
|
|
621
|
+
);
|
|
622
|
+
jsonBatonPath = fallbackPath;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
const jsonEffectiveTs = jsonBaton
|
|
626
|
+
? Math.max(getFileMtimeMsSafe(jsonBatonPath, ioOpts), Number(jsonBaton.createdAt || 0))
|
|
627
|
+
: 0;
|
|
628
|
+
|
|
629
|
+
const bestMarkdown = findNewestMarkdownHandoffCandidate(cwd, sessionId, ioOpts);
|
|
630
|
+
|
|
631
|
+
let baton = jsonBaton;
|
|
632
|
+
let hydratedFrom = jsonBaton ? 'json' : null;
|
|
633
|
+
let hydratedPath = jsonBaton ? jsonBatonPath : null;
|
|
634
|
+
|
|
635
|
+
if (bestMarkdown) {
|
|
636
|
+
const preferMarkdown =
|
|
637
|
+
!jsonBaton ||
|
|
638
|
+
(bestMarkdown.isExternal && bestMarkdown.effectiveTs > jsonEffectiveTs) ||
|
|
639
|
+
bestMarkdown.effectiveTs > jsonEffectiveTs + 50;
|
|
640
|
+
if (preferMarkdown) {
|
|
641
|
+
baton = bestMarkdown.baton;
|
|
642
|
+
hydratedFrom = 'markdown';
|
|
643
|
+
hydratedPath = bestMarkdown.path;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
if (!baton) {
|
|
648
|
+
return {
|
|
649
|
+
hydrated: false,
|
|
650
|
+
hydratedFrom: null,
|
|
651
|
+
baton: null,
|
|
652
|
+
additionalContext: '',
|
|
653
|
+
hookSpecificOutput: null
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
const additionalContext = formatBatonAdditionalContext(baton);
|
|
658
|
+
return {
|
|
659
|
+
hydrated: true,
|
|
660
|
+
hydratedFrom,
|
|
661
|
+
hydratedPath,
|
|
662
|
+
baton,
|
|
663
|
+
additionalContext,
|
|
664
|
+
hookSpecificOutput: {
|
|
665
|
+
hookEventName: 'SessionStart',
|
|
666
|
+
additionalContext
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* Executes `PostCompact` queue flush and records savings into `SavedQuotaReceiptLedger` (`horizon_ledger.jsonl`).
|
|
673
|
+
* Deduplicates dual Tier-1 Mod + Tier-2 CLI execution using `(sessionId, compactionId)` (`ISS-036`).
|
|
674
|
+
*
|
|
675
|
+
* @param {object} [event={}]
|
|
676
|
+
* @param {object} [options={}]
|
|
677
|
+
*/
|
|
678
|
+
export function handlePostCompactFlush(event = {}, options = {}) {
|
|
679
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
680
|
+
const explicitCwd = options.cwd || event.cwd || null;
|
|
681
|
+
const cwd = getCwd(explicitCwd ? { ...options, cwd: explicitCwd } : options);
|
|
682
|
+
const ioOpts = { ...options, cwd };
|
|
683
|
+
const diagOpts = explicitCwd ? ioOpts : { ...options, cwd: undefined };
|
|
684
|
+
const sessionId = sanitizeSessionId(event.session_id || event.sessionId || 'default');
|
|
685
|
+
|
|
686
|
+
const sessionBatonPath = getStateBatonFilePath(sessionId, ioOpts);
|
|
687
|
+
const defaultBatonPath = path.join(cwd, '.claude', 'cache', 'state_baton.json');
|
|
688
|
+
let baton = readBatonJsonWithDiagnostics(
|
|
689
|
+
sessionBatonPath,
|
|
690
|
+
'handlePostCompactFlush.readSessionBaton',
|
|
691
|
+
ioOpts,
|
|
692
|
+
diagOpts
|
|
693
|
+
);
|
|
694
|
+
if (!baton) {
|
|
695
|
+
baton = readBatonJsonWithDiagnostics(
|
|
696
|
+
defaultBatonPath,
|
|
697
|
+
'handlePostCompactFlush.readFallbackBaton',
|
|
698
|
+
ioOpts,
|
|
699
|
+
diagOpts
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const explicitCycle =
|
|
704
|
+
event.compactionId || event.compaction_id || event.compactionEpoch || event.turnId || null;
|
|
705
|
+
const cycleId = explicitCycle
|
|
706
|
+
? `${sessionId}:${String(explicitCycle)}`
|
|
707
|
+
: baton?.compactionId || `${sessionId}:post:${baton?.createdAt || nowMs}`;
|
|
708
|
+
const dedupKey = `${cwd}::${sessionId}::${cycleId}`;
|
|
709
|
+
|
|
710
|
+
const alreadyRecordedOnBaton = Boolean(
|
|
711
|
+
baton &&
|
|
712
|
+
(baton.lastRecordedCompactionId === cycleId ||
|
|
713
|
+
(baton.compactionId === cycleId && baton.ledgerReceiptRecorded === true))
|
|
714
|
+
);
|
|
715
|
+
|
|
716
|
+
if (alreadyRecordedOnBaton || inMemoryRecordedCompactionKeys.has(dedupKey)) {
|
|
717
|
+
return {
|
|
718
|
+
ok: true,
|
|
719
|
+
deduplicated: true,
|
|
720
|
+
sessionId,
|
|
721
|
+
compactionId: cycleId,
|
|
722
|
+
flushedCount: 0,
|
|
723
|
+
appliedMutations: [],
|
|
724
|
+
totalAvoidedPenaltyUSD: 0,
|
|
725
|
+
ledgerEntry: null
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
const queue =
|
|
730
|
+
options.mutationQueue instanceof PostCompactMutationQueue
|
|
731
|
+
? options.mutationQueue
|
|
732
|
+
: new PostCompactMutationQueue(baton?.queuedCacheMutations || event.queuedCacheMutations || []);
|
|
733
|
+
|
|
734
|
+
const flushResult = queue.flush({ nowMs });
|
|
735
|
+
|
|
736
|
+
// Clear queuedCacheMutations and persist idempotent compaction receipt marker in stored baton
|
|
737
|
+
if (baton) {
|
|
738
|
+
baton.queuedCacheMutations = [];
|
|
739
|
+
baton.lastFlushedAt = nowMs;
|
|
740
|
+
baton.ledgerReceiptRecorded = true;
|
|
741
|
+
baton.lastRecordedCompactionId = cycleId;
|
|
742
|
+
writeJsonAtomic(sessionBatonPath, baton, ioOpts);
|
|
743
|
+
writeJsonAtomic(defaultBatonPath, baton, ioOpts);
|
|
744
|
+
}
|
|
745
|
+
inMemoryRecordedCompactionKeys.add(dedupKey);
|
|
746
|
+
|
|
747
|
+
// Record savings receipt in append-only horizon_ledger.jsonl at most once per compaction cycle (`ISS-024`: never fabricate 25000/mutation)
|
|
748
|
+
const summedFlushedTokens = flushResult.appliedMutations.reduce(
|
|
749
|
+
(acc, entry) => acc + Math.max(0, Number(entry?.cachedTokens || entry?.savedTokens || 0)),
|
|
750
|
+
0
|
|
751
|
+
);
|
|
752
|
+
const batonSavedBeforeCompact = Math.max(
|
|
753
|
+
0,
|
|
754
|
+
Number(baton?.metricsSnapshot?.savedTokensBeforeCompact || 0)
|
|
755
|
+
);
|
|
756
|
+
const savedTokens = Math.max(
|
|
757
|
+
0,
|
|
758
|
+
Number(event.tokensSaved ?? batonSavedBeforeCompact + summedFlushedTokens)
|
|
759
|
+
);
|
|
760
|
+
const savedUSD = Math.max(
|
|
761
|
+
0,
|
|
762
|
+
Number(
|
|
763
|
+
event.usdSaved ??
|
|
764
|
+
(Number(baton?.metricsSnapshot?.savedUSDBeforeCompact || 0) +
|
|
765
|
+
Number(flushResult.totalAvoidedPenaltyUSD || 0))
|
|
766
|
+
)
|
|
767
|
+
);
|
|
768
|
+
|
|
769
|
+
let ledgerEntry = null;
|
|
770
|
+
if (savedTokens > 0 || savedUSD > 0 || flushResult.flushedCount > 0) {
|
|
771
|
+
const rec = recordSavingsReceipt(
|
|
772
|
+
{
|
|
773
|
+
timestamp: nowMs,
|
|
774
|
+
sessionId,
|
|
775
|
+
category: flushResult.flushedCount > 0 ? 'POST_COMPACT_MUTATION_RELEASE' : 'COMPACT_STATE_BATON',
|
|
776
|
+
modelId: baton?.modelId || event.modelId || 'claude-sonnet-5-5',
|
|
777
|
+
savedTokens,
|
|
778
|
+
savedUSD,
|
|
779
|
+
detail: `Flushed ${flushResult.flushedCount} deferred mutation(s) on fresh post-compaction prefix`
|
|
780
|
+
},
|
|
781
|
+
ioOpts
|
|
782
|
+
);
|
|
783
|
+
ledgerEntry = rec.entry;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
return {
|
|
787
|
+
ok: true,
|
|
788
|
+
deduplicated: false,
|
|
789
|
+
sessionId,
|
|
790
|
+
compactionId: cycleId,
|
|
791
|
+
flushedCount: flushResult.flushedCount,
|
|
792
|
+
appliedMutations: flushResult.appliedMutations,
|
|
793
|
+
totalAvoidedPenaltyUSD: flushResult.totalAvoidedPenaltyUSD,
|
|
794
|
+
ledgerEntry
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
export default {
|
|
799
|
+
MAX_BATON_TOKEN_BUDGET,
|
|
800
|
+
getStateBatonFilePath,
|
|
801
|
+
buildDurableStateBaton,
|
|
802
|
+
formatBatonAdditionalContext,
|
|
803
|
+
formatUtcHandoffTimestamp,
|
|
804
|
+
parseHandoffFilenameTimestampMs,
|
|
805
|
+
renderPortableHandoffMarkdown,
|
|
806
|
+
parsePortableHandoffMarkdown,
|
|
807
|
+
handlePreCompactBatonFlush,
|
|
808
|
+
handleSessionStartHydration,
|
|
809
|
+
handlePostCompactFlush
|
|
810
|
+
};
|