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,231 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
5
|
+
import { canonicalizePath } from './path_canonicalizer.mjs';
|
|
6
|
+
|
|
7
|
+
function getHomeDir() {
|
|
8
|
+
return process.env.USERPROFILE || process.env.HOME || os.homedir();
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Resolves the 4-tier log file path for a given conversation.
|
|
13
|
+
*/
|
|
14
|
+
export function resolveTranscriptPath(conversationId, brainDirOverride = null) {
|
|
15
|
+
const home = getHomeDir();
|
|
16
|
+
const brainDir = brainDirOverride || path.join(home, '.gemini', 'antigravity', 'brain', conversationId);
|
|
17
|
+
|
|
18
|
+
// Tier 1: transcript_full.jsonl
|
|
19
|
+
const tier1Path = path.join(brainDir, '.system_generated', 'logs', 'transcript_full.jsonl');
|
|
20
|
+
if (fs.existsSync(tier1Path)) {
|
|
21
|
+
return { path: tier1Path, tier: 1, brainDir };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Tier 2: chunks/transcript_full/*.jsonl
|
|
25
|
+
const tier2Dir = path.join(brainDir, '.system_generated', 'logs', 'chunks', 'transcript_full');
|
|
26
|
+
if (fs.existsSync(tier2Dir)) {
|
|
27
|
+
try {
|
|
28
|
+
const files = fs.readdirSync(tier2Dir)
|
|
29
|
+
.filter(f => f.endsWith('.jsonl'))
|
|
30
|
+
.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
|
|
31
|
+
if (files.length > 0) {
|
|
32
|
+
return { path: path.join(tier2Dir, files[files.length - 1]), tier: 2, brainDir, chunkFiles: files.map(f => path.join(tier2Dir, f)) };
|
|
33
|
+
}
|
|
34
|
+
} catch {}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Tier 3: transcript.jsonl
|
|
38
|
+
const tier3Path = path.join(brainDir, '.system_generated', 'logs', 'transcript.jsonl');
|
|
39
|
+
if (fs.existsSync(tier3Path)) {
|
|
40
|
+
return { path: tier3Path, tier: 3, brainDir };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Tier 4: SQLite DB fallback
|
|
44
|
+
const tier4Path = path.join(home, '.gemini', 'antigravity', 'conversations', `${conversationId}.db`);
|
|
45
|
+
if (fs.existsSync(tier4Path)) {
|
|
46
|
+
return { path: tier4Path, tier: 4, brainDir };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return { path: null, tier: 0, brainDir };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Checks for '@deprecated' tag within the first 30 lines of text.
|
|
54
|
+
*/
|
|
55
|
+
export function checkDeprecatedInHeader(text) {
|
|
56
|
+
if (!text || typeof text !== 'string') return false;
|
|
57
|
+
const lines = text.slice(0, 4000).split(/\r?\n/).slice(0, 30);
|
|
58
|
+
return lines.some(line => /@deprecated/i.test(line));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Normalizes raw JSONL step objects into lightweight StepEvents.
|
|
63
|
+
*/
|
|
64
|
+
export function normalizeStepEntry(entry, index, brainDir = null) {
|
|
65
|
+
const stepIndex = typeof entry.step_index === 'number' ? entry.step_index : index;
|
|
66
|
+
const timestampMs = entry.created_at ? new Date(entry.created_at).getTime() : Date.now();
|
|
67
|
+
|
|
68
|
+
let role = 'model';
|
|
69
|
+
if (entry.source === 'USER_EXPLICIT' || entry.type === 'USER_INPUT') {
|
|
70
|
+
role = 'user';
|
|
71
|
+
} else if (entry.source === 'SYSTEM' || entry.type === 'ANCHOR' || entry.type === 'SCHEMA') {
|
|
72
|
+
role = 'system';
|
|
73
|
+
} else if (entry.type === 'TOOL_RESULT' || entry.tool_results) {
|
|
74
|
+
role = 'tool';
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
let toolName = null;
|
|
78
|
+
let targetPath = null;
|
|
79
|
+
let exitCode = null;
|
|
80
|
+
let textSample = '';
|
|
81
|
+
let fullText = '';
|
|
82
|
+
|
|
83
|
+
// Extract from tool_calls
|
|
84
|
+
if (Array.isArray(entry.tool_calls) && entry.tool_calls.length > 0) {
|
|
85
|
+
const call = entry.tool_calls[0];
|
|
86
|
+
toolName = call.name || call.tool || null;
|
|
87
|
+
const args = call.args || call.parameters || call.Arguments || {};
|
|
88
|
+
const rawPath = args.Path || args.path || args.target_file || args.file_path || args.targetPath;
|
|
89
|
+
if (rawPath) targetPath = canonicalizePath(String(rawPath));
|
|
90
|
+
if (toolName === 'run_command' && args.CommandLine) {
|
|
91
|
+
textSample = String(args.CommandLine);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Extract from tool output or content
|
|
96
|
+
if (entry.content) {
|
|
97
|
+
if (typeof entry.content === 'string') {
|
|
98
|
+
fullText = entry.content;
|
|
99
|
+
} else if (typeof entry.content === 'object') {
|
|
100
|
+
fullText = JSON.stringify(entry.content);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (entry.thinking && typeof entry.thinking === 'string') {
|
|
105
|
+
fullText += ' ' + entry.thinking;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Check hydration if transcript.jsonl had truncated_fields
|
|
109
|
+
if (brainDir && Array.isArray(entry.truncated_fields) && entry.truncated_fields.length > 0) {
|
|
110
|
+
const stepOutputPath = path.join(brainDir, 'steps', String(stepIndex), 'output.txt');
|
|
111
|
+
const altOutputPath = path.join(brainDir, '.system_generated', 'steps', String(stepIndex), 'output.txt');
|
|
112
|
+
try {
|
|
113
|
+
if (fs.existsSync(stepOutputPath)) {
|
|
114
|
+
fullText = fs.readFileSync(stepOutputPath, 'utf8');
|
|
115
|
+
} else if (fs.existsSync(altOutputPath)) {
|
|
116
|
+
fullText = fs.readFileSync(altOutputPath, 'utf8');
|
|
117
|
+
}
|
|
118
|
+
} catch {}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (!textSample && fullText) {
|
|
122
|
+
textSample = fullText.slice(0, 512);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Determine exitCode if command or tool error
|
|
126
|
+
if (entry.status === 'ERROR' || entry.exit_code === 1 || entry.exitCode === 1) {
|
|
127
|
+
exitCode = 1;
|
|
128
|
+
} else if (entry.status === 'DONE' && (entry.exit_code === 0 || entry.exitCode === 0)) {
|
|
129
|
+
exitCode = 0;
|
|
130
|
+
} else if (typeof entry.exitCode === 'number') {
|
|
131
|
+
exitCode = entry.exitCode;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const tokenEstimate = entry.token_count || Math.max(1, Math.ceil(fullText.length / 4));
|
|
135
|
+
const isDeprecatedContent = checkDeprecatedInHeader(fullText);
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
stepIndex,
|
|
139
|
+
timestampMs,
|
|
140
|
+
role,
|
|
141
|
+
type: entry.type || (role === 'user' ? 'USER_INPUT' : 'PLANNER_RESPONSE'),
|
|
142
|
+
toolName,
|
|
143
|
+
targetPath,
|
|
144
|
+
exitCode,
|
|
145
|
+
tokenEstimate,
|
|
146
|
+
isDeprecatedContent,
|
|
147
|
+
rawTextSample: textSample
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Incrementally reads transcript logs using byte-offset cursor across all 4 tiers.
|
|
153
|
+
*/
|
|
154
|
+
export function resolveAndReadTranscriptIncremental(conversationId, cursorState = {}, options = {}) {
|
|
155
|
+
const { brainDirOverride = null } = options;
|
|
156
|
+
const resolution = resolveTranscriptPath(conversationId, brainDirOverride);
|
|
157
|
+
|
|
158
|
+
const state = {
|
|
159
|
+
filePath: cursorState.filePath || null,
|
|
160
|
+
byteOffset: cursorState.byteOffset || 0,
|
|
161
|
+
parsedEvents: Array.isArray(cursorState.parsedEvents) ? [...cursorState.parsedEvents] : [],
|
|
162
|
+
tier: resolution.tier
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
if (!resolution.path) {
|
|
166
|
+
return state;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const currentPath = resolution.path;
|
|
170
|
+
|
|
171
|
+
// Handle tier 4 (db) or non-jsonl paths
|
|
172
|
+
if (resolution.tier === 4 || !currentPath.endsWith('.jsonl')) {
|
|
173
|
+
state.filePath = currentPath;
|
|
174
|
+
return state;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// If path changed or log rotated, reset offset
|
|
178
|
+
let stat;
|
|
179
|
+
try {
|
|
180
|
+
stat = fs.statSync(currentPath);
|
|
181
|
+
} catch {
|
|
182
|
+
return state;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (state.filePath !== currentPath || stat.size < state.byteOffset) {
|
|
186
|
+
state.filePath = currentPath;
|
|
187
|
+
state.byteOffset = 0;
|
|
188
|
+
state.parsedEvents = [];
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const bytesToRead = stat.size - state.byteOffset;
|
|
192
|
+
if (bytesToRead <= 0) {
|
|
193
|
+
return state;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const CHUNK_BYTES = 64 * 1024;
|
|
197
|
+
const fd = fs.openSync(currentPath, 'r');
|
|
198
|
+
try {
|
|
199
|
+
const chunkBuf = Buffer.alloc(Math.min(CHUNK_BYTES, Math.max(1, bytesToRead)));
|
|
200
|
+
const decoder = new StringDecoder('utf8');
|
|
201
|
+
let rawChunk = '';
|
|
202
|
+
let readPos = state.byteOffset;
|
|
203
|
+
let remaining = bytesToRead;
|
|
204
|
+
while (remaining > 0) {
|
|
205
|
+
const toRead = Math.min(chunkBuf.length, remaining);
|
|
206
|
+
const bytesRead = fs.readSync(fd, chunkBuf, 0, toRead, readPos);
|
|
207
|
+
if (bytesRead <= 0) break;
|
|
208
|
+
rawChunk += decoder.write(chunkBuf.subarray(0, bytesRead));
|
|
209
|
+
readPos += bytesRead;
|
|
210
|
+
remaining -= bytesRead;
|
|
211
|
+
}
|
|
212
|
+
rawChunk += decoder.end();
|
|
213
|
+
state.byteOffset = readPos;
|
|
214
|
+
|
|
215
|
+
const lines = rawChunk.split(/\r?\n/).filter(l => l.trim().length > 0);
|
|
216
|
+
|
|
217
|
+
for (let i = 0; i < lines.length; i++) {
|
|
218
|
+
try {
|
|
219
|
+
const entry = JSON.parse(lines[i]);
|
|
220
|
+
const normalized = normalizeStepEntry(entry, state.parsedEvents.length, resolution.brainDir);
|
|
221
|
+
state.parsedEvents.push(normalized);
|
|
222
|
+
} catch {
|
|
223
|
+
// Skip malformed individual lines
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
} finally {
|
|
227
|
+
fs.closeSync(fd);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return state;
|
|
231
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { getHomeDir } from './paths.mjs';
|
|
4
|
+
import { evaluateDet13EagerMcpAuditor } from './shared/detectors.mjs';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Rank 10 (DET-13): Read-Only Eager MCP Override & Startup Bloat Auditor
|
|
8
|
+
*
|
|
9
|
+
* Antigravity 1.3.3+ already defaults MCP tools to lazy loading.
|
|
10
|
+
* Audits `~/.gemini/config/mcp_config.json` and workspace MCP configs strictly read-only
|
|
11
|
+
* on `SessionStart` for explicit `"eager": true` overrides, unreachable stdio binaries,
|
|
12
|
+
* or eager schema overhead exceeding 15,000 tokens.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
function isExecutableOnPath(cmdName, envPath = process.env.PATH || '') {
|
|
16
|
+
if (!cmdName || typeof cmdName !== 'string') return false;
|
|
17
|
+
const trimmed = cmdName.trim().replace(/^['"]|['"]$/g, () => '');
|
|
18
|
+
if (!trimmed) return false;
|
|
19
|
+
|
|
20
|
+
if (path.isAbsolute(trimmed) || trimmed.startsWith('./') || trimmed.startsWith('../') || trimmed.includes('/') || trimmed.includes('\\')) {
|
|
21
|
+
return fs.existsSync(trimmed);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Builtin standard runtime shims commonly present
|
|
25
|
+
if (/^(node|npx|npm|python|python3|uv|uvx|docker|deno|bun)(\.exe|\.cmd)?$/i.test(trimmed)) {
|
|
26
|
+
const dirs = String(envPath).split(path.delimiter).filter(Boolean);
|
|
27
|
+
const exts = process.platform === 'win32' ? ['', '.exe', '.cmd', '.bat'] : [''];
|
|
28
|
+
for (const dir of dirs) {
|
|
29
|
+
for (const ext of exts) {
|
|
30
|
+
if (fs.existsSync(path.join(dir, trimmed + ext))) return true;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const dirs = String(envPath).split(path.delimiter).filter(Boolean);
|
|
37
|
+
const exts = process.platform === 'win32' ? ['', '.exe', '.cmd', '.bat'] : [''];
|
|
38
|
+
for (const dir of dirs) {
|
|
39
|
+
for (const ext of exts) {
|
|
40
|
+
if (fs.existsSync(path.join(dir, trimmed + ext))) return true;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function parseMcpConfigFileReadOnly(configPath, { workspacePath, envPath } = {}) {
|
|
47
|
+
if (!configPath || !fs.existsSync(configPath)) return [];
|
|
48
|
+
let parsed = null;
|
|
49
|
+
try {
|
|
50
|
+
const fd = fs.openSync(configPath, 'r');
|
|
51
|
+
try {
|
|
52
|
+
const raw = fs.readFileSync(fd, 'utf8');
|
|
53
|
+
parsed = JSON.parse(raw);
|
|
54
|
+
} finally {
|
|
55
|
+
fs.closeSync(fd);
|
|
56
|
+
}
|
|
57
|
+
} catch {
|
|
58
|
+
return [];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (!parsed || typeof parsed !== 'object') return [];
|
|
62
|
+
const serversMap = parsed.mcpServers || parsed.servers || parsed;
|
|
63
|
+
if (!serversMap || typeof serversMap !== 'object' || Array.isArray(serversMap)) return [];
|
|
64
|
+
|
|
65
|
+
const extracted = [];
|
|
66
|
+
for (const [name, cfg] of Object.entries(serversMap)) {
|
|
67
|
+
if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue;
|
|
68
|
+
if (cfg.disabled === true || cfg.enabled === false) continue;
|
|
69
|
+
|
|
70
|
+
const isHttpOrSse = Boolean(cfg.url || cfg.serverUrl || cfg.httpUrl || cfg.transport === 'sse' || cfg.transport === 'http');
|
|
71
|
+
const transport = isHttpOrSse ? 'remote' : 'stdio';
|
|
72
|
+
let commandReachable = true;
|
|
73
|
+
if (transport === 'stdio' && typeof cfg.command === 'string') {
|
|
74
|
+
const rawCmd = cfg.command.trim();
|
|
75
|
+
const resolvedCmd = (rawCmd.startsWith('./') || rawCmd.startsWith('../')) && workspacePath
|
|
76
|
+
? path.resolve(workspacePath, rawCmd)
|
|
77
|
+
: rawCmd;
|
|
78
|
+
commandReachable = isExecutableOnPath(resolvedCmd, envPath);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const eager = cfg.eager === true || cfg.lazy === false || cfg.loadingMode === 'eager';
|
|
82
|
+
const estimatedTokens = Number(
|
|
83
|
+
cfg.estimatedTokens ??
|
|
84
|
+
cfg.schemaTokens ??
|
|
85
|
+
cfg.tokenCount ??
|
|
86
|
+
(Array.isArray(cfg.eagerTools) ? cfg.eagerTools.length * 450 : (eager ? 3200 : 0))
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
extracted.push({
|
|
90
|
+
name,
|
|
91
|
+
sourceFile: configPath,
|
|
92
|
+
transport,
|
|
93
|
+
command: cfg.command || null,
|
|
94
|
+
commandReachable,
|
|
95
|
+
eager,
|
|
96
|
+
estimatedTokens
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return extracted;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function auditWorkspaceAndGlobalMcpConfigs({
|
|
103
|
+
homeDir = getHomeDir(),
|
|
104
|
+
workspacePath = process.cwd(),
|
|
105
|
+
extraServers = [],
|
|
106
|
+
eagerTokenThreshold = 15000,
|
|
107
|
+
envPath = process.env.PATH || ''
|
|
108
|
+
} = {}) {
|
|
109
|
+
const configPaths = [
|
|
110
|
+
path.join(homeDir, '.gemini', 'config', 'mcp_config.json'),
|
|
111
|
+
path.join(workspacePath, '.agents', 'mcp_config.json'),
|
|
112
|
+
path.join(workspacePath, '.mcp.json')
|
|
113
|
+
];
|
|
114
|
+
|
|
115
|
+
const byName = new Map();
|
|
116
|
+
for (const cfgPath of configPaths) {
|
|
117
|
+
const entries = parseMcpConfigFileReadOnly(cfgPath, { workspacePath, envPath });
|
|
118
|
+
for (const srv of entries) {
|
|
119
|
+
byName.set(srv.name, srv);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (Array.isArray(extraServers)) {
|
|
124
|
+
for (const s of extraServers) {
|
|
125
|
+
if (s && typeof s === 'object' && s.name) {
|
|
126
|
+
byName.set(String(s.name), {
|
|
127
|
+
...byName.get(String(s.name)),
|
|
128
|
+
...s
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return evaluateDet13EagerMcpAuditor({
|
|
135
|
+
servers: Array.from(byName.values()),
|
|
136
|
+
eagerTokenThreshold
|
|
137
|
+
});
|
|
138
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core/micro_skills_store.mjs
|
|
3
|
+
* Disk-backed RSI-04 Repo Micro-Skills persistence store for Google Antigravity (`GA_REPO`).
|
|
4
|
+
* Persists `.agents/state/micro_skills.json` atomically after secret/bypass validation.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { atomicWriteFileSync } from './atomic_io.mjs';
|
|
10
|
+
import { redactSecretsPure } from './shared/ipi_sanitizer.mjs';
|
|
11
|
+
import {
|
|
12
|
+
MAX_MICRO_SKILL_BATON_TOKENS,
|
|
13
|
+
MAX_MICRO_SKILL_BATON_CHARS,
|
|
14
|
+
inspectCommandSafetyForMicroSkill,
|
|
15
|
+
canonicalizeMicroSkillCommand,
|
|
16
|
+
createEmptyMicroSkillsRegistry,
|
|
17
|
+
recordShellOutcomeInRegistry,
|
|
18
|
+
evaluateMicroSkillIntercept,
|
|
19
|
+
formatMicroSkillsBatonSnippet
|
|
20
|
+
} from '../core-isomorphic/diagnostics/micro_skills.mjs';
|
|
21
|
+
|
|
22
|
+
export {
|
|
23
|
+
MAX_MICRO_SKILL_BATON_TOKENS,
|
|
24
|
+
MAX_MICRO_SKILL_BATON_CHARS,
|
|
25
|
+
inspectCommandSafetyForMicroSkill,
|
|
26
|
+
canonicalizeMicroSkillCommand,
|
|
27
|
+
createEmptyMicroSkillsRegistry,
|
|
28
|
+
recordShellOutcomeInRegistry,
|
|
29
|
+
evaluateMicroSkillIntercept,
|
|
30
|
+
formatMicroSkillsBatonSnippet
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export function resolveMicroSkillsPath(workspaceDir = process.cwd()) {
|
|
34
|
+
return path.join(workspaceDir, '.agents', 'state', 'micro_skills.json');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function loadMicroSkillsRegistry(workspaceDir = process.cwd()) {
|
|
38
|
+
const filePath = resolveMicroSkillsPath(workspaceDir);
|
|
39
|
+
try {
|
|
40
|
+
if (!fs.existsSync(filePath)) {
|
|
41
|
+
return createEmptyMicroSkillsRegistry();
|
|
42
|
+
}
|
|
43
|
+
const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
44
|
+
if (!parsed || typeof parsed !== 'object') {
|
|
45
|
+
return createEmptyMicroSkillsRegistry();
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
schemaVersion: '1.0.0',
|
|
49
|
+
skills: Array.isArray(parsed.skills) ? parsed.skills : [],
|
|
50
|
+
pendingFailuresBySession:
|
|
51
|
+
parsed.pendingFailuresBySession && typeof parsed.pendingFailuresBySession === 'object'
|
|
52
|
+
? parsed.pendingFailuresBySession
|
|
53
|
+
: {}
|
|
54
|
+
};
|
|
55
|
+
} catch {
|
|
56
|
+
return createEmptyMicroSkillsRegistry();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function saveMicroSkillsRegistry(workspaceDir = process.cwd(), registry = {}) {
|
|
61
|
+
const filePath = resolveMicroSkillsPath(workspaceDir);
|
|
62
|
+
const rawJson = JSON.stringify(registry, null, 2);
|
|
63
|
+
// Defense-in-depth secondary airlock scrub via ipi_sanitizer
|
|
64
|
+
const { sanitized } = redactSecretsPure(rawJson);
|
|
65
|
+
atomicWriteFileSync(filePath, `${sanitized}\n`, { encoding: 'utf8' });
|
|
66
|
+
return filePath;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function recordWorkspaceShellOutcome(workspaceDir = process.cwd(), event = {}) {
|
|
70
|
+
const rawCmd = String(event.command || '');
|
|
71
|
+
// Secondary secret check via redactSecretsPure: if redaction alters the command, reject immediately
|
|
72
|
+
if (rawCmd) {
|
|
73
|
+
const scrubCheck = redactSecretsPure(rawCmd);
|
|
74
|
+
if (scrubCheck.redactedCount > 0 || scrubCheck.sanitized !== rawCmd) {
|
|
75
|
+
return {
|
|
76
|
+
updated: false,
|
|
77
|
+
rejectedReason: 'SECRET_DETECTED',
|
|
78
|
+
promotedSkill: null,
|
|
79
|
+
capturedCandidate: null,
|
|
80
|
+
evictedContradictions: [],
|
|
81
|
+
registry: loadMicroSkillsRegistry(workspaceDir)
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const current = loadMicroSkillsRegistry(workspaceDir);
|
|
86
|
+
const res = recordShellOutcomeInRegistry(current, event);
|
|
87
|
+
if (res.updated) {
|
|
88
|
+
saveMicroSkillsRegistry(workspaceDir, res.registry);
|
|
89
|
+
}
|
|
90
|
+
return res;
|
|
91
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { canonicalizePath } from './paths.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Cross-session "repeat offender" tracking: files that get re-read in many
|
|
7
|
+
* sessions are good `.antigravityignore` / line-range candidates.
|
|
8
|
+
*
|
|
9
|
+
* Storage: `<cacheDir>/offenders.jsonl`, one line per session:
|
|
10
|
+
* {"sid":"...","ts":1730000000000,"files":[{"path":"C:/x/a.js","reads":3}]}
|
|
11
|
+
* Upserts are idempotent per sid; old lines are pruned on every write.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export const OFFENDER_RETENTION = { maxSessions: 20, maxDays: 14 };
|
|
15
|
+
export const CHRONIC_MIN_SESSIONS = 3;
|
|
16
|
+
const FALLBACK_TOKENS_PER_WASTED_READ = 2000;
|
|
17
|
+
|
|
18
|
+
export function offendersFile(cacheDir) {
|
|
19
|
+
return path.join(cacheDir, 'offenders.jsonl');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function readSessions(cacheDir) {
|
|
23
|
+
try {
|
|
24
|
+
return fs.readFileSync(offendersFile(cacheDir), 'utf8')
|
|
25
|
+
.split(/\r?\n/)
|
|
26
|
+
.filter(Boolean)
|
|
27
|
+
.map(l => { try { return JSON.parse(l); } catch { return null; } })
|
|
28
|
+
.filter(e => e && e.sid && Array.isArray(e.files));
|
|
29
|
+
} catch {
|
|
30
|
+
return [];
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function pruneSessions(entries, { maxSessions, maxDays } = OFFENDER_RETENTION, now = Date.now()) {
|
|
35
|
+
const cutoff = now - maxDays * 86400000;
|
|
36
|
+
return entries
|
|
37
|
+
.filter(e => (e.ts || 0) >= cutoff)
|
|
38
|
+
.sort((a, b) => (b.ts || 0) - (a.ts || 0))
|
|
39
|
+
.slice(0, maxSessions);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function sameFiles(a, b) {
|
|
43
|
+
if (!a || a.length !== b.length) return false;
|
|
44
|
+
return a.every((f, i) => f.path === b[i].path && f.reads === b[i].reads && (f.wastedTokens || 0) === (b[i].wastedTokens || 0));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Upserts this session's duplicate-read list. `duplicateFiles` items are
|
|
49
|
+
* `{ path, occurrences, wastedTokens }` (classifier `brainSignals.duplicateReads.topFiles`).
|
|
50
|
+
* Skips the disk write when nothing changed. Returns the pruned entry list.
|
|
51
|
+
*/
|
|
52
|
+
export function recordSession(cacheDir, sessionId, duplicateFiles = [], opts = OFFENDER_RETENTION, now = Date.now()) {
|
|
53
|
+
const files = (duplicateFiles || [])
|
|
54
|
+
.filter(f => f && f.path && (f.occurrences || 0) >= 1)
|
|
55
|
+
.map(f => ({
|
|
56
|
+
path: String(f.path),
|
|
57
|
+
reads: f.occurrences,
|
|
58
|
+
wastedTokens: Number(f.wastedTokens || (Math.max(1, f.occurrences - 1) * FALLBACK_TOKENS_PER_WASTED_READ) || 0)
|
|
59
|
+
}))
|
|
60
|
+
.sort((a, b) => a.path.localeCompare(b.path));
|
|
61
|
+
const entries = readSessions(cacheDir);
|
|
62
|
+
const existing = entries.find(e => e.sid === sessionId);
|
|
63
|
+
if (existing && sameFiles(existing.files, files)) return pruneSessions(entries, opts, now);
|
|
64
|
+
if (!existing && files.length === 0) return pruneSessions(entries, opts, now);
|
|
65
|
+
|
|
66
|
+
const next = pruneSessions([
|
|
67
|
+
...entries.filter(e => e.sid !== sessionId),
|
|
68
|
+
{ sid: sessionId, ts: now, files }
|
|
69
|
+
], opts, now);
|
|
70
|
+
try {
|
|
71
|
+
fs.mkdirSync(cacheDir, { recursive: true });
|
|
72
|
+
const file = offendersFile(cacheDir);
|
|
73
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
74
|
+
fs.writeFileSync(tmp, next.map(e => JSON.stringify(e)).join('\n') + '\n', 'utf8');
|
|
75
|
+
fs.renameSync(tmp, file);
|
|
76
|
+
} catch {}
|
|
77
|
+
return next;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Aggregates entries into `[{ path, sessions, totalReads, totalWastedTokens, windowSessions, bannerText }]`, most chronic first. */
|
|
81
|
+
export function aggregate(entries, opts = OFFENDER_RETENTION, now = Date.now()) {
|
|
82
|
+
const kept = pruneSessions(entries, opts, now);
|
|
83
|
+
const map = new Map();
|
|
84
|
+
for (const e of kept) {
|
|
85
|
+
for (const f of e.files) {
|
|
86
|
+
const key = canonicalizePath(f.path);
|
|
87
|
+
const agg = map.get(key) || { path: f.path, key, sessions: 0, totalReads: 0, totalWastedTokens: 0 };
|
|
88
|
+
agg.sessions += 1;
|
|
89
|
+
agg.totalReads += f.reads || 0;
|
|
90
|
+
agg.totalWastedTokens += Number(f.wastedTokens || (Math.max(1, (f.reads || 2) - 1) * FALLBACK_TOKENS_PER_WASTED_READ) || 0);
|
|
91
|
+
map.set(key, agg);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return [...map.values()]
|
|
95
|
+
.map(a => {
|
|
96
|
+
const wastedK = Math.max(1, Math.round((a.totalWastedTokens || Math.max(1, a.totalReads - a.sessions) * FALLBACK_TOKENS_PER_WASTED_READ) / 1000));
|
|
97
|
+
const baseName = path.basename(String(a.path || 'file'));
|
|
98
|
+
return {
|
|
99
|
+
...a,
|
|
100
|
+
windowSessions: kept.length,
|
|
101
|
+
bannerText: `Across last ${kept.length} sessions, ${baseName} caused ${wastedK}k repeated re-reads`
|
|
102
|
+
};
|
|
103
|
+
})
|
|
104
|
+
.sort((a, b) => b.sessions - a.sessions || b.totalWastedTokens - a.totalWastedTokens || b.totalReads - a.totalReads);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Formats Law 5 quiet factual banner for the top cross-session offender. */
|
|
108
|
+
export function formatCrossSessionBanner(chronicReads = []) {
|
|
109
|
+
const list = Array.isArray(chronicReads) ? chronicReads : [];
|
|
110
|
+
const top = list.find(c => (c.sessions || 0) >= 2) || list[0];
|
|
111
|
+
if (!top || !top.path) return '';
|
|
112
|
+
if (top.bannerText) return top.bannerText;
|
|
113
|
+
const n = top.windowSessions || top.sessions || 3;
|
|
114
|
+
const wastedK = Math.max(1, Math.round((top.totalWastedTokens || Math.max(1, (top.totalReads || 2) - 1) * FALLBACK_TOKENS_PER_WASTED_READ) / 1000));
|
|
115
|
+
const baseName = path.basename(String(top.path));
|
|
116
|
+
return `Across last ${n} sessions, ${baseName} caused ${wastedK}k repeated re-reads`;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Records the current session and returns the top-N chronic re-read list for `state.chronicReads`. */
|
|
120
|
+
export function updateChronicReads(cacheDir, sessionId, duplicateFiles, limit = 10, workspaceRoot = '') {
|
|
121
|
+
try {
|
|
122
|
+
let entries = recordSession(cacheDir, sessionId, duplicateFiles);
|
|
123
|
+
const effectiveRoot = (workspaceRoot && typeof workspaceRoot === 'string') ? workspaceRoot : process.cwd();
|
|
124
|
+
if (effectiveRoot) {
|
|
125
|
+
try {
|
|
126
|
+
const agentsMdPath = path.join(effectiveRoot, 'AGENTS.md');
|
|
127
|
+
if (fs.existsSync(agentsMdPath)) {
|
|
128
|
+
const agentsTxt = fs.readFileSync(agentsMdPath, 'utf8');
|
|
129
|
+
if (/StartLine/i.test(agentsTxt)) {
|
|
130
|
+
let stripped = false;
|
|
131
|
+
entries = entries.map(e => {
|
|
132
|
+
const filteredFiles = (e.files || []).filter(f => {
|
|
133
|
+
const base = path.basename(String(f.path || ''));
|
|
134
|
+
const keep = !base || !agentsTxt.includes(base);
|
|
135
|
+
if (!keep) stripped = true;
|
|
136
|
+
return keep;
|
|
137
|
+
});
|
|
138
|
+
return { ...e, files: filteredFiles };
|
|
139
|
+
}).filter(e => e.files.length > 0);
|
|
140
|
+
if (stripped && cacheDir) {
|
|
141
|
+
try {
|
|
142
|
+
const file = offendersFile(cacheDir);
|
|
143
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
144
|
+
fs.writeFileSync(tmp, entries.map(e => JSON.stringify(e)).join('\n') + (entries.length ? '\n' : ''), 'utf8');
|
|
145
|
+
fs.renameSync(tmp, file);
|
|
146
|
+
} catch (_writeErr) {
|
|
147
|
+
// Fail-open on disk write
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
} catch (_err) {
|
|
153
|
+
// Fail-open if workspace AGENTS.md is unreadable
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const list = aggregate(entries);
|
|
157
|
+
return list.slice(0, limit);
|
|
158
|
+
} catch {
|
|
159
|
+
return [];
|
|
160
|
+
}
|
|
161
|
+
}
|