ctxtop 0.0.0-stage → 4.1.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 +166 -0
- package/LICENSE +27 -0
- package/README.md +350 -2
- 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 +175 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1799 -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 +133 -0
- package/config/modelCatalog.json +785 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +577 -0
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +311 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +366 -0
- package/hooks/handlers/pre-model-switch.mjs +1048 -0
- package/hooks/handlers/pre-tool-use.mjs +632 -0
- package/hooks/handlers/stop-gate.mjs +526 -0
- package/hooks/handlers/user-prompt-submit.mjs +367 -0
- package/hooks/hooks.json +131 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +25 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +726 -0
- package/hooks/session_start.mjs +24 -0
- package/hooks/stop.mjs +23 -0
- package/hooks.json +56 -0
- package/package.json +110 -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 +2038 -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 +50 -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 +109 -0
- package/src/adapters/claude-code/index.mjs +194 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +888 -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 +704 -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/bucket_b_runtime.mjs +1200 -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 +1987 -0
- package/src/core/detectors_det01_to_16.mjs +1523 -0
- package/src/core/doc_indexer.mjs +338 -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 +1084 -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 +1997 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +311 -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/rsl_clash_auditor.mjs +423 -0
- package/src/core/rsl_distiller.mjs +372 -0
- package/src/core/rsl_ledger.mjs +969 -0
- package/src/core/rsl_triage.mjs +909 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_auditor.mjs +658 -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/shield_manager.mjs +1417 -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 +1547 -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/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1055 -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 +888 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +433 -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/bucketBAlphaBeta.mjs +860 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +27 -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 +1156 -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 +1237 -0
- package/src/core-isomorphic/ui/modViews.mjs +1504 -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/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +295 -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 +342 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +12 -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 +376 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +611 -0
- package/src/hooks/pre_invocation.mjs +1725 -0
- package/src/hooks/session_start.mjs +199 -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/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +12397 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/utils/modelSwitchTelemetry.mjs
|
|
3
|
+
* Local-only privacy-sanitized telemetry counters for `PreModelSwitch` ("ask" / "deny" / "allow")
|
|
4
|
+
* vs `PostModelSwitch` events, plus sanitized hook stdin captures (`cache_ttl`, `prompt_cache_warm`).
|
|
5
|
+
*
|
|
6
|
+
* Privacy Invariant:
|
|
7
|
+
* - Zero file paths, zero OS usernames, zero repository directory names, and zero raw session IDs
|
|
8
|
+
* are persisted. Session identifiers are one-way SHA-256 hashed (`sess_<12hex>`).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { fs, path, os, crypto, readJsonSafe, writeJsonAtomic } from './nodeIo.mjs';
|
|
12
|
+
|
|
13
|
+
export const MODEL_SWITCH_TELEMETRY_SCHEMA_VERSION = 1;
|
|
14
|
+
const MAX_RECENT_CAPTURES = 50;
|
|
15
|
+
const MAX_PENDING_ASKS = 64;
|
|
16
|
+
|
|
17
|
+
const SAFE_TOKEN_RX = /^[a-z0-9._:/-]{1,64}$/i;
|
|
18
|
+
const PATH_LIKE_RX = /([\\/]{1,2}[a-z0-9_.-]+|[a-z]:[\\/]|users[\\/]|home[\\/])/i;
|
|
19
|
+
|
|
20
|
+
function sanitizeShortToken(value, maxLen = 64) {
|
|
21
|
+
if (typeof value !== 'string') return null;
|
|
22
|
+
const trimmed = value.trim();
|
|
23
|
+
if (!trimmed || trimmed.length > maxLen) return null;
|
|
24
|
+
if (PATH_LIKE_RX.test(trimmed)) return null;
|
|
25
|
+
if (!SAFE_TOKEN_RX.test(trimmed)) return null;
|
|
26
|
+
return trimmed;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function sanitizeFiniteNumber(value) {
|
|
30
|
+
const num = Number(value);
|
|
31
|
+
return Number.isFinite(num) ? num : null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Hash an arbitrary session identifier into a non-reversible 12-hex tag (`sess_<12hex>`).
|
|
36
|
+
* @param {string|null|undefined} sessionId
|
|
37
|
+
* @returns {string|null}
|
|
38
|
+
*/
|
|
39
|
+
export function hashSessionIdentifier(sessionId) {
|
|
40
|
+
if (typeof sessionId !== 'string' || !sessionId.trim()) return null;
|
|
41
|
+
const digest = crypto.createHash('sha256').update(sessionId.trim()).digest('hex').slice(0, 12);
|
|
42
|
+
return `sess_${digest}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Resolve the local telemetry JSON path under `~/.attention-horizon/cache/`.
|
|
47
|
+
* @param {object} [options={}]
|
|
48
|
+
* @returns {string}
|
|
49
|
+
*/
|
|
50
|
+
export function resolveModelSwitchTelemetryPath(options = {}) {
|
|
51
|
+
if (typeof options.telemetryPath === 'string' && options.telemetryPath.trim()) {
|
|
52
|
+
return options.telemetryPath.trim();
|
|
53
|
+
}
|
|
54
|
+
const envPath = globalThis.process?.env?.AH_MODEL_SWITCH_TELEMETRY_PATH;
|
|
55
|
+
if (typeof envPath === 'string' && envPath.trim()) {
|
|
56
|
+
return envPath.trim();
|
|
57
|
+
}
|
|
58
|
+
const homeDir = options.homeDir || os.homedir();
|
|
59
|
+
return path.join(homeDir, '.attention-horizon', 'cache', 'model_switch_telemetry.json');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Produce a strictly allowlisted, path-free, username-free summary of a
|
|
64
|
+
* `PreModelSwitch` or `PostModelSwitch` stdin payload.
|
|
65
|
+
*
|
|
66
|
+
* @param {object} [rawEvent={}]
|
|
67
|
+
* @param {'PreModelSwitch'|'PostModelSwitch'} [hookEventName='PreModelSwitch']
|
|
68
|
+
* @returns {object}
|
|
69
|
+
*/
|
|
70
|
+
export function sanitizeModelSwitchStdin(rawEvent = {}, hookEventName = 'PreModelSwitch') {
|
|
71
|
+
const ev = rawEvent && typeof rawEvent === 'object' ? rawEvent : {};
|
|
72
|
+
const sessionHash = hashSessionIdentifier(ev.session_id || ev.sessionId || null);
|
|
73
|
+
|
|
74
|
+
const rawWarm =
|
|
75
|
+
ev.prompt_cache_warm !== undefined
|
|
76
|
+
? ev.prompt_cache_warm
|
|
77
|
+
: ev.cache_warm !== undefined
|
|
78
|
+
? ev.cache_warm
|
|
79
|
+
: ev.promptCacheWarm;
|
|
80
|
+
const promptCacheWarm =
|
|
81
|
+
rawWarm === undefined || rawWarm === null ? null : Boolean(rawWarm);
|
|
82
|
+
|
|
83
|
+
const rawTtl = ev.cache_ttl ?? ev.cacheTtl ?? ev.cache_ttl_tier ?? ev.cacheTtlTier ?? null;
|
|
84
|
+
const cacheTtl = sanitizeShortToken(rawTtl ? String(rawTtl) : null, 16);
|
|
85
|
+
|
|
86
|
+
const rawSource = ev.source ?? ev.trigger ?? null;
|
|
87
|
+
const source = sanitizeShortToken(rawSource ? String(rawSource) : null, 32) || 'unknown';
|
|
88
|
+
|
|
89
|
+
const fromModel = sanitizeShortToken(
|
|
90
|
+
ev.from_model ?? ev.fromModel ?? ev.current_model ?? ev.currentModel ?? null,
|
|
91
|
+
64
|
|
92
|
+
);
|
|
93
|
+
const toModel = sanitizeShortToken(
|
|
94
|
+
ev.to_model ?? ev.toModel ?? ev.target_model ?? ev.targetModel ?? ev.requested_model ?? null,
|
|
95
|
+
64
|
|
96
|
+
);
|
|
97
|
+
const requestedModel = sanitizeShortToken(ev.requested_model ?? ev.requestedModel ?? null, 64);
|
|
98
|
+
|
|
99
|
+
const observedKeys = Object.keys(ev)
|
|
100
|
+
.filter((k) => /^[a-z0-9_]{1,48}$/i.test(k))
|
|
101
|
+
.sort();
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
hookEventName: hookEventName === 'PostModelSwitch' ? 'PostModelSwitch' : 'PreModelSwitch',
|
|
105
|
+
recordedAtIso: new Date().toISOString(),
|
|
106
|
+
sessionHash,
|
|
107
|
+
source,
|
|
108
|
+
fromModel,
|
|
109
|
+
toModel,
|
|
110
|
+
requestedModel,
|
|
111
|
+
cacheTtl,
|
|
112
|
+
promptCacheWarm,
|
|
113
|
+
contextTokens: sanitizeFiniteNumber(ev.context_tokens ?? ev.contextTokens),
|
|
114
|
+
cachedTokens: sanitizeFiniteNumber(
|
|
115
|
+
ev.cached_tokens ?? ev.cachedTokens ?? ev.cache_read_input_tokens
|
|
116
|
+
),
|
|
117
|
+
estimatedCacheWriteUsd: sanitizeFiniteNumber(
|
|
118
|
+
ev.estimated_cache_write_usd ?? ev.estimatedCacheWriteUsd
|
|
119
|
+
),
|
|
120
|
+
hasPricingPayload: Boolean(ev.pricing && typeof ev.pricing === 'object'),
|
|
121
|
+
observedKeys
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function createEmptyTelemetryState() {
|
|
126
|
+
return {
|
|
127
|
+
schemaVersion: MODEL_SWITCH_TELEMETRY_SCHEMA_VERSION,
|
|
128
|
+
updatedAtIso: null,
|
|
129
|
+
counts: {
|
|
130
|
+
preModelSwitchTotal: 0,
|
|
131
|
+
preModelSwitchAsk: 0,
|
|
132
|
+
preModelSwitchDeny: 0,
|
|
133
|
+
preModelSwitchAllow: 0,
|
|
134
|
+
postModelSwitchTotal: 0,
|
|
135
|
+
postModelSwitchFromAsk: 0
|
|
136
|
+
},
|
|
137
|
+
metrics: {
|
|
138
|
+
askAcceptanceRate: null,
|
|
139
|
+
rawPostToAskRatio: null,
|
|
140
|
+
pendingOrDeclinedAsks: 0,
|
|
141
|
+
sourceBreakdown: {}
|
|
142
|
+
},
|
|
143
|
+
pendingAsks: [],
|
|
144
|
+
recentSanitizedCaptures: []
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function normalizeTelemetryState(raw) {
|
|
149
|
+
const base = createEmptyTelemetryState();
|
|
150
|
+
if (!raw || typeof raw !== 'object') return base;
|
|
151
|
+
const counts = {
|
|
152
|
+
preModelSwitchTotal: Math.max(0, Number(raw.counts?.preModelSwitchTotal || 0)),
|
|
153
|
+
preModelSwitchAsk: Math.max(0, Number(raw.counts?.preModelSwitchAsk || 0)),
|
|
154
|
+
preModelSwitchDeny: Math.max(0, Number(raw.counts?.preModelSwitchDeny || 0)),
|
|
155
|
+
preModelSwitchAllow: Math.max(0, Number(raw.counts?.preModelSwitchAllow || 0)),
|
|
156
|
+
postModelSwitchTotal: Math.max(0, Number(raw.counts?.postModelSwitchTotal || 0)),
|
|
157
|
+
postModelSwitchFromAsk: Math.max(0, Number(raw.counts?.postModelSwitchFromAsk || 0))
|
|
158
|
+
};
|
|
159
|
+
const sourceBreakdown =
|
|
160
|
+
raw.metrics?.sourceBreakdown && typeof raw.metrics.sourceBreakdown === 'object'
|
|
161
|
+
? { ...raw.metrics.sourceBreakdown }
|
|
162
|
+
: {};
|
|
163
|
+
const pendingAsks = Array.isArray(raw.pendingAsks)
|
|
164
|
+
? raw.pendingAsks.slice(-MAX_PENDING_ASKS)
|
|
165
|
+
: [];
|
|
166
|
+
const recentSanitizedCaptures = Array.isArray(raw.recentSanitizedCaptures)
|
|
167
|
+
? raw.recentSanitizedCaptures.slice(-MAX_RECENT_CAPTURES)
|
|
168
|
+
: [];
|
|
169
|
+
return recomputeTelemetryMetrics({
|
|
170
|
+
schemaVersion: MODEL_SWITCH_TELEMETRY_SCHEMA_VERSION,
|
|
171
|
+
updatedAtIso: typeof raw.updatedAtIso === 'string' ? raw.updatedAtIso : null,
|
|
172
|
+
counts,
|
|
173
|
+
metrics: {
|
|
174
|
+
askAcceptanceRate: null,
|
|
175
|
+
rawPostToAskRatio: null,
|
|
176
|
+
pendingOrDeclinedAsks: 0,
|
|
177
|
+
sourceBreakdown
|
|
178
|
+
},
|
|
179
|
+
pendingAsks,
|
|
180
|
+
recentSanitizedCaptures
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function recomputeTelemetryMetrics(state) {
|
|
185
|
+
const { counts } = state;
|
|
186
|
+
const askCount = counts.preModelSwitchAsk;
|
|
187
|
+
const matchedPost = Math.min(askCount, counts.postModelSwitchFromAsk);
|
|
188
|
+
counts.postModelSwitchFromAsk = matchedPost;
|
|
189
|
+
|
|
190
|
+
state.metrics.askAcceptanceRate =
|
|
191
|
+
askCount > 0 ? Number((matchedPost / askCount).toFixed(4)) : null;
|
|
192
|
+
state.metrics.rawPostToAskRatio =
|
|
193
|
+
askCount > 0 ? Number((counts.postModelSwitchTotal / askCount).toFixed(4)) : null;
|
|
194
|
+
state.metrics.pendingOrDeclinedAsks = Math.max(0, askCount - matchedPost);
|
|
195
|
+
return state;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function writeTelemetryStateAtomic(targetPath, state) {
|
|
199
|
+
const dir = path.dirname(targetPath);
|
|
200
|
+
if (dir && dir !== '.' && !fs.existsSync(dir)) {
|
|
201
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
202
|
+
}
|
|
203
|
+
writeJsonAtomic(targetPath, state);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Read persisted local-only `PreModelSwitch` vs `PostModelSwitch` telemetry.
|
|
208
|
+
* @param {object} [options={}]
|
|
209
|
+
*/
|
|
210
|
+
export function readModelSwitchTelemetry(options = {}) {
|
|
211
|
+
const targetPath = resolveModelSwitchTelemetryPath(options);
|
|
212
|
+
const raw = readJsonSafe(targetPath, null);
|
|
213
|
+
return {
|
|
214
|
+
telemetryPath: targetPath,
|
|
215
|
+
exists: Boolean(raw),
|
|
216
|
+
state: normalizeTelemetryState(raw)
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Record a sanitized `PreModelSwitch` decision and stdin capture locally.
|
|
222
|
+
* @param {object} [rawEvent={}]
|
|
223
|
+
* @param {string} [decision='allow']
|
|
224
|
+
* @param {object} [options={}]
|
|
225
|
+
*/
|
|
226
|
+
export function recordPreModelSwitchEvent(rawEvent = {}, decision = 'allow', options = {}) {
|
|
227
|
+
const targetPath = resolveModelSwitchTelemetryPath(options);
|
|
228
|
+
const state = normalizeTelemetryState(readJsonSafe(targetPath, null));
|
|
229
|
+
const capture = sanitizeModelSwitchStdin(rawEvent, 'PreModelSwitch');
|
|
230
|
+
const normDecision = String(decision || 'allow').toLowerCase();
|
|
231
|
+
|
|
232
|
+
state.counts.preModelSwitchTotal += 1;
|
|
233
|
+
if (normDecision === 'ask') {
|
|
234
|
+
state.counts.preModelSwitchAsk += 1;
|
|
235
|
+
state.pendingAsks.push({
|
|
236
|
+
sessionHash: capture.sessionHash,
|
|
237
|
+
toModel: capture.toModel,
|
|
238
|
+
source: capture.source,
|
|
239
|
+
recordedAtIso: capture.recordedAtIso
|
|
240
|
+
});
|
|
241
|
+
if (state.pendingAsks.length > MAX_PENDING_ASKS) {
|
|
242
|
+
state.pendingAsks = state.pendingAsks.slice(-MAX_PENDING_ASKS);
|
|
243
|
+
}
|
|
244
|
+
} else if (normDecision === 'deny') {
|
|
245
|
+
state.counts.preModelSwitchDeny += 1;
|
|
246
|
+
} else {
|
|
247
|
+
state.counts.preModelSwitchAllow += 1;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const sourceKey = capture.source || 'unknown';
|
|
251
|
+
state.metrics.sourceBreakdown[sourceKey] =
|
|
252
|
+
(Number(state.metrics.sourceBreakdown[sourceKey]) || 0) + 1;
|
|
253
|
+
|
|
254
|
+
state.recentSanitizedCaptures.push({
|
|
255
|
+
...capture,
|
|
256
|
+
decision: normDecision
|
|
257
|
+
});
|
|
258
|
+
if (state.recentSanitizedCaptures.length > MAX_RECENT_CAPTURES) {
|
|
259
|
+
state.recentSanitizedCaptures = state.recentSanitizedCaptures.slice(-MAX_RECENT_CAPTURES);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
state.updatedAtIso = capture.recordedAtIso;
|
|
263
|
+
recomputeTelemetryMetrics(state);
|
|
264
|
+
writeTelemetryStateAtomic(targetPath, state);
|
|
265
|
+
return { telemetryPath: targetPath, state, capture };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Record a sanitized `PostModelSwitch` completion event and reconcile against pending asks.
|
|
270
|
+
* @param {object} [rawEvent={}]
|
|
271
|
+
* @param {object} [options={}]
|
|
272
|
+
*/
|
|
273
|
+
export function recordPostModelSwitchEvent(rawEvent = {}, options = {}) {
|
|
274
|
+
const targetPath = resolveModelSwitchTelemetryPath(options);
|
|
275
|
+
const state = normalizeTelemetryState(readJsonSafe(targetPath, null));
|
|
276
|
+
const capture = sanitizeModelSwitchStdin(rawEvent, 'PostModelSwitch');
|
|
277
|
+
|
|
278
|
+
state.counts.postModelSwitchTotal += 1;
|
|
279
|
+
|
|
280
|
+
// Match the earliest pending `"ask"` for the same hashed session + target model
|
|
281
|
+
const matchIdx = state.pendingAsks.findIndex((pending) => {
|
|
282
|
+
const sameSession =
|
|
283
|
+
pending.sessionHash === null ||
|
|
284
|
+
capture.sessionHash === null ||
|
|
285
|
+
pending.sessionHash === capture.sessionHash;
|
|
286
|
+
const sameTarget =
|
|
287
|
+
pending.toModel === null || capture.toModel === null || pending.toModel === capture.toModel;
|
|
288
|
+
return sameSession && sameTarget;
|
|
289
|
+
});
|
|
290
|
+
const matchedPendingAsk = matchIdx >= 0;
|
|
291
|
+
if (matchedPendingAsk) {
|
|
292
|
+
state.pendingAsks.splice(matchIdx, 1);
|
|
293
|
+
state.counts.postModelSwitchFromAsk += 1;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
state.recentSanitizedCaptures.push({
|
|
297
|
+
...capture,
|
|
298
|
+
matchedPendingAsk
|
|
299
|
+
});
|
|
300
|
+
if (state.recentSanitizedCaptures.length > MAX_RECENT_CAPTURES) {
|
|
301
|
+
state.recentSanitizedCaptures = state.recentSanitizedCaptures.slice(-MAX_RECENT_CAPTURES);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
state.updatedAtIso = capture.recordedAtIso;
|
|
305
|
+
recomputeTelemetryMetrics(state);
|
|
306
|
+
writeTelemetryStateAtomic(targetPath, state);
|
|
307
|
+
return { telemetryPath: targetPath, state, capture, matchedPendingAsk };
|
|
308
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/utils/nodeIo.mjs
|
|
3
|
+
* Tier-2 Spawned Node.js CLI I/O Adapter (`ISS-032`).
|
|
4
|
+
*
|
|
5
|
+
* Architectural Boundary:
|
|
6
|
+
* - Imported ONLY by Tier-2 Node CLI entrypoints (`bin/*`, `hooks/handlers/*`,
|
|
7
|
+
* `src/guards/losslessPostSanitizer.mjs`, `src/diagnostics/bugReportGenerator.mjs`, `scripts/*`).
|
|
8
|
+
* - NEVER imported by `hooks/register.js` or any module in `register.js`'s transitive Mod graph!
|
|
9
|
+
* - Uses standard ESM `node:*` imports supported across all Node.js >= 20.0.0 (`20.0.0`..`24.x`),
|
|
10
|
+
* completely eliminating `process.getBuiltinModule` smuggling.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import * as fs from 'node:fs';
|
|
14
|
+
import * as path from 'node:path';
|
|
15
|
+
import * as os from 'node:os';
|
|
16
|
+
import * as crypto from 'node:crypto';
|
|
17
|
+
import * as url from 'node:url';
|
|
18
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
19
|
+
import {
|
|
20
|
+
registerNodeIo,
|
|
21
|
+
writeTextAtomic,
|
|
22
|
+
writeJsonAtomic,
|
|
23
|
+
readJsonSafe,
|
|
24
|
+
readTextSafe,
|
|
25
|
+
appendJsonlSafe,
|
|
26
|
+
getDiagnosticsFilePath,
|
|
27
|
+
recordRuntimeDiagnostic,
|
|
28
|
+
readRuntimeDiagnostics
|
|
29
|
+
} from '../core-isomorphic/utils/runtime.mjs';
|
|
30
|
+
|
|
31
|
+
export const NODE_IO_PROVIDER = Object.freeze({
|
|
32
|
+
fs,
|
|
33
|
+
path,
|
|
34
|
+
os,
|
|
35
|
+
crypto,
|
|
36
|
+
url: Object.freeze({ fileURLToPath, pathToFileURL }),
|
|
37
|
+
cwd: () => globalThis.process?.cwd?.() || '.'
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// Automatically activate disk I/O for Tier-2 Node CLI processes on import
|
|
41
|
+
registerNodeIo(NODE_IO_PROVIDER);
|
|
42
|
+
|
|
43
|
+
export {
|
|
44
|
+
fs,
|
|
45
|
+
path,
|
|
46
|
+
os,
|
|
47
|
+
crypto,
|
|
48
|
+
url,
|
|
49
|
+
fileURLToPath,
|
|
50
|
+
pathToFileURL,
|
|
51
|
+
writeTextAtomic,
|
|
52
|
+
writeJsonAtomic,
|
|
53
|
+
readJsonSafe,
|
|
54
|
+
readTextSafe,
|
|
55
|
+
appendJsonlSafe,
|
|
56
|
+
getDiagnosticsFilePath,
|
|
57
|
+
recordRuntimeDiagnostic,
|
|
58
|
+
readRuntimeDiagnostics
|
|
59
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from '../core-isomorphic/utils/runtime.mjs';
|