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,789 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { execFileSync } from 'node:child_process';
|
|
4
|
+
import { getHomeDir } from './paths.mjs';
|
|
5
|
+
import { PrefixCacheShield } from './prefix_cache_shield.mjs';
|
|
6
|
+
import { atomicWriteFileSync } from './atomic_io.mjs';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Phase 4: U-Shaped Attention, Recency Mirror & Rule Hygiene Optimizer
|
|
10
|
+
*
|
|
11
|
+
* Prevents instruction drift caused by U-shaped transformer attention curves and
|
|
12
|
+
* Antigravity's 16.6k–30.7k native system prompt sandwich.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const U_CURVE_CONSTANTS = Object.freeze({
|
|
16
|
+
PRIMACY_END_RATIO: 0.30,
|
|
17
|
+
MIDDLE_TROUGH_START_RATIO: 0.30,
|
|
18
|
+
MIDDLE_TROUGH_END_RATIO: 0.70,
|
|
19
|
+
RECENCY_START_RATIO: 0.70,
|
|
20
|
+
GEMINI_MD_MAX_LINES: 150,
|
|
21
|
+
MEMORY_MD_MAX_LINES: 200,
|
|
22
|
+
MEMORY_MD_MAX_BYTES: 25 * 1024, // 25 KB
|
|
23
|
+
STALE_RULE_MAX_AGE_DAYS: 180,
|
|
24
|
+
STALE_RULE_MAX_AGE_MS: 180 * 24 * 60 * 60 * 1000,
|
|
25
|
+
NATIVE_SYSTEM_HEADER_EST_TOKENS: 20000,
|
|
26
|
+
RECENCY_MIRROR_MAX_INVARIANTS: 5,
|
|
27
|
+
CRITICAL_KEYWORD_REGEX: /\b(NEVER|ALWAYS|MUST|CRITICAL|NON-NEGOTIABLE)\b/i
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
export function getDefaultArchivedRulesPath(homeDir = getHomeDir()) {
|
|
31
|
+
return path.join(homeDir, '.gemini', 'antigravity', 'agy-horizon', 'archived_rules.md');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Computes positional attention recall weight for a relative position ratio p in [0, 1].
|
|
36
|
+
* - Primacy Band (0.00 - 0.30): 0.90 .. 1.00
|
|
37
|
+
* - Middle Attention Trough (0.30 - 0.70): 0.55 .. 0.70 (lowest at p = 0.50 -> 0.55)
|
|
38
|
+
* - Recency Band (0.70 - 1.00): 0.88 .. 0.98
|
|
39
|
+
*/
|
|
40
|
+
export function computePositionalRecallWeight(positionRatio = 0) {
|
|
41
|
+
const p = Math.max(0, Math.min(1, Number(positionRatio) || 0));
|
|
42
|
+
if (p < U_CURVE_CONSTANTS.PRIMACY_END_RATIO) {
|
|
43
|
+
const t = p / U_CURVE_CONSTANTS.PRIMACY_END_RATIO;
|
|
44
|
+
return Number((1.00 - t * 0.10).toFixed(4));
|
|
45
|
+
}
|
|
46
|
+
if (p < U_CURVE_CONSTANTS.MIDDLE_TROUGH_END_RATIO) {
|
|
47
|
+
const distFromCenter = Math.abs(p - 0.50) / 0.20; // 0 at center (0.50), 1 at edges (0.30, 0.70)
|
|
48
|
+
return Number((0.55 + distFromCenter * 0.15).toFixed(4));
|
|
49
|
+
}
|
|
50
|
+
const t = (p - U_CURVE_CONSTANTS.RECENCY_START_RATIO) / (1 - U_CURVE_CONSTANTS.RECENCY_START_RATIO);
|
|
51
|
+
return Number((0.88 + t * 0.10).toFixed(4));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function classifyPositionalBand(positionRatio = 0) {
|
|
55
|
+
const p = Math.max(0, Math.min(1, Number(positionRatio) || 0));
|
|
56
|
+
if (p < U_CURVE_CONSTANTS.PRIMACY_END_RATIO) return 'PRIMACY';
|
|
57
|
+
if (p < U_CURVE_CONSTANTS.MIDDLE_TROUGH_END_RATIO) return 'MIDDLE_TROUGH';
|
|
58
|
+
return 'RECENCY';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function isCriticalDirectiveLine(line = '') {
|
|
62
|
+
const trimmed = String(line || '').trim();
|
|
63
|
+
if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('```') || trimmed.startsWith('<!--')) return false;
|
|
64
|
+
return U_CURVE_CONSTANTS.CRITICAL_KEYWORD_REGEX.test(trimmed);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Scores directive priority for the top-5 Recency Anchor Mirror.
|
|
69
|
+
* Prioritizes NEVER and NON-NEGOTIABLE highest, followed by MUST, CRITICAL, ALWAYS.
|
|
70
|
+
*/
|
|
71
|
+
export function scoreDirectivePriority(line = '') {
|
|
72
|
+
const text = String(line || '').trim();
|
|
73
|
+
let score = 0;
|
|
74
|
+
if (/\bNON-NEGOTIABLE\b/i.test(text)) score += 50;
|
|
75
|
+
if (/\bNEVER\b/i.test(text)) score += 45;
|
|
76
|
+
if (/\bMUST\b/i.test(text)) score += 35;
|
|
77
|
+
if (/\bCRITICAL\b/i.test(text)) score += 30;
|
|
78
|
+
if (/\bALWAYS\b/i.test(text)) score += 25;
|
|
79
|
+
if (/^[-*+]\s+\*\*\[?/.test(text) || /^[-*+]\s+\*\*/.test(text)) score += 10;
|
|
80
|
+
return score;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Parses inline staleness metadata or git blame timestamps to detect rules older than 180 days.
|
|
85
|
+
* Supports inline tags such as `(last_verified: 2025-01-15)`, `[verified: 2025-01-15]`,
|
|
86
|
+
* `[updated: 2025-01-15]`, or `<!-- date: 2025-01-15 -->`.
|
|
87
|
+
*/
|
|
88
|
+
export function extractLineTimestampMs(line = '', lineNumber = 1, gitBlameMap = null) {
|
|
89
|
+
const text = String(line || '');
|
|
90
|
+
const dateMatch = text.match(
|
|
91
|
+
/(?:last_verified_at|last_verified|verified|updated|date|touched)\s*[:=]\s*(\d{4}-\d{2}-\d{2})/i
|
|
92
|
+
) || text.match(/\b(20\d{2}-\d{2}-\d{2})\b/);
|
|
93
|
+
|
|
94
|
+
if (dateMatch) {
|
|
95
|
+
const parsed = Date.parse(`${dateMatch[1]}T00:00:00Z`);
|
|
96
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (gitBlameMap && gitBlameMap.has(lineNumber)) {
|
|
100
|
+
return gitBlameMap.get(lineNumber);
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function getGitBlameLineTimestamps(filePath) {
|
|
106
|
+
const map = new Map();
|
|
107
|
+
if (!filePath || !fs.existsSync(filePath)) return map;
|
|
108
|
+
try {
|
|
109
|
+
const cwd = path.dirname(filePath);
|
|
110
|
+
const out = execFileSync('git', ['blame', '--line-porcelain', path.basename(filePath)], {
|
|
111
|
+
cwd,
|
|
112
|
+
encoding: 'utf8',
|
|
113
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
114
|
+
timeout: 3000
|
|
115
|
+
});
|
|
116
|
+
let currentLine = 0;
|
|
117
|
+
for (const rawLine of out.split(/\r?\n/)) {
|
|
118
|
+
const headerMatch = rawLine.match(/^[0-9a-f]{40}\s+\d+\s+(\d+)/);
|
|
119
|
+
if (headerMatch) {
|
|
120
|
+
currentLine = Number(headerMatch[1]);
|
|
121
|
+
} else if (rawLine.startsWith('committer-time ') && currentLine > 0) {
|
|
122
|
+
const sec = Number(rawLine.slice('committer-time '.length).trim());
|
|
123
|
+
if (Number.isFinite(sec) && sec > 0) {
|
|
124
|
+
map.set(currentLine, sec * 1000);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
} catch {}
|
|
129
|
+
return map;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Estimates MCP schema token overhead from ~/.gemini/config/mcp_config.json
|
|
134
|
+
*/
|
|
135
|
+
export function estimateCompositeSystemOverhead(homeDir = getHomeDir()) {
|
|
136
|
+
const mcpConfigPath = path.join(homeDir, '.gemini', 'config', 'mcp_config.json');
|
|
137
|
+
let mcpSchemaTokens = 0;
|
|
138
|
+
if (fs.existsSync(mcpConfigPath)) {
|
|
139
|
+
try {
|
|
140
|
+
const stat = fs.statSync(mcpConfigPath);
|
|
141
|
+
mcpSchemaTokens = Math.round(stat.size / 4) + 2500;
|
|
142
|
+
} catch {}
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
nativeHeaderTokens: U_CURVE_CONSTANTS.NATIVE_SYSTEM_HEADER_EST_TOKENS,
|
|
146
|
+
mcpSchemaTokens,
|
|
147
|
+
totalSystemOverheadTokens: U_CURVE_CONSTANTS.NATIVE_SYSTEM_HEADER_EST_TOKENS + mcpSchemaTokens
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Analyzes an instruction file's text (or file path) for U-shaped attention vulnerabilities.
|
|
153
|
+
*/
|
|
154
|
+
export function analyzeRuleFileAttention(input, options = {}) {
|
|
155
|
+
let content = '';
|
|
156
|
+
let filePath = options.filePath || null;
|
|
157
|
+
|
|
158
|
+
if (typeof input === 'string' && !options.isRawText && fs.existsSync(input)) {
|
|
159
|
+
filePath = path.resolve(input);
|
|
160
|
+
content = fs.readFileSync(filePath, 'utf8');
|
|
161
|
+
} else {
|
|
162
|
+
content = String(input || '');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const lines = content.split(/\r?\n/);
|
|
166
|
+
const totalLines = lines.length;
|
|
167
|
+
const criticalDirectives = [];
|
|
168
|
+
const middleTroughVulnerabilities = [];
|
|
169
|
+
const primacyDirectives = [];
|
|
170
|
+
const recencyDirectives = [];
|
|
171
|
+
|
|
172
|
+
for (let i = 0; i < totalLines; i++) {
|
|
173
|
+
const lineNumber = i + 1;
|
|
174
|
+
const rawLine = lines[i];
|
|
175
|
+
const positionRatio = totalLines > 1 ? i / (totalLines - 1) : 0;
|
|
176
|
+
const band = classifyPositionalBand(positionRatio);
|
|
177
|
+
const recallWeight = computePositionalRecallWeight(positionRatio);
|
|
178
|
+
|
|
179
|
+
if (isCriticalDirectiveLine(rawLine)) {
|
|
180
|
+
const matchedKeyword = (rawLine.match(U_CURVE_CONSTANTS.CRITICAL_KEYWORD_REGEX) || [])[1]?.toUpperCase() || 'CRITICAL';
|
|
181
|
+
const item = {
|
|
182
|
+
lineNumber,
|
|
183
|
+
text: rawLine.trim(),
|
|
184
|
+
keyword: matchedKeyword,
|
|
185
|
+
positionRatio: Number(positionRatio.toFixed(4)),
|
|
186
|
+
band,
|
|
187
|
+
recallWeight,
|
|
188
|
+
priorityScore: scoreDirectivePriority(rawLine)
|
|
189
|
+
};
|
|
190
|
+
criticalDirectives.push(item);
|
|
191
|
+
if (band === 'MIDDLE_TROUGH') {
|
|
192
|
+
middleTroughVulnerabilities.push(item);
|
|
193
|
+
} else if (band === 'PRIMACY') {
|
|
194
|
+
primacyDirectives.push(item);
|
|
195
|
+
} else {
|
|
196
|
+
recencyDirectives.push(item);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const avgCriticalRecall =
|
|
202
|
+
criticalDirectives.length > 0
|
|
203
|
+
? criticalDirectives.reduce((sum, d) => sum + d.recallWeight, 0) / criticalDirectives.length
|
|
204
|
+
: 0.95;
|
|
205
|
+
|
|
206
|
+
// Vulnerability penalty for critical directives stranded in the 30-70% middle trough
|
|
207
|
+
const troughRatio =
|
|
208
|
+
criticalDirectives.length > 0
|
|
209
|
+
? middleTroughVulnerabilities.length / criticalDirectives.length
|
|
210
|
+
: 0;
|
|
211
|
+
|
|
212
|
+
const attentionHealthScore = Math.max(
|
|
213
|
+
0,
|
|
214
|
+
Math.min(100, Math.round(avgCriticalRecall * 100 - troughRatio * 25))
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
const primacyScorePct = Math.round(
|
|
218
|
+
(primacyDirectives.length > 0
|
|
219
|
+
? primacyDirectives.reduce((s, d) => s + d.recallWeight, 0) / primacyDirectives.length
|
|
220
|
+
: 0.94) * 100
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
return {
|
|
224
|
+
filePath,
|
|
225
|
+
totalLines,
|
|
226
|
+
totalCriticalDirectives: criticalDirectives.length,
|
|
227
|
+
middleTroughRiskCount: middleTroughVulnerabilities.length,
|
|
228
|
+
middleTroughVulnerabilities,
|
|
229
|
+
primacyDirectives,
|
|
230
|
+
recencyDirectives,
|
|
231
|
+
criticalDirectives,
|
|
232
|
+
avgCriticalRecall: Number(avgCriticalRecall.toFixed(4)),
|
|
233
|
+
primacyScorePct,
|
|
234
|
+
attentionHealthScore,
|
|
235
|
+
uiSummary: `Primacy: ${primacyScorePct}% | Middle Trough Risk: ${middleTroughVulnerabilities.length} critical rules`
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Audits an instruction file (GEMINI.md, AGENTS.md, or MEMORY.md) for:
|
|
241
|
+
* - Line/byte budget violations (150 lines for GEMINI.md, 200 lines / 25 KB for MEMORY.md)
|
|
242
|
+
* - Duplicate directives
|
|
243
|
+
* - Contradictory directives (ALWAYS X vs NEVER/DO NOT X)
|
|
244
|
+
* - Stale entries (>180 days since last git touch or inline verification date)
|
|
245
|
+
*/
|
|
246
|
+
export function auditRuleFileHygiene(input, options = {}) {
|
|
247
|
+
let content = '';
|
|
248
|
+
let filePath = options.filePath || null;
|
|
249
|
+
|
|
250
|
+
if (typeof input === 'string' && !options.isRawText && fs.existsSync(input)) {
|
|
251
|
+
filePath = path.resolve(input);
|
|
252
|
+
content = fs.readFileSync(filePath, 'utf8');
|
|
253
|
+
} else {
|
|
254
|
+
content = String(input || '');
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const nowMs = typeof options.nowFn === 'function' ? options.nowFn() : Date.now();
|
|
258
|
+
const isMemoryMd = filePath ? /MEMORY\.md$/i.test(filePath) : Boolean(options.isMemoryMd);
|
|
259
|
+
const maxLines = isMemoryMd ? U_CURVE_CONSTANTS.MEMORY_MD_MAX_LINES : U_CURVE_CONSTANTS.GEMINI_MD_MAX_LINES;
|
|
260
|
+
const maxBytes = isMemoryMd ? U_CURVE_CONSTANTS.MEMORY_MD_MAX_BYTES : 64 * 1024;
|
|
261
|
+
|
|
262
|
+
const lines = content.split(/\r?\n/);
|
|
263
|
+
const byteSize = Buffer.byteLength(content, 'utf8');
|
|
264
|
+
const gitBlameMap = options.enableGitBlame && filePath ? getGitBlameLineTimestamps(filePath) : null;
|
|
265
|
+
|
|
266
|
+
const seenNormalized = new Map();
|
|
267
|
+
const duplicateLines = [];
|
|
268
|
+
const staleLines = [];
|
|
269
|
+
const positiveAssertions = new Map();
|
|
270
|
+
const negativeAssertions = new Map();
|
|
271
|
+
const contradictions = [];
|
|
272
|
+
|
|
273
|
+
for (let i = 0; i < lines.length; i++) {
|
|
274
|
+
const lineNumber = i + 1;
|
|
275
|
+
const raw = lines[i];
|
|
276
|
+
const trimmed = raw.trim();
|
|
277
|
+
if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('```')) continue;
|
|
278
|
+
|
|
279
|
+
// 1. Check staleness (>180 days)
|
|
280
|
+
const tsMs = extractLineTimestampMs(raw, lineNumber, gitBlameMap);
|
|
281
|
+
if (tsMs !== null && nowMs - tsMs > U_CURVE_CONSTANTS.STALE_RULE_MAX_AGE_MS) {
|
|
282
|
+
const ageDays = Math.floor((nowMs - tsMs) / (24 * 60 * 60 * 1000));
|
|
283
|
+
staleLines.push({
|
|
284
|
+
lineNumber,
|
|
285
|
+
text: trimmed,
|
|
286
|
+
ageDays
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// 2. Check duplicate directives
|
|
291
|
+
const norm = trimmed
|
|
292
|
+
.toLowerCase()
|
|
293
|
+
.replace(/^[-*+\d.)\s]+/, '')
|
|
294
|
+
.replace(/\s+/g, ' ')
|
|
295
|
+
.trim();
|
|
296
|
+
if (norm.length >= 12) {
|
|
297
|
+
if (seenNormalized.has(norm)) {
|
|
298
|
+
duplicateLines.push({
|
|
299
|
+
lineNumber,
|
|
300
|
+
firstLineNumber: seenNormalized.get(norm),
|
|
301
|
+
text: trimmed
|
|
302
|
+
});
|
|
303
|
+
} else {
|
|
304
|
+
seenNormalized.set(norm, lineNumber);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// 3. Check contradictions (ALWAYS <target> vs NEVER/DO NOT <target>)
|
|
309
|
+
const alwaysMatch = trimmed.match(/\b(?:ALWAYS|MUST)\s+(?:use\s+|enable\s+|run\s+)?([a-z0-9_./:-]{3,40})/i);
|
|
310
|
+
if (alwaysMatch) {
|
|
311
|
+
const subject = alwaysMatch[1].toLowerCase();
|
|
312
|
+
positiveAssertions.set(subject, { lineNumber, text: trimmed });
|
|
313
|
+
if (negativeAssertions.has(subject)) {
|
|
314
|
+
contradictions.push({
|
|
315
|
+
subject,
|
|
316
|
+
positive: { lineNumber, text: trimmed },
|
|
317
|
+
negative: negativeAssertions.get(subject)
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const neverMatch = trimmed.match(/\b(?:NEVER|DO\s+NOT|DON'T)\s+(?:use\s+|enable\s+|run\s+)?([a-z0-9_./:-]{3,40})/i);
|
|
323
|
+
if (neverMatch) {
|
|
324
|
+
const subject = neverMatch[1].toLowerCase();
|
|
325
|
+
negativeAssertions.set(subject, { lineNumber, text: trimmed });
|
|
326
|
+
if (positiveAssertions.has(subject)) {
|
|
327
|
+
contradictions.push({
|
|
328
|
+
subject,
|
|
329
|
+
positive: positiveAssertions.get(subject),
|
|
330
|
+
negative: { lineNumber, text: trimmed }
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
return {
|
|
337
|
+
filePath,
|
|
338
|
+
isMemoryMd,
|
|
339
|
+
lineCount: lines.length,
|
|
340
|
+
maxLines,
|
|
341
|
+
overLineBudget: lines.length > maxLines,
|
|
342
|
+
excessLines: Math.max(0, lines.length - maxLines),
|
|
343
|
+
byteSize,
|
|
344
|
+
maxBytes,
|
|
345
|
+
overByteBudget: byteSize > maxBytes,
|
|
346
|
+
staleLines,
|
|
347
|
+
duplicateLines,
|
|
348
|
+
contradictions
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Reorders an instruction file for U-Shaped Attention while archiving >180-day stale lines
|
|
354
|
+
* and deduplicating directives:
|
|
355
|
+
* - Primacy Band (Top 30%): Document title, core architectural overview & structural rules
|
|
356
|
+
* - Middle Band (30%-70%): Reference lookup tables, non-critical notes & examples
|
|
357
|
+
* - Recency Band (Bottom 30%): Hard NEVER / MUST / ALWAYS / CRITICAL / NON-NEGOTIABLE guardrails
|
|
358
|
+
*/
|
|
359
|
+
export function buildUShapedReorderedContent(rawContent = '', options = {}) {
|
|
360
|
+
const nowMs = typeof options.nowFn === 'function' ? options.nowFn() : Date.now();
|
|
361
|
+
const maxLines = Number.isFinite(options.maxLines)
|
|
362
|
+
? options.maxLines
|
|
363
|
+
: U_CURVE_CONSTANTS.GEMINI_MD_MAX_LINES;
|
|
364
|
+
|
|
365
|
+
const lines = String(rawContent || '').split(/\r?\n/);
|
|
366
|
+
const primacyLines = [];
|
|
367
|
+
const middleReferenceLines = [];
|
|
368
|
+
const recencyCriticalLines = [];
|
|
369
|
+
const archivedLines = [];
|
|
370
|
+
const seenNormalized = new Set();
|
|
371
|
+
|
|
372
|
+
let inCodeBlock = false;
|
|
373
|
+
let currentSectionType = 'PRIMACY'; // 'PRIMACY' | 'MIDDLE'
|
|
374
|
+
|
|
375
|
+
for (let i = 0; i < lines.length; i++) {
|
|
376
|
+
const line = lines[i];
|
|
377
|
+
const trimmed = line.trim();
|
|
378
|
+
|
|
379
|
+
if (trimmed.startsWith('```')) {
|
|
380
|
+
inCodeBlock = !inCodeBlock;
|
|
381
|
+
middleReferenceLines.push(line);
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
if (inCodeBlock) {
|
|
386
|
+
middleReferenceLines.push(line);
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
if (!trimmed) {
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Check if >180 days stale
|
|
395
|
+
const tsMs = extractLineTimestampMs(line, i + 1, null);
|
|
396
|
+
if (tsMs !== null && nowMs - tsMs > U_CURVE_CONSTANTS.STALE_RULE_MAX_AGE_MS) {
|
|
397
|
+
archivedLines.push({
|
|
398
|
+
lineNumber: i + 1,
|
|
399
|
+
text: trimmed,
|
|
400
|
+
reason: 'STALE_OVER_180_DAYS'
|
|
401
|
+
});
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// Deduplicate bullet rules
|
|
406
|
+
const norm = trimmed
|
|
407
|
+
.toLowerCase()
|
|
408
|
+
.replace(/^[-*+\d.)\s]+/, '')
|
|
409
|
+
.replace(/\s+/g, ' ')
|
|
410
|
+
.trim();
|
|
411
|
+
if (!trimmed.startsWith('#') && !trimmed.startsWith('|') && norm.length >= 12) {
|
|
412
|
+
if (seenNormalized.has(norm)) {
|
|
413
|
+
archivedLines.push({
|
|
414
|
+
lineNumber: i + 1,
|
|
415
|
+
text: trimmed,
|
|
416
|
+
reason: 'DUPLICATE_DIRECTIVE'
|
|
417
|
+
});
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
seenNormalized.add(norm);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// Critical NEVER/MUST/ALWAYS/CRITICAL/NON-NEGOTIABLE directives go to the Recency Band
|
|
424
|
+
if (!trimmed.startsWith('#') && isCriticalDirectiveLine(trimmed)) {
|
|
425
|
+
recencyCriticalLines.push(line);
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// Markdown tables or reference items go to Middle Band
|
|
430
|
+
if (
|
|
431
|
+
trimmed.startsWith('|') ||
|
|
432
|
+
/\b(reference|lookup|table|appendix|glossary|note|example|background)\b/i.test(trimmed)
|
|
433
|
+
) {
|
|
434
|
+
if (trimmed.startsWith('#')) currentSectionType = 'MIDDLE';
|
|
435
|
+
middleReferenceLines.push(line);
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
if (trimmed.startsWith('#')) {
|
|
440
|
+
if (/\b(architecture|overview|foundation|identity|core|invariant|primacy)\b/i.test(trimmed)) {
|
|
441
|
+
currentSectionType = 'PRIMACY';
|
|
442
|
+
primacyLines.push(line);
|
|
443
|
+
} else {
|
|
444
|
+
currentSectionType = primacyLines.length < 25 ? 'PRIMACY' : 'MIDDLE';
|
|
445
|
+
if (currentSectionType === 'PRIMACY') {
|
|
446
|
+
primacyLines.push(line);
|
|
447
|
+
} else {
|
|
448
|
+
middleReferenceLines.push(line);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
if (currentSectionType === 'PRIMACY' && primacyLines.length < Math.floor(maxLines * 0.28)) {
|
|
455
|
+
primacyLines.push(line);
|
|
456
|
+
} else {
|
|
457
|
+
middleReferenceLines.push(line);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// Sort recencyCriticalLines so highest-priority NEVER / NON-NEGOTIABLE / MUST rules are at the very bottom
|
|
462
|
+
recencyCriticalLines.sort((a, b) => scoreDirectivePriority(a) - scoreDirectivePriority(b));
|
|
463
|
+
|
|
464
|
+
// Enforce line budget by trimming excess non-critical middle reference lines into archive if needed
|
|
465
|
+
const headerLines = primacyLines.length > 0 ? primacyLines : ['# Workspace Architecture & Primacy Rules'];
|
|
466
|
+
const recencySectionHeader = [
|
|
467
|
+
'',
|
|
468
|
+
'## Recency Guardrail Pin (Critical Invariants)',
|
|
469
|
+
...recencyCriticalLines
|
|
470
|
+
];
|
|
471
|
+
|
|
472
|
+
const availableMiddleBudget = Math.max(
|
|
473
|
+
10,
|
|
474
|
+
maxLines - headerLines.length - recencySectionHeader.length - 4
|
|
475
|
+
);
|
|
476
|
+
|
|
477
|
+
let keptMiddle = middleReferenceLines;
|
|
478
|
+
if (middleReferenceLines.length > availableMiddleBudget) {
|
|
479
|
+
const overflow = middleReferenceLines.slice(availableMiddleBudget);
|
|
480
|
+
for (const ov of overflow) {
|
|
481
|
+
if (ov.trim()) {
|
|
482
|
+
archivedLines.push({
|
|
483
|
+
lineNumber: 0,
|
|
484
|
+
text: ov.trim(),
|
|
485
|
+
reason: 'LINE_BUDGET_OVERFLOW'
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
keptMiddle = middleReferenceLines.slice(0, availableMiddleBudget);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
const finalLines = [
|
|
493
|
+
...headerLines,
|
|
494
|
+
'',
|
|
495
|
+
'## Reference & Context Lookup (Middle Band)',
|
|
496
|
+
...keptMiddle,
|
|
497
|
+
...recencySectionHeader,
|
|
498
|
+
''
|
|
499
|
+
];
|
|
500
|
+
|
|
501
|
+
return {
|
|
502
|
+
reorderedContent: finalLines.join('\n'),
|
|
503
|
+
archivedLines,
|
|
504
|
+
stats: {
|
|
505
|
+
primacyCount: headerLines.length,
|
|
506
|
+
middleCount: keptMiddle.length,
|
|
507
|
+
recencyCriticalCount: recencyCriticalLines.length,
|
|
508
|
+
archivedCount: archivedLines.length,
|
|
509
|
+
totalLines: finalLines.length
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
export class UShapedAttentionOptimizer {
|
|
515
|
+
constructor(options = {}) {
|
|
516
|
+
this.homeDir = options.homeDir || getHomeDir();
|
|
517
|
+
this.workspaceDir = options.workspaceDir || process.cwd();
|
|
518
|
+
this.archivedRulesPath =
|
|
519
|
+
options.archivedRulesPath || getDefaultArchivedRulesPath(this.homeDir);
|
|
520
|
+
this.prefixShield =
|
|
521
|
+
options.prefixShield ||
|
|
522
|
+
options.prefixCacheShield ||
|
|
523
|
+
new PrefixCacheShield({
|
|
524
|
+
homeDir: this.homeDir,
|
|
525
|
+
queuePath: options.queuePath
|
|
526
|
+
});
|
|
527
|
+
this.nowFn = typeof options.nowFn === 'function' ? options.nowFn : () => Date.now();
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Scans global and workspace instruction files and returns composite U-shaped attention analysis.
|
|
532
|
+
*/
|
|
533
|
+
scanWorkspaceAndGlobalRules(customFiles = null) {
|
|
534
|
+
const candidates = customFiles || [
|
|
535
|
+
path.join(this.homeDir, '.gemini', 'GEMINI.md'),
|
|
536
|
+
path.join(this.workspaceDir, 'GEMINI.md'),
|
|
537
|
+
path.join(this.workspaceDir, 'AGENTS.md'),
|
|
538
|
+
path.join(this.workspaceDir, '.agents', 'CONTEXT.md'),
|
|
539
|
+
path.join(this.workspaceDir, 'MEMORY.md')
|
|
540
|
+
];
|
|
541
|
+
|
|
542
|
+
const fileReports = [];
|
|
543
|
+
for (const candidate of candidates) {
|
|
544
|
+
if (candidate && fs.existsSync(candidate)) {
|
|
545
|
+
const attention = analyzeRuleFileAttention(candidate);
|
|
546
|
+
const hygiene = auditRuleFileHygiene(candidate, { nowFn: this.nowFn });
|
|
547
|
+
fileReports.push({
|
|
548
|
+
filePath: candidate,
|
|
549
|
+
attention,
|
|
550
|
+
hygiene
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const systemOverhead = estimateCompositeSystemOverhead(this.homeDir);
|
|
556
|
+
const totalMiddleTroughRisk = fileReports.reduce(
|
|
557
|
+
(sum, r) => sum + r.attention.middleTroughRiskCount,
|
|
558
|
+
0
|
|
559
|
+
);
|
|
560
|
+
const avgPrimacyPct =
|
|
561
|
+
fileReports.length > 0
|
|
562
|
+
? Math.round(
|
|
563
|
+
fileReports.reduce((sum, r) => sum + r.attention.primacyScorePct, 0) /
|
|
564
|
+
fileReports.length
|
|
565
|
+
)
|
|
566
|
+
: 94;
|
|
567
|
+
|
|
568
|
+
return {
|
|
569
|
+
systemOverhead,
|
|
570
|
+
fileReports,
|
|
571
|
+
totalMiddleTroughRisk,
|
|
572
|
+
avgPrimacyPct,
|
|
573
|
+
uiSummary: `Primacy: ${avgPrimacyPct}% | Middle Trough Risk: ${totalMiddleTroughRisk} critical rules`
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* 1-Click U-Shape Reorder & Hygiene Archiver:
|
|
579
|
+
* - Reorders directives so critical NEVER/MUST guardrails move out of the 30-70% Middle Trough
|
|
580
|
+
* into the bottom 30% Recency Band
|
|
581
|
+
* - Archives >180-day stale rules and budget overflow lines to `~/.gemini/antigravity/agy-horizon/archived_rules.md`
|
|
582
|
+
* - Routes GEMINI.md / AGENTS.md mutations through PrefixCacheShield so a warm prefix cache is never busted
|
|
583
|
+
* - Optionally mirrors the top 5 NEVER/MUST invariants into `brain/<GUID>/task.md`
|
|
584
|
+
*/
|
|
585
|
+
optimizeRuleFile(filePath, options = {}) {
|
|
586
|
+
const resolvedPath = path.resolve(filePath);
|
|
587
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
588
|
+
throw new Error(`Rule file not found: ${resolvedPath}`);
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
const rawContent = fs.readFileSync(resolvedPath, 'utf8');
|
|
592
|
+
const beforeAnalysis = analyzeRuleFileAttention(rawContent, {
|
|
593
|
+
isRawText: true,
|
|
594
|
+
filePath: resolvedPath
|
|
595
|
+
});
|
|
596
|
+
const beforeHygiene = auditRuleFileHygiene(rawContent, {
|
|
597
|
+
isRawText: true,
|
|
598
|
+
filePath: resolvedPath,
|
|
599
|
+
nowFn: this.nowFn
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
const isMemoryMd = /MEMORY\.md$/i.test(resolvedPath);
|
|
603
|
+
const maxLines = isMemoryMd
|
|
604
|
+
? U_CURVE_CONSTANTS.MEMORY_MD_MAX_LINES
|
|
605
|
+
: options.maxLines || U_CURVE_CONSTANTS.GEMINI_MD_MAX_LINES;
|
|
606
|
+
|
|
607
|
+
const { reorderedContent, archivedLines, stats } = buildUShapedReorderedContent(rawContent, {
|
|
608
|
+
nowFn: this.nowFn,
|
|
609
|
+
maxLines
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
// Write archived stale/overflow lines to ~/.gemini/antigravity/agy-horizon/archived_rules.md
|
|
613
|
+
if (archivedLines.length > 0) {
|
|
614
|
+
this._appendArchivedRules(resolvedPath, archivedLines);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
const resolvedSession = options.session || {
|
|
618
|
+
cacheState: options.cacheState,
|
|
619
|
+
cacheWarm: options.cacheWarm,
|
|
620
|
+
cachedTokens: options.cachedTokens,
|
|
621
|
+
cacheTtlSeconds: options.cacheTtlSeconds,
|
|
622
|
+
forceColdBust: options.forceColdBust,
|
|
623
|
+
postCompact: options.postCompact
|
|
624
|
+
};
|
|
625
|
+
|
|
626
|
+
// Stage or apply the reordered rule file via PrefixCacheShield
|
|
627
|
+
const shieldResult = this.prefixShield.stageOrApplyDelta(
|
|
628
|
+
{
|
|
629
|
+
targetPath: resolvedPath,
|
|
630
|
+
operation: 'REORDER',
|
|
631
|
+
newContent: reorderedContent,
|
|
632
|
+
source: 'u-shaped-optimizer',
|
|
633
|
+
metadata: {
|
|
634
|
+
beforeMiddleTroughRisk: beforeAnalysis.middleTroughRiskCount,
|
|
635
|
+
archivedCount: archivedLines.length
|
|
636
|
+
}
|
|
637
|
+
},
|
|
638
|
+
resolvedSession
|
|
639
|
+
);
|
|
640
|
+
|
|
641
|
+
const afterAnalysis = analyzeRuleFileAttention(reorderedContent, {
|
|
642
|
+
isRawText: true,
|
|
643
|
+
filePath: resolvedPath
|
|
644
|
+
});
|
|
645
|
+
|
|
646
|
+
let recencyMirrorResult = null;
|
|
647
|
+
if (options.taskMdPath) {
|
|
648
|
+
recencyMirrorResult = this.mirrorTopGuardrailsToTaskMd(reorderedContent, options.taskMdPath);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
return {
|
|
652
|
+
filePath: resolvedPath,
|
|
653
|
+
beforeAnalysis,
|
|
654
|
+
beforeHygiene,
|
|
655
|
+
afterAnalysis,
|
|
656
|
+
archivedLines,
|
|
657
|
+
archivedRulesPath: this.archivedRulesPath,
|
|
658
|
+
stats,
|
|
659
|
+
staged: Boolean(shieldResult.staged),
|
|
660
|
+
deferred: Boolean(shieldResult.deferred),
|
|
661
|
+
shieldResult,
|
|
662
|
+
recencyMirrorResult
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
_appendArchivedRules(sourceFilePath, archivedLines = []) {
|
|
667
|
+
fs.mkdirSync(path.dirname(this.archivedRulesPath), { recursive: true });
|
|
668
|
+
const nowIso = new Date(this.nowFn()).toISOString();
|
|
669
|
+
const header = `\n## Archived from \`${path.basename(sourceFilePath)}\` (${nowIso})\n`;
|
|
670
|
+
const body = archivedLines
|
|
671
|
+
.map(item => `- [${item.reason}] (line ${item.lineNumber}): ${item.text}`)
|
|
672
|
+
.join('\n');
|
|
673
|
+
fs.appendFileSync(this.archivedRulesPath, `${header}${body}\n`, 'utf8');
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/**
|
|
677
|
+
* Antigravity Recency Anchor Mirror:
|
|
678
|
+
* Mirrors the top 5 highest-priority NEVER/MUST invariants into a compact
|
|
679
|
+
* `## Active Guardrail Pin` block at the very bottom of `~/.gemini/antigravity/brain/<GUID>/task.md`
|
|
680
|
+
* so those rules remain inside the final 10% Recency Band of the entire conversation window.
|
|
681
|
+
*/
|
|
682
|
+
mirrorTopGuardrailsToTaskMd(ruleContentOrFilePath, taskMdPath, options = {}) {
|
|
683
|
+
if (!taskMdPath) {
|
|
684
|
+
throw new Error('taskMdPath is required for mirrorTopGuardrailsToTaskMd');
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
const content =
|
|
688
|
+
typeof ruleContentOrFilePath === 'string' && fs.existsSync(ruleContentOrFilePath)
|
|
689
|
+
? fs.readFileSync(ruleContentOrFilePath, 'utf8')
|
|
690
|
+
: String(ruleContentOrFilePath || '');
|
|
691
|
+
|
|
692
|
+
const analysis = analyzeRuleFileAttention(content, { isRawText: true });
|
|
693
|
+
const maxInvariants = Number.isFinite(options.maxInvariants)
|
|
694
|
+
? options.maxInvariants
|
|
695
|
+
: U_CURVE_CONSTANTS.RECENCY_MIRROR_MAX_INVARIANTS;
|
|
696
|
+
|
|
697
|
+
// Select top 5 highest-priority NEVER / MUST invariants
|
|
698
|
+
const sorted = [...analysis.criticalDirectives].sort((a, b) => {
|
|
699
|
+
if (b.priorityScore !== a.priorityScore) return b.priorityScore - a.priorityScore;
|
|
700
|
+
return b.lineNumber - a.lineNumber;
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
const topInvariants = [];
|
|
704
|
+
const seen = new Set();
|
|
705
|
+
for (const item of sorted) {
|
|
706
|
+
const normalized = item.text.replace(/^[-*+\d.)\s]+/, '').trim();
|
|
707
|
+
const key = normalized.toLowerCase();
|
|
708
|
+
if (!seen.has(key)) {
|
|
709
|
+
seen.add(key);
|
|
710
|
+
topInvariants.push(normalized.startsWith('-') ? normalized : `- ${normalized}`);
|
|
711
|
+
}
|
|
712
|
+
if (topInvariants.length >= maxInvariants) break;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
const existingTaskMd = fs.existsSync(taskMdPath) ? fs.readFileSync(taskMdPath, 'utf8') : '';
|
|
716
|
+
const stripped = existingTaskMd
|
|
717
|
+
.replace(/\n*## Active Guardrail Pin[\s\S]*$/i, '')
|
|
718
|
+
.trimEnd();
|
|
719
|
+
|
|
720
|
+
const pinLines = [
|
|
721
|
+
'## Active Guardrail Pin',
|
|
722
|
+
...topInvariants
|
|
723
|
+
];
|
|
724
|
+
|
|
725
|
+
const updatedTaskMd = `${stripped}\n\n${pinLines.join('\n')}\n`;
|
|
726
|
+
atomicWriteFileSync(taskMdPath, updatedTaskMd, { encoding: 'utf8' });
|
|
727
|
+
|
|
728
|
+
return {
|
|
729
|
+
taskMdPath,
|
|
730
|
+
mirroredCount: topInvariants.length,
|
|
731
|
+
invariants: topInvariants,
|
|
732
|
+
activeInTaskMd: true
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* HUD Hygiene: Computes a strictly read-only U-curve positional decay heatmap over
|
|
739
|
+
* conversation transcript steps (Primacy top-30%, Middle Trough 30%-70%, Recency bottom-30%)
|
|
740
|
+
* without mutating `AGENTS.md` or enforcing Claude Code's 200-line `MEMORY.md` cap.
|
|
741
|
+
*/
|
|
742
|
+
export function computeReadOnlyUCurveConversationHeatmap(steps = []) {
|
|
743
|
+
const list = Array.isArray(steps) ? steps : [];
|
|
744
|
+
const totalSteps = list.length;
|
|
745
|
+
let primacyTokens = 0;
|
|
746
|
+
let middleTroughTokens = 0;
|
|
747
|
+
let recencyTokens = 0;
|
|
748
|
+
let middleTroughCriticalSteps = 0;
|
|
749
|
+
|
|
750
|
+
const cells = list.map((step, idx) => {
|
|
751
|
+
const ratio = totalSteps <= 1 ? 0 : idx / (totalSteps - 1);
|
|
752
|
+
const band = classifyPositionalBand(ratio);
|
|
753
|
+
const recallWeight = computePositionalRecallWeight(ratio);
|
|
754
|
+
const text = String(step?.content ?? step?.text ?? '');
|
|
755
|
+
const tokens = Math.max(0, Number(step?.tokens ?? Math.ceil(text.length / 4)));
|
|
756
|
+
const hasCriticalConstraint = U_CURVE_CONSTANTS.CRITICAL_KEYWORD_REGEX.test(text);
|
|
757
|
+
|
|
758
|
+
if (band === 'PRIMACY') primacyTokens += tokens;
|
|
759
|
+
else if (band === 'MIDDLE_TROUGH') {
|
|
760
|
+
middleTroughTokens += tokens;
|
|
761
|
+
if (hasCriticalConstraint) middleTroughCriticalSteps++;
|
|
762
|
+
} else {
|
|
763
|
+
recencyTokens += tokens;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
return {
|
|
767
|
+
stepIndex: idx,
|
|
768
|
+
positionRatio: Number(ratio.toFixed(4)),
|
|
769
|
+
band,
|
|
770
|
+
recallWeight,
|
|
771
|
+
tokens,
|
|
772
|
+
hasCriticalConstraint
|
|
773
|
+
};
|
|
774
|
+
});
|
|
775
|
+
|
|
776
|
+
return Object.freeze({
|
|
777
|
+
readOnly: true,
|
|
778
|
+
mutatesAgentsMd: false,
|
|
779
|
+
enforces200LineMemoryCap: false,
|
|
780
|
+
totalSteps,
|
|
781
|
+
primacyTokens,
|
|
782
|
+
middleTroughTokens,
|
|
783
|
+
recencyTokens,
|
|
784
|
+
middleTroughCriticalSteps,
|
|
785
|
+
cells
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
export default UShapedAttentionOptimizer;
|