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,338 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/control/callTree.mjs
|
|
3
|
+
* Real-Time Call-Tree & Execution Span Tracking (Feature 24).
|
|
4
|
+
*
|
|
5
|
+
* Implements in-process span lifecycle tracking, parent-child call-tree assembly,
|
|
6
|
+
* critical path calculation, ASCII tree rendering, and USTF v1-compliant flamegraph data.
|
|
7
|
+
* Pure ESM with strictly 0 node:* imports adhering to Claude Mod Laws 1–5.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Creates an execution span compliant with USTF v1 span schema.
|
|
12
|
+
*
|
|
13
|
+
* @param {object} [options]
|
|
14
|
+
* @returns {object}
|
|
15
|
+
*/
|
|
16
|
+
export function createSpan(options = {}) {
|
|
17
|
+
const now = typeof options.startTimeMs === 'number'
|
|
18
|
+
? options.startTimeMs
|
|
19
|
+
: (typeof options.startMs === 'number' ? options.startMs : Date.now());
|
|
20
|
+
|
|
21
|
+
const spanId = options.spanId || options.toolCallId || ('span-' + Math.random().toString(36).slice(2, 10));
|
|
22
|
+
const name = options.name || options.toolName || 'anonymous';
|
|
23
|
+
const kind = options.kind || 'tool';
|
|
24
|
+
const parentSpanId = options.parentSpanId !== undefined ? options.parentSpanId : null;
|
|
25
|
+
|
|
26
|
+
const durationMs = typeof options.durationMs === 'number'
|
|
27
|
+
? options.durationMs
|
|
28
|
+
: (typeof options.duration === 'number' ? options.duration : null);
|
|
29
|
+
|
|
30
|
+
const endTimeMs = durationMs !== null ? now + durationMs : (options.endTimeMs ?? options.endMs ?? null);
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
spanId,
|
|
34
|
+
parentSpanId,
|
|
35
|
+
kind,
|
|
36
|
+
name,
|
|
37
|
+
startTimeMs: now,
|
|
38
|
+
endTimeMs,
|
|
39
|
+
durationMs,
|
|
40
|
+
status: options.status || 'ok',
|
|
41
|
+
metadata: options.metadata ? { ...options.metadata } : {},
|
|
42
|
+
children: [],
|
|
43
|
+
// Backward compatibility aliases
|
|
44
|
+
toolCallId: spanId,
|
|
45
|
+
toolName: name,
|
|
46
|
+
startMs: now,
|
|
47
|
+
endMs: endTimeMs
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Ends an in-flight execution span and computes its duration.
|
|
53
|
+
*
|
|
54
|
+
* @param {object} span
|
|
55
|
+
* @param {object} [options]
|
|
56
|
+
* @returns {object}
|
|
57
|
+
*/
|
|
58
|
+
export function endSpan(span, options = {}) {
|
|
59
|
+
if (!span || typeof span !== 'object') return span;
|
|
60
|
+
|
|
61
|
+
const end = options.endTimeMs ?? options.endMs ?? (
|
|
62
|
+
typeof options.durationMs === 'number'
|
|
63
|
+
? (span.startTimeMs + options.durationMs)
|
|
64
|
+
: Date.now()
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
const durationMs = typeof options.durationMs === 'number'
|
|
68
|
+
? Math.max(0, options.durationMs)
|
|
69
|
+
: Math.max(0, Number((end - span.startTimeMs).toFixed(2)));
|
|
70
|
+
|
|
71
|
+
span.endTimeMs = end;
|
|
72
|
+
span.endMs = end;
|
|
73
|
+
span.durationMs = durationMs;
|
|
74
|
+
|
|
75
|
+
if (options.status) {
|
|
76
|
+
span.status = options.status;
|
|
77
|
+
}
|
|
78
|
+
if (options.error) {
|
|
79
|
+
span.error = String(options.error);
|
|
80
|
+
if (!options.status) span.status = 'error';
|
|
81
|
+
}
|
|
82
|
+
if (options.metadata) {
|
|
83
|
+
span.metadata = { ...span.metadata, ...options.metadata };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return span;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Closes any unclosed spans in an array (e.g. at turn completion).
|
|
91
|
+
*
|
|
92
|
+
* @param {Array<object>} spans
|
|
93
|
+
* @param {object} [options]
|
|
94
|
+
* @returns {Array<object>}
|
|
95
|
+
*/
|
|
96
|
+
export function closeUnclosedSpans(spans, options = {}) {
|
|
97
|
+
if (!Array.isArray(spans)) return [];
|
|
98
|
+
const defaultEndTime = options.endTimeMs ?? Date.now();
|
|
99
|
+
const status = options.status || 'ok';
|
|
100
|
+
|
|
101
|
+
for (const span of spans) {
|
|
102
|
+
if (span && typeof span === 'object' && (span.durationMs == null || span.endTimeMs == null)) {
|
|
103
|
+
const fallbackEnd = span.startTimeMs ? Math.max(span.startTimeMs, defaultEndTime) : defaultEndTime;
|
|
104
|
+
endSpan(span, { endTimeMs: fallbackEnd, status });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return spans;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Assembles a flat list of spans into a hierarchical tree.
|
|
112
|
+
* Iterative implementation avoids stack overflow even on 50+ nested levels.
|
|
113
|
+
*
|
|
114
|
+
* @param {Array<object>} spans
|
|
115
|
+
* @returns {Array<object>} Root spans with populated .children
|
|
116
|
+
*/
|
|
117
|
+
export function buildCallTree(spans) {
|
|
118
|
+
if (!Array.isArray(spans) || spans.length === 0) return [];
|
|
119
|
+
|
|
120
|
+
const spanMap = new Map();
|
|
121
|
+
const roots = [];
|
|
122
|
+
|
|
123
|
+
// Clone spans to avoid mutating original objects
|
|
124
|
+
for (const s of spans) {
|
|
125
|
+
if (!s || typeof s !== 'object') continue;
|
|
126
|
+
const id = s.spanId || s.toolCallId;
|
|
127
|
+
if (!id) continue;
|
|
128
|
+
spanMap.set(id, {
|
|
129
|
+
...s,
|
|
130
|
+
spanId: id,
|
|
131
|
+
children: []
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
for (const node of spanMap.values()) {
|
|
136
|
+
const parentId = node.parentSpanId;
|
|
137
|
+
if (parentId && spanMap.has(parentId)) {
|
|
138
|
+
spanMap.get(parentId).children.push(node);
|
|
139
|
+
} else {
|
|
140
|
+
roots.push(node);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return roots;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Computes the critical path duration across sequential and parallel execution spans.
|
|
149
|
+
* Dynamic programming over topological intervals:
|
|
150
|
+
* criticalPath[i] = duration[i] + max({ criticalPath[j] for j where end[j] <= start[i] } union {0})
|
|
151
|
+
*
|
|
152
|
+
* @param {Array<object>} spans
|
|
153
|
+
* @returns {number} Critical path duration in milliseconds
|
|
154
|
+
*/
|
|
155
|
+
export function computeCriticalPath(spans) {
|
|
156
|
+
if (!Array.isArray(spans) || spans.length === 0) return 0;
|
|
157
|
+
|
|
158
|
+
// Filter valid spans and sort by start timestamp
|
|
159
|
+
const normalized = spans
|
|
160
|
+
.filter((s) => s && typeof s === 'object')
|
|
161
|
+
.map((s) => {
|
|
162
|
+
const start = typeof s.startTimeMs === 'number' ? s.startTimeMs : (typeof s.startMs === 'number' ? s.startMs : 0);
|
|
163
|
+
const dur = typeof s.durationMs === 'number' ? s.durationMs : 0;
|
|
164
|
+
const end = typeof s.endTimeMs === 'number' ? s.endTimeMs : (typeof s.endMs === 'number' ? s.endMs : (start + dur));
|
|
165
|
+
return { start, dur, end };
|
|
166
|
+
})
|
|
167
|
+
.sort((a, b) => a.start - b.start);
|
|
168
|
+
|
|
169
|
+
if (normalized.length === 0) return 0;
|
|
170
|
+
|
|
171
|
+
const n = normalized.length;
|
|
172
|
+
const cp = new Array(n).fill(0);
|
|
173
|
+
let maxCriticalPath = 0;
|
|
174
|
+
|
|
175
|
+
for (let i = 0; i < n; i++) {
|
|
176
|
+
const curr = normalized[i];
|
|
177
|
+
let maxPredecessorCp = 0;
|
|
178
|
+
|
|
179
|
+
for (let j = 0; j < i; j++) {
|
|
180
|
+
if (normalized[j].end <= curr.start) {
|
|
181
|
+
if (cp[j] > maxPredecessorCp) {
|
|
182
|
+
maxPredecessorCp = cp[j];
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
cp[i] = curr.dur + maxPredecessorCp;
|
|
188
|
+
if (cp[i] > maxCriticalPath) {
|
|
189
|
+
maxCriticalPath = cp[i];
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return maxCriticalPath;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Renders an ASCII representation of the call tree or USTF trajectory.
|
|
198
|
+
*
|
|
199
|
+
* @param {object|Array} trajectoryOrTree
|
|
200
|
+
* @param {object} [options]
|
|
201
|
+
* @returns {string}
|
|
202
|
+
*/
|
|
203
|
+
export function renderCallTree(trajectoryOrTree, options = {}) {
|
|
204
|
+
if (!trajectoryOrTree) return '';
|
|
205
|
+
|
|
206
|
+
// Case 1: USTF trajectory with turns
|
|
207
|
+
if (trajectoryOrTree.turns && Array.isArray(trajectoryOrTree.turns)) {
|
|
208
|
+
const sessionId = trajectoryOrTree.sessionId || 'session-default';
|
|
209
|
+
const host = trajectoryOrTree.host || 'antigravity';
|
|
210
|
+
let out = `Session: ${sessionId} [${host}]\n`;
|
|
211
|
+
|
|
212
|
+
for (let tIdx = 0; tIdx < trajectoryOrTree.turns.length; tIdx++) {
|
|
213
|
+
const turn = trajectoryOrTree.turns[tIdx];
|
|
214
|
+
if (!turn || typeof turn !== 'object') continue;
|
|
215
|
+
const isLastTurn = tIdx === trajectoryOrTree.turns.length - 1;
|
|
216
|
+
const turnDuration = turn.durationMs ?? 0;
|
|
217
|
+
const turnIndex = turn.turnIndex ?? (tIdx + 1);
|
|
218
|
+
|
|
219
|
+
out += `└── Turn ${turnIndex} [${turnDuration}ms]\n`;
|
|
220
|
+
|
|
221
|
+
const toolSpans = Array.isArray(turn.toolSpans) ? turn.toolSpans : [];
|
|
222
|
+
for (let sIdx = 0; sIdx < toolSpans.length; sIdx++) {
|
|
223
|
+
const s = toolSpans[sIdx];
|
|
224
|
+
if (!s || typeof s !== 'object') continue;
|
|
225
|
+
const isLastSpan = sIdx === toolSpans.length - 1;
|
|
226
|
+
const branch = isLastSpan ? ' └── ' : ' ├── ';
|
|
227
|
+
const name = s.toolName || s.name || 'tool';
|
|
228
|
+
const dur = s.durationMs ?? 0;
|
|
229
|
+
const status = s.status || 'ok';
|
|
230
|
+
out += `${branch}${name} [${dur}ms] (${status})\n`;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Case 2: Tree of spans (either roots array or single root)
|
|
237
|
+
const roots = Array.isArray(trajectoryOrTree) ? trajectoryOrTree : [trajectoryOrTree];
|
|
238
|
+
let out = '';
|
|
239
|
+
|
|
240
|
+
// Iterative DFS stack: { node, depth, isLast, prefix }
|
|
241
|
+
const stack = [];
|
|
242
|
+
for (let i = roots.length - 1; i >= 0; i--) {
|
|
243
|
+
stack.push({ node: roots[i], depth: 0, isLast: i === roots.length - 1, prefix: '' });
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
while (stack.length > 0) {
|
|
247
|
+
const { node, depth, isLast, prefix } = stack.pop();
|
|
248
|
+
if (!node || typeof node !== 'object') continue;
|
|
249
|
+
|
|
250
|
+
const branch = depth === 0 ? '' : (isLast ? '└── ' : '├── ');
|
|
251
|
+
const name = node.name || node.toolName || 'span';
|
|
252
|
+
const dur = node.durationMs ?? 0;
|
|
253
|
+
const status = node.status ? ` (${node.status})` : '';
|
|
254
|
+
|
|
255
|
+
out += `${prefix}${branch}${name} [${dur}ms]${status}\n`;
|
|
256
|
+
|
|
257
|
+
const children = Array.isArray(node.children) ? node.children : [];
|
|
258
|
+
const childPrefix = depth === 0 ? '' : (prefix + (isLast ? ' ' : '│ '));
|
|
259
|
+
|
|
260
|
+
for (let c = children.length - 1; c >= 0; c--) {
|
|
261
|
+
stack.push({
|
|
262
|
+
node: children[c],
|
|
263
|
+
depth: depth + 1,
|
|
264
|
+
isLast: c === children.length - 1,
|
|
265
|
+
prefix: childPrefix
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return out;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Builds flamegraph data structure (Speedscope & Chrome Trace format).
|
|
275
|
+
*
|
|
276
|
+
* @param {Array<object>} spans
|
|
277
|
+
* @param {object} [options]
|
|
278
|
+
* @returns {object}
|
|
279
|
+
*/
|
|
280
|
+
export function buildFlamegraphData(spans, options = {}) {
|
|
281
|
+
if (!Array.isArray(spans) || spans.length === 0) {
|
|
282
|
+
return {
|
|
283
|
+
version: '0.0.1',
|
|
284
|
+
$schema: 'https://www.speedscope.app/file-format-schema.json',
|
|
285
|
+
shared: { frames: [] },
|
|
286
|
+
profiles: []
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const frameMap = new Map();
|
|
291
|
+
const frames = [];
|
|
292
|
+
|
|
293
|
+
function getFrameIndex(name) {
|
|
294
|
+
if (frameMap.has(name)) return frameMap.get(name);
|
|
295
|
+
const idx = frames.length;
|
|
296
|
+
frames.push({ name });
|
|
297
|
+
frameMap.set(name, idx);
|
|
298
|
+
return idx;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
let minTime = Infinity;
|
|
302
|
+
let maxTime = 0;
|
|
303
|
+
const events = [];
|
|
304
|
+
|
|
305
|
+
for (const s of spans) {
|
|
306
|
+
if (!s || typeof s !== 'object') continue;
|
|
307
|
+
const name = s.name || s.toolName || 'tool';
|
|
308
|
+
const frameIdx = getFrameIndex(name);
|
|
309
|
+
const start = typeof s.startTimeMs === 'number' ? s.startTimeMs : (typeof s.startMs === 'number' ? s.startMs : 0);
|
|
310
|
+
const dur = typeof s.durationMs === 'number' ? s.durationMs : 0;
|
|
311
|
+
const end = typeof s.endTimeMs === 'number' ? s.endTimeMs : (typeof s.endMs === 'number' ? s.endMs : (start + dur));
|
|
312
|
+
|
|
313
|
+
if (start < minTime) minTime = start;
|
|
314
|
+
if (end > maxTime) maxTime = end;
|
|
315
|
+
|
|
316
|
+
events.push({ type: 'O', frame: frameIdx, at: start });
|
|
317
|
+
events.push({ type: 'C', frame: frameIdx, at: end });
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// Sort events chronologically, close events before open at same timestamp
|
|
321
|
+
events.sort((a, b) => (a.at === b.at ? (a.type === 'C' ? -1 : 1) : a.at - b.at));
|
|
322
|
+
|
|
323
|
+
return {
|
|
324
|
+
version: '0.0.1',
|
|
325
|
+
$schema: 'https://www.speedscope.app/file-format-schema.json',
|
|
326
|
+
shared: { frames },
|
|
327
|
+
profiles: [
|
|
328
|
+
{
|
|
329
|
+
type: 'evented',
|
|
330
|
+
name: options.name || 'Highbeam Call-Tree',
|
|
331
|
+
unit: 'milliseconds',
|
|
332
|
+
startValue: minTime === Infinity ? 0 : minTime,
|
|
333
|
+
endValue: maxTime,
|
|
334
|
+
events
|
|
335
|
+
}
|
|
336
|
+
]
|
|
337
|
+
};
|
|
338
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/control/coachLatches.mjs
|
|
3
|
+
* Control Latching in COACH Mode (Feature 27).
|
|
4
|
+
*
|
|
5
|
+
* Enforces hard user /control commands (/pause, /step, /abort, /rewind) while
|
|
6
|
+
* keeping autonomous detector findings advisory in COACH mode and blocking in AUTO_PILOT mode.
|
|
7
|
+
* Pure ESM with strictly 0 node:* imports adhering to Claude Mod Laws 1–5.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { normalizeFlightMode as normalizeGravityFlightMode } from '../coach/cacheGravityRouter.mjs';
|
|
11
|
+
import { CONTROL_STATES, evaluateToolBoundaryLatch } from './controlStateMachine.mjs';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Normalizes user or configuration flight mode string.
|
|
15
|
+
* Defaults unrecognized or missing values safely to COACH.
|
|
16
|
+
*
|
|
17
|
+
* @param {string} [rawMode]
|
|
18
|
+
* @returns {'COACH' | 'AUTO_PILOT' | 'SILENT' | 'OFF'}
|
|
19
|
+
*/
|
|
20
|
+
export function normalizeFlightMode(rawMode) {
|
|
21
|
+
if (typeof normalizeGravityFlightMode === 'function') {
|
|
22
|
+
const norm = normalizeGravityFlightMode(rawMode);
|
|
23
|
+
if (norm) return norm;
|
|
24
|
+
}
|
|
25
|
+
if (!rawMode || typeof rawMode !== 'string') return 'COACH';
|
|
26
|
+
const clean = rawMode.trim().toUpperCase();
|
|
27
|
+
if (['COACH', 'AUTO_PILOT', 'SILENT', 'OFF'].includes(clean)) return clean;
|
|
28
|
+
return 'COACH';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Evaluates the composite control latch decision combining user control state,
|
|
33
|
+
* active flight mode, and autonomous detector verdicts.
|
|
34
|
+
*
|
|
35
|
+
* @param {object} params
|
|
36
|
+
* @param {object} [params.controlState] - Runtime control state from .ctl or IPC
|
|
37
|
+
* @param {string} [params.flightMode='COACH'] - Flight mode (COACH, AUTO_PILOT, SILENT, OFF)
|
|
38
|
+
* @param {object} [params.detectorVerdict=null] - Autonomous detector outcome { triggered, detectorId, reason }
|
|
39
|
+
* @param {boolean} [params.isSecurityRing0=false] - Whether verdict is an unbypassable Ring-0 guard
|
|
40
|
+
* @returns {object} Decision object
|
|
41
|
+
*/
|
|
42
|
+
export function evaluateCoachLatch({
|
|
43
|
+
controlState = null,
|
|
44
|
+
flightMode = 'COACH',
|
|
45
|
+
detectorVerdict = null,
|
|
46
|
+
isSecurityRing0 = false
|
|
47
|
+
} = {}) {
|
|
48
|
+
const mode = normalizeFlightMode(flightMode);
|
|
49
|
+
|
|
50
|
+
// Priority 1: User Control State takes strict precedence
|
|
51
|
+
if (controlState && controlState.state && controlState.state !== CONTROL_STATES.RUNNING) {
|
|
52
|
+
const userLatch = evaluateToolBoundaryLatch(controlState);
|
|
53
|
+
if (userLatch.decision !== 'allow') {
|
|
54
|
+
return {
|
|
55
|
+
...userLatch,
|
|
56
|
+
flightMode: mode,
|
|
57
|
+
userCommand: true
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Priority 2: Security Ring-0 guards always hard block regardless of flight mode
|
|
63
|
+
if (isSecurityRing0 || detectorVerdict?.isSecurityRing0) {
|
|
64
|
+
return {
|
|
65
|
+
decision: 'deny',
|
|
66
|
+
flightMode: mode,
|
|
67
|
+
blocked: true,
|
|
68
|
+
detectorId: detectorVerdict?.detectorId || 'RING_0_SECURITY',
|
|
69
|
+
reason: detectorVerdict?.reason || 'Security Ring-0 invariant violation'
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Priority 3: Autonomous Detector Findings
|
|
74
|
+
if (detectorVerdict && detectorVerdict.triggered) {
|
|
75
|
+
if (mode === 'COACH') {
|
|
76
|
+
// In COACH mode, autonomous detector findings emit advisory warnings without blocking
|
|
77
|
+
return {
|
|
78
|
+
decision: 'allow',
|
|
79
|
+
flightMode: 'COACH',
|
|
80
|
+
advisory: true,
|
|
81
|
+
detectorId: detectorVerdict.detectorId,
|
|
82
|
+
systemMessage: detectorVerdict.reason || `[${detectorVerdict.detectorId}] Advisory warning: proceed with caution`
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (mode === 'AUTO_PILOT') {
|
|
87
|
+
// In AUTO_PILOT mode, autonomous triggers enforce hard blocking
|
|
88
|
+
return {
|
|
89
|
+
decision: 'block',
|
|
90
|
+
flightMode: 'AUTO_PILOT',
|
|
91
|
+
blocked: true,
|
|
92
|
+
detectorId: detectorVerdict.detectorId,
|
|
93
|
+
reason: detectorVerdict.reason || `[${detectorVerdict.detectorId}] Autonomous execution blocked`
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (mode === 'SILENT' || mode === 'OFF') {
|
|
98
|
+
return {
|
|
99
|
+
decision: 'allow',
|
|
100
|
+
flightMode: mode
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
decision: 'allow',
|
|
107
|
+
flightMode: mode
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Renders the COACH status pill for HUD and statusline display.
|
|
113
|
+
*
|
|
114
|
+
* @param {object} [options]
|
|
115
|
+
* @returns {string} e.g. '[COACH]' or '[COACH · DET-09 ACTIVE]'
|
|
116
|
+
*/
|
|
117
|
+
export function renderCoachPill(options = {}) {
|
|
118
|
+
const mode = normalizeFlightMode(options.flightMode);
|
|
119
|
+
const breaker = options.breakerVerdict || options.detectorVerdict;
|
|
120
|
+
|
|
121
|
+
if (breaker && breaker.triggered && breaker.detectorId) {
|
|
122
|
+
return `[${mode} · ${breaker.detectorId} ACTIVE]`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return `[${mode}]`;
|
|
126
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/control/controlStateMachine.mjs
|
|
3
|
+
* Interactive Runtime Control State Machine (Feature 26).
|
|
4
|
+
*
|
|
5
|
+
* Implements deterministic 5-state execution control (RUNNING, PAUSED, STEP, ABORTED, REWIND),
|
|
6
|
+
* transition rules, and .ctl serialization/parsing with safe corrupted fallbacks.
|
|
7
|
+
* Pure ESM with strictly 0 node:* imports adhering to Claude Mod Laws 1–5.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const CONTROL_STATES = Object.freeze({
|
|
11
|
+
RUNNING: 'RUNNING',
|
|
12
|
+
PAUSED: 'PAUSED',
|
|
13
|
+
STEP: 'STEP',
|
|
14
|
+
ABORTED: 'ABORTED',
|
|
15
|
+
REWIND: 'REWIND'
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Creates an initial runtime control state object.
|
|
20
|
+
*
|
|
21
|
+
* @param {string} [sessionId='default']
|
|
22
|
+
* @returns {object}
|
|
23
|
+
*/
|
|
24
|
+
export function createInitialControlState(sessionId = 'default') {
|
|
25
|
+
return {
|
|
26
|
+
sessionId: String(sessionId),
|
|
27
|
+
state: CONTROL_STATES.RUNNING,
|
|
28
|
+
stepCount: 0,
|
|
29
|
+
stepRemaining: 0,
|
|
30
|
+
rewindTarget: null,
|
|
31
|
+
reason: '',
|
|
32
|
+
updatedAt: Date.now()
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Transitions control state deterministically according to FSM rules.
|
|
38
|
+
* ABORTED is terminal and irreversible.
|
|
39
|
+
*
|
|
40
|
+
* @param {object} currentState
|
|
41
|
+
* @param {string} action - 'pause' | 'resume' | 'run' | 'step' | 'abort' | 'rewind' | 'consume_step'
|
|
42
|
+
* @param {string} [reason='']
|
|
43
|
+
* @param {object} [options={}]
|
|
44
|
+
* @returns {object} Next state
|
|
45
|
+
*/
|
|
46
|
+
export function transitionControlState(currentState, action, reason = '', options = {}) {
|
|
47
|
+
const base = currentState && typeof currentState === 'object'
|
|
48
|
+
? currentState
|
|
49
|
+
: createInitialControlState(options.sessionId || 'default');
|
|
50
|
+
const current = base.state || CONTROL_STATES.RUNNING;
|
|
51
|
+
const now = Date.now();
|
|
52
|
+
|
|
53
|
+
// Terminal state: once ABORTED, no transitions allowed
|
|
54
|
+
if (current === CONTROL_STATES.ABORTED) {
|
|
55
|
+
return base;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const normalizedAction = String(action || '').toLowerCase();
|
|
59
|
+
|
|
60
|
+
switch (normalizedAction) {
|
|
61
|
+
case 'pause':
|
|
62
|
+
return {
|
|
63
|
+
...base,
|
|
64
|
+
state: CONTROL_STATES.PAUSED,
|
|
65
|
+
reason: reason || base.reason || '',
|
|
66
|
+
updatedAt: now,
|
|
67
|
+
stepRemaining: 0
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
case 'resume':
|
|
71
|
+
case 'run':
|
|
72
|
+
return {
|
|
73
|
+
...base,
|
|
74
|
+
state: CONTROL_STATES.RUNNING,
|
|
75
|
+
reason: reason || '',
|
|
76
|
+
updatedAt: now,
|
|
77
|
+
stepRemaining: 0
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
case 'step':
|
|
81
|
+
return {
|
|
82
|
+
...base,
|
|
83
|
+
state: CONTROL_STATES.STEP,
|
|
84
|
+
reason: reason || '',
|
|
85
|
+
updatedAt: now,
|
|
86
|
+
stepRemaining: 1,
|
|
87
|
+
stepCount: (Number(base.stepCount) || 0) + 1
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
case 'consume_step':
|
|
91
|
+
return {
|
|
92
|
+
...base,
|
|
93
|
+
state: CONTROL_STATES.PAUSED,
|
|
94
|
+
reason: reason || 'Step consumed',
|
|
95
|
+
updatedAt: now,
|
|
96
|
+
stepRemaining: 0
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
case 'abort':
|
|
100
|
+
return {
|
|
101
|
+
...base,
|
|
102
|
+
state: CONTROL_STATES.ABORTED,
|
|
103
|
+
reason: reason || 'Aborted by user',
|
|
104
|
+
updatedAt: now
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
case 'rewind':
|
|
108
|
+
return {
|
|
109
|
+
...base,
|
|
110
|
+
state: CONTROL_STATES.REWIND,
|
|
111
|
+
reason: reason || 'Rewind requested',
|
|
112
|
+
rewindTarget: options.target ?? null,
|
|
113
|
+
updatedAt: now
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
default:
|
|
117
|
+
return base;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Parses control file string representation (~/.ctxtop/runtime/<sessionId>.ctl).
|
|
123
|
+
* Safely defaults to RUNNING with 'corrupted_fallback' on syntax errors or corruption.
|
|
124
|
+
*
|
|
125
|
+
* @param {string} jsonString
|
|
126
|
+
* @param {string} [fallbackSessionId='default']
|
|
127
|
+
* @returns {object} ControlState
|
|
128
|
+
*/
|
|
129
|
+
export function parseControlFile(jsonString, fallbackSessionId = 'default') {
|
|
130
|
+
if (!jsonString || typeof jsonString !== 'string' || !jsonString.trim()) {
|
|
131
|
+
return {
|
|
132
|
+
...createInitialControlState(fallbackSessionId),
|
|
133
|
+
reason: 'missing_fallback'
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
try {
|
|
138
|
+
const parsed = JSON.parse(jsonString);
|
|
139
|
+
if (!parsed || typeof parsed !== 'object') {
|
|
140
|
+
return {
|
|
141
|
+
...createInitialControlState(fallbackSessionId),
|
|
142
|
+
reason: 'corrupted_fallback'
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (!parsed.state || !Object.values(CONTROL_STATES).includes(parsed.state)) {
|
|
147
|
+
return {
|
|
148
|
+
...createInitialControlState(fallbackSessionId),
|
|
149
|
+
reason: 'corrupted_fallback'
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return {
|
|
154
|
+
sessionId: String(parsed.sessionId || fallbackSessionId),
|
|
155
|
+
state: parsed.state,
|
|
156
|
+
stepCount: Number(parsed.stepCount) || 0,
|
|
157
|
+
stepRemaining: Number(parsed.stepRemaining) || 0,
|
|
158
|
+
rewindTarget: parsed.rewindTarget ?? null,
|
|
159
|
+
reason: String(parsed.reason || ''),
|
|
160
|
+
updatedAt: Number(parsed.updatedAt) || Date.now()
|
|
161
|
+
};
|
|
162
|
+
} catch (_err) {
|
|
163
|
+
return {
|
|
164
|
+
...createInitialControlState(fallbackSessionId),
|
|
165
|
+
reason: 'corrupted_fallback'
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Serializes control state to JSON string with trailing newline.
|
|
172
|
+
*
|
|
173
|
+
* @param {object} state
|
|
174
|
+
* @returns {string}
|
|
175
|
+
*/
|
|
176
|
+
export function serializeControlFile(state) {
|
|
177
|
+
if (!state || typeof state !== 'object') {
|
|
178
|
+
return JSON.stringify(createInitialControlState(), null, 2) + '\n';
|
|
179
|
+
}
|
|
180
|
+
return JSON.stringify(state, null, 2) + '\n';
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Evaluates tool boundary latch synchronously.
|
|
185
|
+
*
|
|
186
|
+
* @param {object} controlState
|
|
187
|
+
* @returns {{ decision: 'allow' | 'suspend' | 'deny', reason?: string, consumeStep?: boolean, stepRemaining?: number }}
|
|
188
|
+
*/
|
|
189
|
+
export function evaluateToolBoundaryLatch(controlState) {
|
|
190
|
+
if (!controlState) return { decision: 'allow' };
|
|
191
|
+
|
|
192
|
+
if (controlState.state === CONTROL_STATES.ABORTED) {
|
|
193
|
+
return { decision: 'deny', reason: controlState.reason || 'Session aborted by user' };
|
|
194
|
+
}
|
|
195
|
+
if (controlState.state === CONTROL_STATES.PAUSED) {
|
|
196
|
+
return { decision: 'suspend', reason: controlState.reason || 'Execution paused by user' };
|
|
197
|
+
}
|
|
198
|
+
if (controlState.state === CONTROL_STATES.REWIND) {
|
|
199
|
+
return { decision: 'suspend', reason: controlState.reason || 'Session rewinding' };
|
|
200
|
+
}
|
|
201
|
+
if (controlState.state === CONTROL_STATES.STEP) {
|
|
202
|
+
return { decision: 'allow', consumeStep: true, stepRemaining: controlState.stepRemaining ?? 1 };
|
|
203
|
+
}
|
|
204
|
+
return { decision: 'allow' };
|
|
205
|
+
}
|