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,551 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import { execFileSync } from 'node:child_process';
|
|
5
|
+
import { performance } from 'node:perf_hooks';
|
|
6
|
+
import { atomicWriteFileSync } from '../atomic_io.mjs';
|
|
7
|
+
import {
|
|
8
|
+
CASCADE_COMPACTION_CEILING_TOKENS,
|
|
9
|
+
CASCADE_CHECKPOINT_BANDS,
|
|
10
|
+
createStateBaton,
|
|
11
|
+
validateStateBaton,
|
|
12
|
+
formatColdResumeBatonPrompt,
|
|
13
|
+
formatHandoffMarkdown
|
|
14
|
+
} from '../shared/handoff_schema.mjs';
|
|
15
|
+
import { evaluateDet17CascadeCheckpoints } from '../shared/detectors.mjs';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Phase 1.1: Progressive Checkpoint & Session Continuity Sync (`DET-10`)
|
|
19
|
+
* (`src/core/coach/progressive_checkpointer.mjs`)
|
|
20
|
+
*
|
|
21
|
+
* Prevents Negative Constraint Evaporation and context amnesia across unexpected
|
|
22
|
+
* automatic compactions (50k-70k soft watermark) or deep fill bands:
|
|
23
|
+
* - Takes zero-token out-of-band disk snapshots at 20%, 35%, 50%, 65%, and 80%
|
|
24
|
+
* fill bands, plus at the 50,000-token soft watermark.
|
|
25
|
+
* - Writes strictly to `.agents/cache/checkpoints/` without touching `AGENTS.md`,
|
|
26
|
+
* `GEMINI.md`, or `.agents/CONTEXT.md` (preserving 100% KV prefix cache hits).
|
|
27
|
+
* - Detects evaporated negative constraints (`NEVER`, `MUST`, `DO NOT`, `NON-NEGOTIABLE`)
|
|
28
|
+
* and lost `[/]` active task steps immediately after `/compact`, generating a
|
|
29
|
+
* 1-click recovery prompt.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
export const CHECKPOINT_BANDS = Object.freeze([0.20, 0.35, 0.50, 0.65, 0.80]);
|
|
33
|
+
export const SOFT_WATERMARK_TOKENS = 50000;
|
|
34
|
+
export const DEFAULT_MAX_TOKENS = 256000;
|
|
35
|
+
|
|
36
|
+
const NEGATIVE_CONSTRAINT_REGEX = /\b(NEVER|MUST\s+NOT|MUST|DO\s+NOT|DON'T|NON-NEGOTIABLE|STRICTLY\s+FORBIDDEN)\b/i;
|
|
37
|
+
|
|
38
|
+
export function sha256Text(text = '') {
|
|
39
|
+
return crypto.createHash('sha256').update(String(text ?? ''), 'utf8').digest('hex');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Extracts critical negative constraints and invariant directives from rule files,
|
|
44
|
+
* `task.md`, or user turns.
|
|
45
|
+
*/
|
|
46
|
+
export function extractNegativeConstraints(sources = []) {
|
|
47
|
+
const list = Array.isArray(sources) ? sources : [sources];
|
|
48
|
+
const seen = new Set();
|
|
49
|
+
const constraints = [];
|
|
50
|
+
|
|
51
|
+
for (const src of list) {
|
|
52
|
+
if (!src) continue;
|
|
53
|
+
const lines = String(src).split(/\r?\n/);
|
|
54
|
+
for (const rawLine of lines) {
|
|
55
|
+
const cleaned = rawLine
|
|
56
|
+
.replace(/^\s*[-*+]\s*(\[[ xX/]\]\s*)?/, '')
|
|
57
|
+
.replace(/^\s*\d+\.\s*/, '')
|
|
58
|
+
.trim();
|
|
59
|
+
if (!cleaned || cleaned.length < 10 || cleaned.length > 260) continue;
|
|
60
|
+
if (cleaned.startsWith('#') || cleaned.startsWith('```') || cleaned.startsWith('//')) continue;
|
|
61
|
+
if (NEGATIVE_CONSTRAINT_REGEX.test(cleaned)) {
|
|
62
|
+
const normKey = cleaned.toLowerCase().replace(/\s+/g, ' ');
|
|
63
|
+
if (!seen.has(normKey)) {
|
|
64
|
+
seen.add(normKey);
|
|
65
|
+
constraints.push(cleaned);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return constraints;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Parses `task.md` content into `completed` (`[x]`), `inProgress` (`[/]`), and `pending` (`[ ]`) arrays.
|
|
76
|
+
*/
|
|
77
|
+
export function parseTaskMdChecklist(taskMdContent = '') {
|
|
78
|
+
const completed = [];
|
|
79
|
+
const inProgress = [];
|
|
80
|
+
const pending = [];
|
|
81
|
+
|
|
82
|
+
const lines = String(taskMdContent || '').split(/\r?\n/);
|
|
83
|
+
for (const rawLine of lines) {
|
|
84
|
+
const match = rawLine.match(/^\s*[-*+]\s*\[([ xX/])\]\s*(.+)$/);
|
|
85
|
+
if (!match) continue;
|
|
86
|
+
const marker = match[1].toLowerCase();
|
|
87
|
+
const itemText = match[2].trim();
|
|
88
|
+
if (!itemText) continue;
|
|
89
|
+
if (marker === 'x') {
|
|
90
|
+
completed.push(itemText);
|
|
91
|
+
} else if (marker === '/') {
|
|
92
|
+
inProgress.push(itemText);
|
|
93
|
+
} else {
|
|
94
|
+
pending.push(itemText);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return { completed, inProgress, pending };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function tryCaptureGitDiffStat(cwd) {
|
|
102
|
+
if (!cwd || !fs.existsSync(cwd)) return '';
|
|
103
|
+
try {
|
|
104
|
+
return execFileSync('git', ['diff', '--stat'], {
|
|
105
|
+
cwd,
|
|
106
|
+
encoding: 'utf8',
|
|
107
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
108
|
+
timeout: 2500
|
|
109
|
+
}).trim();
|
|
110
|
+
} catch {
|
|
111
|
+
return '';
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export class ProgressiveCheckpointer {
|
|
116
|
+
constructor(options = {}) {
|
|
117
|
+
this.workspaceDir = options.workspaceDir || process.cwd();
|
|
118
|
+
this.checkpointDir =
|
|
119
|
+
options.checkpointDir ||
|
|
120
|
+
path.join(this.workspaceDir, '.agents', 'cache', 'checkpoints');
|
|
121
|
+
this.maxTokens = Number(options.maxTokens) > 0 ? Number(options.maxTokens) : DEFAULT_MAX_TOKENS;
|
|
122
|
+
this.captureGitStat = options.captureGitStat !== false;
|
|
123
|
+
this.nowFn = typeof options.nowFn === 'function' ? options.nowFn : () => Date.now();
|
|
124
|
+
// sessionId -> Set<string> of crossed band labels ('20%', '35%', '50k_watermark', etc.)
|
|
125
|
+
this.recordedBandsBySession = new Map();
|
|
126
|
+
// sessionId -> Array<checkpointObj>
|
|
127
|
+
this.checkpointsBySession = new Map();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
_getSessionBands(sessionId) {
|
|
131
|
+
const key = String(sessionId || 'default-session');
|
|
132
|
+
if (!this.recordedBandsBySession.has(key)) {
|
|
133
|
+
this.recordedBandsBySession.set(key, new Set());
|
|
134
|
+
}
|
|
135
|
+
return this.recordedBandsBySession.get(key);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
_getSessionCheckpoints(sessionId) {
|
|
139
|
+
const key = String(sessionId || 'default-session');
|
|
140
|
+
if (!this.checkpointsBySession.has(key)) {
|
|
141
|
+
this.checkpointsBySession.set(key, []);
|
|
142
|
+
}
|
|
143
|
+
return this.checkpointsBySession.get(key);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Evaluates current token usage against the 50k soft watermark and 20%/35%/50%/65%/80%
|
|
148
|
+
* fill bands. Takes a zero-token disk snapshot when crossing any new band.
|
|
149
|
+
*/
|
|
150
|
+
evaluateAndSnapshot(input = {}) {
|
|
151
|
+
const startMs = performance.now();
|
|
152
|
+
const sessionId = String(input.sessionId || 'default-session');
|
|
153
|
+
const totalTokens = Math.max(0, Number(input.totalTokens ?? input.contextTokens ?? 0));
|
|
154
|
+
const maxTokens = Number(input.maxTokens) > 0 ? Number(input.maxTokens) : this.maxTokens;
|
|
155
|
+
const fillRatio = maxTokens > 0 ? totalTokens / maxTokens : 0;
|
|
156
|
+
|
|
157
|
+
const crossedBands = this._getSessionBands(sessionId);
|
|
158
|
+
const newlyTriggeredBands = [];
|
|
159
|
+
|
|
160
|
+
// 1. Check 50,000-token soft compaction watermark
|
|
161
|
+
if (totalTokens >= SOFT_WATERMARK_TOKENS && !crossedBands.has('50k_watermark')) {
|
|
162
|
+
newlyTriggeredBands.push('50k_watermark');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// 2. Check percentage fill bands (20%, 35%, 50%, 65%, 80%)
|
|
166
|
+
for (const band of CHECKPOINT_BANDS) {
|
|
167
|
+
const label = `${Math.round(band * 100)}%`;
|
|
168
|
+
if (fillRatio >= band && !crossedBands.has(label)) {
|
|
169
|
+
newlyTriggeredBands.push(label);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (newlyTriggeredBands.length === 0 && !input.forceSnapshot) {
|
|
174
|
+
const latest = this.getLatestCheckpoint(sessionId);
|
|
175
|
+
return {
|
|
176
|
+
snapshotted: false,
|
|
177
|
+
sessionId,
|
|
178
|
+
totalTokens,
|
|
179
|
+
fillRatio: Number(fillRatio.toFixed(4)),
|
|
180
|
+
crossedBands: Array.from(crossedBands),
|
|
181
|
+
latestCheckpoint: latest,
|
|
182
|
+
elapsedMs: Number((performance.now() - startMs).toFixed(3))
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const primaryBandLabel =
|
|
187
|
+
newlyTriggeredBands[newlyTriggeredBands.length - 1] ||
|
|
188
|
+
`manual_${Math.round(fillRatio * 100)}%`;
|
|
189
|
+
|
|
190
|
+
for (const b of newlyTriggeredBands) {
|
|
191
|
+
crossedBands.add(b);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Resolve task.md content if path provided
|
|
195
|
+
let taskMdContent = String(input.taskMdContent || '');
|
|
196
|
+
if (!taskMdContent && input.taskMdPath && fs.existsSync(input.taskMdPath)) {
|
|
197
|
+
try {
|
|
198
|
+
taskMdContent = fs.readFileSync(input.taskMdPath, 'utf8');
|
|
199
|
+
} catch {}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const taskChecklist = parseTaskMdChecklist(taskMdContent);
|
|
203
|
+
|
|
204
|
+
// Extract negative constraints from provided sources
|
|
205
|
+
const constraintSources = [
|
|
206
|
+
...(Array.isArray(input.userConstraints) ? input.userConstraints : [input.userConstraints]),
|
|
207
|
+
input.agentsMdContent || '',
|
|
208
|
+
taskMdContent,
|
|
209
|
+
...(Array.isArray(input.userMessages) ? input.userMessages : [])
|
|
210
|
+
];
|
|
211
|
+
const negativeConstraints = extractNegativeConstraints(constraintSources);
|
|
212
|
+
|
|
213
|
+
// Hash modified files if provided
|
|
214
|
+
const modifiedFiles = (Array.isArray(input.modifiedFiles) ? input.modifiedFiles : []).map((item) => {
|
|
215
|
+
if (typeof item === 'string') {
|
|
216
|
+
let hash = null;
|
|
217
|
+
if (fs.existsSync(item)) {
|
|
218
|
+
try {
|
|
219
|
+
hash = sha256Text(fs.readFileSync(item, 'utf8'));
|
|
220
|
+
} catch {}
|
|
221
|
+
}
|
|
222
|
+
return { path: item, sha256: hash };
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
path: String(item.path || item.filePath || ''),
|
|
226
|
+
sha256: item.sha256 || (item.content !== undefined ? sha256Text(item.content) : null)
|
|
227
|
+
};
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
const gitDiffStat =
|
|
231
|
+
input.gitDiffStat !== undefined
|
|
232
|
+
? String(input.gitDiffStat)
|
|
233
|
+
: this.captureGitStat
|
|
234
|
+
? tryCaptureGitDiffStat(this.workspaceDir)
|
|
235
|
+
: '';
|
|
236
|
+
|
|
237
|
+
const nowMs = this.nowFn();
|
|
238
|
+
const createdAt = new Date(nowMs).toISOString();
|
|
239
|
+
const safeSession = sessionId.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 36);
|
|
240
|
+
const safeBand = primaryBandLabel.replace(/[^a-zA-Z0-9_-]/g, 'pct');
|
|
241
|
+
const fileName = `checkpoint_${safeSession}_${safeBand}.json`;
|
|
242
|
+
const filePath = path.join(this.checkpointDir, fileName);
|
|
243
|
+
|
|
244
|
+
const checkpoint = {
|
|
245
|
+
id: `ckpt-${safeSession}-${safeBand}-${nowMs}`,
|
|
246
|
+
detectorId: 'DET-25',
|
|
247
|
+
sessionId,
|
|
248
|
+
bandLabel: primaryBandLabel,
|
|
249
|
+
triggeredBands: newlyTriggeredBands.length > 0 ? newlyTriggeredBands : [primaryBandLabel],
|
|
250
|
+
totalTokens,
|
|
251
|
+
maxTokens,
|
|
252
|
+
fillRatio: Number(fillRatio.toFixed(4)),
|
|
253
|
+
taskChecklist,
|
|
254
|
+
negativeConstraints,
|
|
255
|
+
modifiedFiles,
|
|
256
|
+
gitDiffStat,
|
|
257
|
+
filePath,
|
|
258
|
+
createdAt,
|
|
259
|
+
zeroTokenOverhead: true
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
if (input.writeToDisk !== false) {
|
|
263
|
+
atomicWriteFileSync(filePath, JSON.stringify(checkpoint, null, 2) + '\n', { encoding: 'utf8' });
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const sessionList = this._getSessionCheckpoints(sessionId);
|
|
267
|
+
sessionList.push(checkpoint);
|
|
268
|
+
|
|
269
|
+
return {
|
|
270
|
+
snapshotted: true,
|
|
271
|
+
sessionId,
|
|
272
|
+
bandLabel: primaryBandLabel,
|
|
273
|
+
triggeredBands: checkpoint.triggeredBands,
|
|
274
|
+
totalTokens,
|
|
275
|
+
fillRatio: checkpoint.fillRatio,
|
|
276
|
+
crossedBands: Array.from(crossedBands),
|
|
277
|
+
checkpoint,
|
|
278
|
+
latestCheckpoint: checkpoint,
|
|
279
|
+
elapsedMs: Number((performance.now() - startMs).toFixed(3))
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
getLatestCheckpoint(sessionId = 'default-session') {
|
|
284
|
+
const list = this._getSessionCheckpoints(sessionId);
|
|
285
|
+
if (list.length > 0) {
|
|
286
|
+
return list[list.length - 1];
|
|
287
|
+
}
|
|
288
|
+
// Check disk fallback if checkpointDir has matching files
|
|
289
|
+
if (!fs.existsSync(this.checkpointDir)) return null;
|
|
290
|
+
const safeSession = String(sessionId).replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 36);
|
|
291
|
+
try {
|
|
292
|
+
const files = fs
|
|
293
|
+
.readdirSync(this.checkpointDir)
|
|
294
|
+
.filter((f) => f.startsWith(`checkpoint_${safeSession}_`) && f.endsWith('.json'))
|
|
295
|
+
.map((f) => path.join(this.checkpointDir, f));
|
|
296
|
+
if (files.length === 0) return null;
|
|
297
|
+
files.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);
|
|
298
|
+
const parsed = JSON.parse(fs.readFileSync(files[0], 'utf8'));
|
|
299
|
+
list.push(parsed);
|
|
300
|
+
return parsed;
|
|
301
|
+
} catch {
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
listCheckpoints(sessionId = 'default-session') {
|
|
307
|
+
return [...this._getSessionCheckpoints(sessionId)];
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Compares a post-compaction `<CONTEXT_SUMMARY>` (or active context text) against
|
|
312
|
+
* the latest disk checkpoint for `sessionId` to detect Negative Constraint Evaporation
|
|
313
|
+
* or lost active (`[/]`) task items.
|
|
314
|
+
*/
|
|
315
|
+
detectConstraintEvaporation(compactedSummaryText = '', sessionId = 'default-session', explicitCheckpoint = null) {
|
|
316
|
+
const latest = explicitCheckpoint || this.getLatestCheckpoint(sessionId);
|
|
317
|
+
if (!latest) {
|
|
318
|
+
return {
|
|
319
|
+
evaporated: false,
|
|
320
|
+
missingConstraints: [],
|
|
321
|
+
missingActiveTasks: [],
|
|
322
|
+
preservedConstraintsCount: 0,
|
|
323
|
+
recoveryPrompt: '',
|
|
324
|
+
latestCheckpoint: null
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const normSummary = String(compactedSummaryText || '').toLowerCase().replace(/\s+/g, ' ');
|
|
329
|
+
const missingConstraints = [];
|
|
330
|
+
let preservedConstraintsCount = 0;
|
|
331
|
+
|
|
332
|
+
for (const constraint of latest.negativeConstraints || []) {
|
|
333
|
+
const normConstraint = String(constraint).toLowerCase().replace(/\s+/g, ' ');
|
|
334
|
+
// Check either full substring or significant tokens (>= 60% of words >= 4 chars)
|
|
335
|
+
if (normSummary.includes(normConstraint)) {
|
|
336
|
+
preservedConstraintsCount++;
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
const stopWords = new Set([
|
|
340
|
+
'never', 'must', 'always', 'strictly', 'forbidden', 'when', 'with',
|
|
341
|
+
'from', 'that', 'this', 'render', 'preserve', 'across', 'button',
|
|
342
|
+
'clickable', 'make', 'keep', 'ensure', 'into', 'only'
|
|
343
|
+
]);
|
|
344
|
+
const summaryAlpha = normSummary.replace(/[^a-z0-9\s]/g, ' ');
|
|
345
|
+
const keyWords = normConstraint
|
|
346
|
+
.replace(/[^a-z0-9\s]/g, ' ')
|
|
347
|
+
.split(/\s+/)
|
|
348
|
+
.filter((w) => w.length >= 4 && !stopWords.has(w));
|
|
349
|
+
|
|
350
|
+
if (keyWords.length > 0) {
|
|
351
|
+
const matchedWords = keyWords.filter((w) => summaryAlpha.includes(w));
|
|
352
|
+
if (matchedWords.length / keyWords.length >= 0.5) {
|
|
353
|
+
preservedConstraintsCount++;
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
missingConstraints.push(constraint);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const missingActiveTasks = [];
|
|
361
|
+
for (const activeItem of latest.taskChecklist?.inProgress || []) {
|
|
362
|
+
const normTask = String(activeItem).toLowerCase().replace(/\s+/g, ' ');
|
|
363
|
+
const taskWords = normTask
|
|
364
|
+
.replace(/[^a-z0-9\s/_-]/g, ' ')
|
|
365
|
+
.split(/\s+/)
|
|
366
|
+
.filter((w) => w.length >= 4);
|
|
367
|
+
if (taskWords.length === 0) continue;
|
|
368
|
+
const matched = taskWords.filter((w) => normSummary.includes(w));
|
|
369
|
+
if (matched.length / taskWords.length < 0.6) {
|
|
370
|
+
missingActiveTasks.push(activeItem);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const evaporated = missingConstraints.length > 0 || missingActiveTasks.length > 0;
|
|
375
|
+
let recoveryPrompt = '';
|
|
376
|
+
|
|
377
|
+
if (evaporated) {
|
|
378
|
+
const lines = [
|
|
379
|
+
`[Checkpoint Continuity Sync (${latest.bandLabel} snapshot)]: Please restore the following active session constraints and in-progress tasks that were truncated during compaction:`
|
|
380
|
+
];
|
|
381
|
+
if (missingActiveTasks.length > 0) {
|
|
382
|
+
lines.push('Active In-Progress Task (`[/]`):');
|
|
383
|
+
for (const t of missingActiveTasks) {
|
|
384
|
+
lines.push(`- [/] ${t}`);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
if (missingConstraints.length > 0) {
|
|
388
|
+
lines.push('Mandatory Invariants:');
|
|
389
|
+
for (const c of missingConstraints) {
|
|
390
|
+
lines.push(`- ${c}`);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
recoveryPrompt = lines.join('\n');
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
return {
|
|
397
|
+
evaporated,
|
|
398
|
+
detectorId: 'DET-25',
|
|
399
|
+
bandLabel: latest.bandLabel,
|
|
400
|
+
missingConstraints,
|
|
401
|
+
missingActiveTasks,
|
|
402
|
+
preservedConstraintsCount,
|
|
403
|
+
recoveryPrompt,
|
|
404
|
+
latestCheckpoint: latest
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Rank 4 (`DET-17`): Anchors zero-token progressive State Baton snapshots to
|
|
410
|
+
* Antigravity's 70,000-token Cascade ceiling (`14k`, `25k`, `35k`, `45k`, `56k`),
|
|
411
|
+
* persists atomically to gitignored `.agents/cache/state_baton.json`, suppresses
|
|
412
|
+
* premature `/compact` when cache hit ratio `> 96%` below `50,000` tokens, and writes
|
|
413
|
+
* `docs/HANDOFF_<timestamp>.md` ONLY on explicit click or `Turn >= 45` in `AUTO_PILOT`.
|
|
414
|
+
*/
|
|
415
|
+
evaluateCascadeBaton(input = {}) {
|
|
416
|
+
return evaluateCascadeBatonCheckpoint(input, {
|
|
417
|
+
workspaceDir: this.workspaceDir,
|
|
418
|
+
nowFn: this.nowFn,
|
|
419
|
+
sessionBandsMap: this.recordedBandsBySession
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Ensures `.agents/cache/` is listed in `<workspaceDir>/.git/info/exclude` when a git
|
|
426
|
+
* repository is present so rolling State Baton snapshots never dirty `git status`.
|
|
427
|
+
*/
|
|
428
|
+
export function ensureGitInfoExcludeForAgentsCache(workspaceDir) {
|
|
429
|
+
if (!workspaceDir) return false;
|
|
430
|
+
const excludePath = path.join(workspaceDir, '.git', 'info', 'exclude');
|
|
431
|
+
if (!fs.existsSync(excludePath)) return false;
|
|
432
|
+
try {
|
|
433
|
+
const raw = fs.readFileSync(excludePath, 'utf8');
|
|
434
|
+
const lines = raw.split(/\r?\n/).map((l) => l.trim());
|
|
435
|
+
if (lines.includes('.agents/') || lines.includes('.agents/cache/') || lines.includes('.agents/cache')) {
|
|
436
|
+
return true;
|
|
437
|
+
}
|
|
438
|
+
const prefix = raw.endsWith('\n') || raw.length === 0 ? raw : `${raw}\n`;
|
|
439
|
+
atomicWriteFileSync(excludePath, `${prefix}.agents/cache/\n`, { encoding: 'utf8' });
|
|
440
|
+
return true;
|
|
441
|
+
} catch {
|
|
442
|
+
return false;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function formatCompactUtcStamp(nowMs = Date.now()) {
|
|
447
|
+
const iso = new Date(nowMs).toISOString(); // YYYY-MM-DDTHH:MM:SS.sssZ
|
|
448
|
+
return iso
|
|
449
|
+
.slice(0, 19)
|
|
450
|
+
.replace(/[-:]/g, () => '')
|
|
451
|
+
.replace('T', () => '_');
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
export function evaluateCascadeBatonCheckpoint(input = {}, options = {}) {
|
|
455
|
+
const workspaceDir = options.workspaceDir || input.workspaceDir || process.cwd();
|
|
456
|
+
const nowFn = typeof options.nowFn === 'function' ? options.nowFn : () => Date.now();
|
|
457
|
+
const sessionId = String(input.sessionId || 'default-session');
|
|
458
|
+
const currentTokens = Math.max(0, Number(input.currentTokens ?? input.totalTokens ?? 0));
|
|
459
|
+
const ceilingTokens = Number(input.ceilingTokens) > 0
|
|
460
|
+
? Number(input.ceilingTokens)
|
|
461
|
+
: CASCADE_COMPACTION_CEILING_TOKENS;
|
|
462
|
+
const cacheHitRatio = Number(input.cacheHitRatio ?? input.cacheHitRate ?? 0);
|
|
463
|
+
const turn = Math.max(0, Math.round(Number(input.turn ?? input.turnCount ?? 0)));
|
|
464
|
+
const flightMode = String(input.flightMode || 'COACH').toUpperCase();
|
|
465
|
+
|
|
466
|
+
const mapKey = `cascade70k:${sessionId}`;
|
|
467
|
+
const existingSet = options.sessionBandsMap instanceof Map
|
|
468
|
+
? (options.sessionBandsMap.get(mapKey) || new Set())
|
|
469
|
+
: new Set(Array.isArray(input.crossedBands) ? input.crossedBands : []);
|
|
470
|
+
|
|
471
|
+
const det17 = evaluateDet17CascadeCheckpoints({
|
|
472
|
+
currentTokens,
|
|
473
|
+
ceilingTokens,
|
|
474
|
+
crossedBands: Array.from(existingSet),
|
|
475
|
+
cacheHitRatio
|
|
476
|
+
});
|
|
477
|
+
|
|
478
|
+
if (options.sessionBandsMap instanceof Map) {
|
|
479
|
+
options.sessionBandsMap.set(mapKey, new Set(det17.crossedBands));
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
const stateBatonPath = input.stateBatonPath || path.join(workspaceDir, '.agents', 'cache', 'state_baton.json');
|
|
483
|
+
const highestNewBand = det17.newlyCrossedBands.length > 0
|
|
484
|
+
? det17.newlyCrossedBands[det17.newlyCrossedBands.length - 1].label
|
|
485
|
+
: (det17.crossedBands[det17.crossedBands.length - 1] || 'nominal');
|
|
486
|
+
|
|
487
|
+
const baton = createStateBaton({
|
|
488
|
+
sessionId,
|
|
489
|
+
bandLabel: highestNewBand,
|
|
490
|
+
turn,
|
|
491
|
+
currentTokens,
|
|
492
|
+
ceilingTokens,
|
|
493
|
+
updatedAt: new Date(nowFn()).toISOString(),
|
|
494
|
+
activeGoal: input.activeGoal || 'Continue active workspace implementation',
|
|
495
|
+
workingSetFiles: input.workingSetFiles || [],
|
|
496
|
+
verifiedInvariants: input.verifiedInvariants || [],
|
|
497
|
+
negativeConstraints: input.negativeConstraints || extractNegativeConstraints([
|
|
498
|
+
...(Array.isArray(input.userConstraints) ? input.userConstraints : [input.userConstraints]),
|
|
499
|
+
input.agentsMdContent || ''
|
|
500
|
+
]),
|
|
501
|
+
deadEnds: input.deadEnds || []
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
let persistedBaton = false;
|
|
505
|
+
if ((det17.shouldWriteStateBaton || input.forceSnapshot === true) && input.writeToDisk !== false) {
|
|
506
|
+
ensureGitInfoExcludeForAgentsCache(workspaceDir);
|
|
507
|
+
atomicWriteFileSync(stateBatonPath, JSON.stringify(baton, null, 2) + '\n', { encoding: 'utf8' });
|
|
508
|
+
persistedBaton = true;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// Gate docs/HANDOFF_<timestamp>.md strictly to explicit Export Handoff click OR Turn >= 45 in AUTO_PILOT
|
|
512
|
+
const explicitExportClick = input.explicitExportClick === true;
|
|
513
|
+
const autoPilotTurnGate = flightMode === 'AUTO_PILOT' && turn >= 45 && input.alreadyExportedHandoff !== true;
|
|
514
|
+
let handoffExported = false;
|
|
515
|
+
let handoffPath = null;
|
|
516
|
+
|
|
517
|
+
if ((explicitExportClick || autoPilotTurnGate) && input.writeToDisk !== false) {
|
|
518
|
+
const stamp = input.timestampStamp || formatCompactUtcStamp(nowFn());
|
|
519
|
+
const docsDir = input.docsDir || path.join(workspaceDir, 'docs');
|
|
520
|
+
handoffPath = path.join(docsDir, `HANDOFF_${stamp}.md`);
|
|
521
|
+
const trigger = explicitExportClick ? 'explicit_export_click' : 'autopilot_turn_45';
|
|
522
|
+
const md = formatHandoffMarkdown(baton, { trigger });
|
|
523
|
+
atomicWriteFileSync(handoffPath, md, { encoding: 'utf8' });
|
|
524
|
+
handoffExported = true;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
return {
|
|
528
|
+
detectorId: 'DET-17',
|
|
529
|
+
sessionId,
|
|
530
|
+
currentTokens,
|
|
531
|
+
ceilingTokens,
|
|
532
|
+
newlyCrossedBands: det17.newlyCrossedBands,
|
|
533
|
+
crossedBands: det17.crossedBands,
|
|
534
|
+
suppressPrematureCompact: det17.suppressPrematureCompact,
|
|
535
|
+
persistedBaton,
|
|
536
|
+
stateBatonPath,
|
|
537
|
+
baton,
|
|
538
|
+
coldResumePrompt: formatColdResumeBatonPrompt(baton),
|
|
539
|
+
handoffExported,
|
|
540
|
+
handoffPath
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
export {
|
|
545
|
+
CASCADE_COMPACTION_CEILING_TOKENS,
|
|
546
|
+
CASCADE_CHECKPOINT_BANDS,
|
|
547
|
+
createStateBaton,
|
|
548
|
+
validateStateBaton
|
|
549
|
+
};
|
|
550
|
+
|
|
551
|
+
export default ProgressiveCheckpointer;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phase 3.2: Advisory TDD Planning Gate & Mega-Prompt Decomposer (`DET-12`)
|
|
3
|
+
* (`src/core/coach/prompt_decomposer_coach.mjs`)
|
|
4
|
+
*
|
|
5
|
+
* Feature #13:
|
|
6
|
+
* - Detects multi-objective "mega-prompts" (>= 3 distinct mutation verbs, >= 4 target
|
|
7
|
+
* files/modules, or >= 120 words with multiple objectives) when no `implementation_plan.md`
|
|
8
|
+
* or `/plan` workflow is active.
|
|
9
|
+
* - Operates strictly in non-blocking Advisory Mode (`COACH`): never hard-blocks experienced
|
|
10
|
+
* developers, but recommends `/plan` or `/grill-me` with a structured 3-step decomposition.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const DECOMPOSER_CONSTANTS = Object.freeze({
|
|
14
|
+
MIN_MUTATION_VERBS: 3,
|
|
15
|
+
MIN_TARGET_FILES: 4,
|
|
16
|
+
MEGA_PROMPT_WORD_THRESHOLD: 120,
|
|
17
|
+
MIN_BULLET_OBJECTIVES: 3
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
const MUTATION_VERB_REGEX =
|
|
21
|
+
/\b(implement|refactor|migrate|redesign|create|build|rewrite|replace|integrate|convert|upgrade|overhaul|extract|deprecate|architect)\b/gi;
|
|
22
|
+
|
|
23
|
+
const FILE_OR_PATH_REGEX =
|
|
24
|
+
/\b(?:[a-zA-Z0-9_-]+\/)+[a-zA-Z0-9_.-]+\.[a-z0-9]{1,6}\b|\b[a-zA-Z0-9_-]+\.(?:mjs|cjs|js|ts|tsx|jsx|py|go|rs|java|html|css|sql|json|md)\b/g;
|
|
25
|
+
|
|
26
|
+
export function analyzePromptSprawl(promptText = '', options = {}) {
|
|
27
|
+
const raw = String(promptText || '').trim();
|
|
28
|
+
if (!raw) {
|
|
29
|
+
return {
|
|
30
|
+
isMegaPrompt: false,
|
|
31
|
+
detectorId: 'DET-26',
|
|
32
|
+
blocking: false,
|
|
33
|
+
wordCount: 0,
|
|
34
|
+
distinctVerbCount: 0,
|
|
35
|
+
distinctVerbs: [],
|
|
36
|
+
targetFileCount: 0,
|
|
37
|
+
targetFiles: [],
|
|
38
|
+
bulletObjectiveCount: 0,
|
|
39
|
+
hasPlanCommand: false,
|
|
40
|
+
recommendedSlashCommand: null,
|
|
41
|
+
decomposedStages: [],
|
|
42
|
+
advisoryPrompt: ''
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const hasPlanCommand =
|
|
47
|
+
Boolean(options.hasApprovedPlan) ||
|
|
48
|
+
/(?:^|\s)(\/plan|\/grill-me|implementation_plan\.md)\b/i.test(raw);
|
|
49
|
+
|
|
50
|
+
const isReadOnlyAudit =
|
|
51
|
+
/\b(read-only(?:\s+evaluation|\s+audit|\s+mode|\s+inspection)?|do\s+not\s+(?:edit|modify|write)|never\s+(?:edit|modify)|audit\s+only)\b/i.test(raw);
|
|
52
|
+
|
|
53
|
+
const words = raw.split(/\s+/).filter(Boolean);
|
|
54
|
+
const wordCount = words.length;
|
|
55
|
+
|
|
56
|
+
const verbMatches = raw.match(MUTATION_VERB_REGEX) || [];
|
|
57
|
+
const distinctVerbs = Array.from(new Set(verbMatches.map((v) => v.toLowerCase())));
|
|
58
|
+
|
|
59
|
+
const fileMatches = raw.match(FILE_OR_PATH_REGEX) || [];
|
|
60
|
+
const explicitFiles = Array.isArray(options.referencedFiles) ? options.referencedFiles : [];
|
|
61
|
+
const targetFiles = Array.from(
|
|
62
|
+
new Set([...fileMatches, ...explicitFiles].map((f) => String(f).trim()).filter(Boolean))
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
const lines = raw.split(/\r?\n/);
|
|
66
|
+
const bulletLines = lines
|
|
67
|
+
.map((l) => l.trim())
|
|
68
|
+
.filter((l) => /^([-*+]|\d+[.)])\s+\S+/.test(l));
|
|
69
|
+
const bulletObjectiveCount = bulletLines.length;
|
|
70
|
+
|
|
71
|
+
const ClauseConjunctions = (raw.match(/\b(and\s+also|then\s+also|additionally|furthermore|finally)\b/gi) || []).length;
|
|
72
|
+
|
|
73
|
+
const triggersVerbSprawl =
|
|
74
|
+
distinctVerbs.length >= DECOMPOSER_CONSTANTS.MIN_MUTATION_VERBS &&
|
|
75
|
+
(targetFiles.length >= 2 || bulletObjectiveCount >= 2 || wordCount >= 45 || ClauseConjunctions >= 1);
|
|
76
|
+
|
|
77
|
+
const triggersFileSprawl = targetFiles.length >= DECOMPOSER_CONSTANTS.MIN_TARGET_FILES;
|
|
78
|
+
|
|
79
|
+
const triggersLengthSprawl =
|
|
80
|
+
wordCount >= DECOMPOSER_CONSTANTS.MEGA_PROMPT_WORD_THRESHOLD &&
|
|
81
|
+
bulletObjectiveCount >= DECOMPOSER_CONSTANTS.MIN_BULLET_OBJECTIVES;
|
|
82
|
+
|
|
83
|
+
const isMegaPrompt =
|
|
84
|
+
!hasPlanCommand && !isReadOnlyAudit && (triggersVerbSprawl || triggersFileSprawl || triggersLengthSprawl);
|
|
85
|
+
|
|
86
|
+
if (!isMegaPrompt) {
|
|
87
|
+
return {
|
|
88
|
+
isMegaPrompt: false,
|
|
89
|
+
detectorId: 'DET-26',
|
|
90
|
+
blocking: false,
|
|
91
|
+
wordCount,
|
|
92
|
+
distinctVerbCount: distinctVerbs.length,
|
|
93
|
+
distinctVerbs,
|
|
94
|
+
targetFileCount: targetFiles.length,
|
|
95
|
+
targetFiles,
|
|
96
|
+
bulletObjectiveCount,
|
|
97
|
+
hasPlanCommand,
|
|
98
|
+
recommendedSlashCommand: null,
|
|
99
|
+
decomposedStages: [],
|
|
100
|
+
advisoryPrompt: ''
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const primaryTargets =
|
|
105
|
+
targetFiles.length > 0 ? targetFiles.slice(0, 4).join(', ') : 'target modules';
|
|
106
|
+
|
|
107
|
+
const decomposedStages = [
|
|
108
|
+
`Phase 1 (Contract & Plan): Align on interfaces and edge cases for ${primaryTargets} in implementation_plan.md before mutating files.`,
|
|
109
|
+
`Phase 2 (Scoped Implementation): Execute changes incrementally (${distinctVerbs.slice(0, 3).join(' -> ') || 'step-by-step'}) with pause gates.`,
|
|
110
|
+
`Phase 3 (TDD Verification): Run targeted unit tests for ${primaryTargets} before expanding scope.`
|
|
111
|
+
];
|
|
112
|
+
|
|
113
|
+
const advisoryPrompt = `/plan Break this request into a phased implementation plan with verification gates for ${primaryTargets}:\n\n${raw}`;
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
isMegaPrompt: true,
|
|
117
|
+
detectorId: 'DET-26',
|
|
118
|
+
blocking: false, // Strictly advisory in COACH mode
|
|
119
|
+
mode: 'ADVISORY_COACH',
|
|
120
|
+
wordCount,
|
|
121
|
+
distinctVerbCount: distinctVerbs.length,
|
|
122
|
+
distinctVerbs,
|
|
123
|
+
targetFileCount: targetFiles.length,
|
|
124
|
+
targetFiles,
|
|
125
|
+
bulletObjectiveCount,
|
|
126
|
+
hasPlanCommand,
|
|
127
|
+
recommendedSlashCommand: '/plan',
|
|
128
|
+
alternativeSlashCommand: '/grill-me',
|
|
129
|
+
decomposedStages,
|
|
130
|
+
advisoryPrompt,
|
|
131
|
+
message: `💡 DET-26 Mega-Prompt Advisory: Detected ${distinctVerbs.length} action verbs across ${targetFiles.length || bulletObjectiveCount || 'multiple'} targets. Consider running /plan or /grill-me first to prevent unaligned multi-file edits.`
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export class PromptDecomposerCoach {
|
|
136
|
+
evaluate(promptText = '', options = {}) {
|
|
137
|
+
return analyzePromptSprawl(promptText, options);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export default PromptDecomposerCoach;
|