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,382 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/diagnostics/drift_guard.mjs
|
|
3
|
+
* DET-32 IOEDR / REMORY Semantic Drift & Contradiction Guard.
|
|
4
|
+
*
|
|
5
|
+
* Detects actions contradicting locked task.md invariants and repeating
|
|
6
|
+
* falsified hypotheses across >= 3 turns. Injects a <300-token re-anchoring directive.
|
|
7
|
+
*
|
|
8
|
+
* Pure JS / ESM with strictly 0 node:* imports adhering to Claude Mod Laws 1–5.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const POSITIVE_MARKERS = /\b(always|must|ensure|require|required|mandatory|enforce)\b/i;
|
|
12
|
+
const NEGATIVE_MARKERS = /\b(never|do not|don't|dont|prohibit|prohibited|forbidden|cannot|must not|disallow|refuse)\b/i;
|
|
13
|
+
const INSTEAD_OF_REGEX = /(?:use|prefer)\s+([a-zA-Z0-9_-]+)\s+(?:instead of|rather than)\s+([a-zA-Z0-9_-]+)/i;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Escapes special regex characters in a string.
|
|
17
|
+
*
|
|
18
|
+
* @param {string} str
|
|
19
|
+
* @returns {string}
|
|
20
|
+
*/
|
|
21
|
+
export function escapeRegex(str) {
|
|
22
|
+
return String(str || '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Builds a regex that matches a token with word/command boundaries,
|
|
27
|
+
* avoiding substring collisions (e.g. `pnpm` matching `npm`, `bash` or `push` matching `sh`)
|
|
28
|
+
* and preventing file extensions (e.g. `.sh` in `run.sh` or `.npm` in `package.npm`) from matching.
|
|
29
|
+
*
|
|
30
|
+
* @param {string} token
|
|
31
|
+
* @returns {RegExp}
|
|
32
|
+
*/
|
|
33
|
+
export function buildTokenBoundaryRegex(token) {
|
|
34
|
+
const escaped = escapeRegex(token);
|
|
35
|
+
return new RegExp(`(?<![a-zA-Z0-9_.])(?:${escaped})(?![a-zA-Z0-9_])`, 'i');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Parses directive polarity and subjects.
|
|
40
|
+
*
|
|
41
|
+
* @param {string} directive
|
|
42
|
+
* @returns {{ polarity: 'POSITIVE' | 'NEGATIVE' | 'INSTEAD_OF' | 'NEUTRAL', preferred?: string, forbidden?: string, subjects: string[] }}
|
|
43
|
+
*/
|
|
44
|
+
export function parseDirectivePolarity(directive = '') {
|
|
45
|
+
const str = String(directive || '').trim();
|
|
46
|
+
if (!str) return { polarity: 'NEUTRAL', subjects: [] };
|
|
47
|
+
|
|
48
|
+
const insteadMatch = str.match(INSTEAD_OF_REGEX);
|
|
49
|
+
if (insteadMatch) {
|
|
50
|
+
const preferred = insteadMatch[1].toLowerCase();
|
|
51
|
+
const forbidden = insteadMatch[2].toLowerCase();
|
|
52
|
+
return {
|
|
53
|
+
polarity: 'INSTEAD_OF',
|
|
54
|
+
preferred,
|
|
55
|
+
forbidden,
|
|
56
|
+
subjects: [preferred, forbidden]
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const isNeg = NEGATIVE_MARKERS.test(str);
|
|
61
|
+
const isPos = POSITIVE_MARKERS.test(str);
|
|
62
|
+
|
|
63
|
+
// Stop words: purely grammatical, prepositions, auxiliaries, quantifiers, negation words
|
|
64
|
+
// DO NOT drop domain rule subjects like 'delete', 'modify', 'remove', 'files' when they are rule targets.
|
|
65
|
+
const stopWords = new Set([
|
|
66
|
+
'the', 'and', 'for', 'with', 'that', 'this', 'from', 'into', 'always', 'never',
|
|
67
|
+
'must', 'should', 'would', 'could', 'cannot', 'have', 'been', 'before', 'after',
|
|
68
|
+
'directly', 'manually', 'using',
|
|
69
|
+
'not', 'don', 'dont', 'any', 'all', 'does', 'do', 'without', 'each', 'every', 'such',
|
|
70
|
+
'code', 'step', 'turn', 'will', 'shall', 'just', 'only', 'both', 'either'
|
|
71
|
+
]);
|
|
72
|
+
|
|
73
|
+
const rawTokens = str.toLowerCase()
|
|
74
|
+
.replace(/[^a-z0-9_.-]/g, ' ')
|
|
75
|
+
.split(/\s+/)
|
|
76
|
+
.filter(t => t.length >= 3 && !stopWords.has(t));
|
|
77
|
+
|
|
78
|
+
const subjects = Array.from(new Set(rawTokens));
|
|
79
|
+
|
|
80
|
+
// Modal precedence: Negative prohibitions take precedence over positive modal auxiliaries
|
|
81
|
+
// e.g. "You must NEVER run rm -rf" -> NEGATIVE
|
|
82
|
+
if (isNeg) {
|
|
83
|
+
return { polarity: 'NEGATIVE', subjects };
|
|
84
|
+
}
|
|
85
|
+
if (isPos) {
|
|
86
|
+
return { polarity: 'POSITIVE', subjects };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return { polarity: 'NEUTRAL', subjects };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Extracts invariant strings from raw task.md content or list.
|
|
94
|
+
*
|
|
95
|
+
* @param {string|string[]} source
|
|
96
|
+
* @returns {string[]}
|
|
97
|
+
*/
|
|
98
|
+
export function extractLockedInvariants(source) {
|
|
99
|
+
if (!source) return [];
|
|
100
|
+
if (Array.isArray(source)) {
|
|
101
|
+
return source.map(s => String(s || '').trim()).filter(Boolean);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const text = String(source || '');
|
|
105
|
+
const lines = text.split(/\r?\n/);
|
|
106
|
+
const invariants = [];
|
|
107
|
+
let inInvariantSection = false;
|
|
108
|
+
|
|
109
|
+
for (const line of lines) {
|
|
110
|
+
const trimmed = line.trim();
|
|
111
|
+
if (/^#+\s+(?:.*(?:Invariant|Constraint|Key Rule|Never|Ground Rule)|🔒)/i.test(trimmed)) {
|
|
112
|
+
inInvariantSection = true;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (inInvariantSection && /^#+\s+/.test(trimmed)) {
|
|
116
|
+
inInvariantSection = false;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (inInvariantSection) {
|
|
120
|
+
if (trimmed.startsWith('-') || trimmed.startsWith('*') || /^\d+\./.test(trimmed)) {
|
|
121
|
+
const cleaned = trimmed.replace(/^[-*]|\d+\.\s*/, '').trim();
|
|
122
|
+
if (cleaned) invariants.push(cleaned);
|
|
123
|
+
}
|
|
124
|
+
} else if (
|
|
125
|
+
(trimmed.startsWith('-') || trimmed.startsWith('*')) &&
|
|
126
|
+
(NEGATIVE_MARKERS.test(trimmed) || POSITIVE_MARKERS.test(trimmed) || INSTEAD_OF_REGEX.test(trimmed))
|
|
127
|
+
) {
|
|
128
|
+
const cleaned = trimmed.replace(/^[-*]\s*/, '').trim();
|
|
129
|
+
if (cleaned) invariants.push(cleaned);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return invariants;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const NEGATION_BYPASS_PREFIX = '(?:skip(?:ping|ped)?|bypass(?:ing|ed)?|disabl(?:e|ing|ed)|omit(?:ting|ted)?|ignor(?:e|ing|ed)|without|never|no|not|do not)';
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Audits candidate action against locked invariants.
|
|
140
|
+
*
|
|
141
|
+
* @param {object} candidateAction
|
|
142
|
+
* @param {string[]} invariants
|
|
143
|
+
* @returns {Array<{ rule: string, reason: string }>}
|
|
144
|
+
*/
|
|
145
|
+
export function auditInvariantContradiction(candidateAction = {}, invariants = []) {
|
|
146
|
+
if (!candidateAction || !Array.isArray(invariants) || invariants.length === 0) return [];
|
|
147
|
+
|
|
148
|
+
const actionText = [
|
|
149
|
+
candidateAction.description,
|
|
150
|
+
candidateAction.command,
|
|
151
|
+
candidateAction.targetFile,
|
|
152
|
+
candidateAction.proposedContent,
|
|
153
|
+
candidateAction.tool
|
|
154
|
+
].filter(Boolean).join(' ').toLowerCase();
|
|
155
|
+
|
|
156
|
+
const violations = [];
|
|
157
|
+
|
|
158
|
+
for (const rule of invariants) {
|
|
159
|
+
const parsed = parseDirectivePolarity(rule);
|
|
160
|
+
|
|
161
|
+
if (parsed.polarity === 'INSTEAD_OF' && parsed.forbidden) {
|
|
162
|
+
const forbiddenRegex = buildTokenBoundaryRegex(parsed.forbidden);
|
|
163
|
+
if (forbiddenRegex.test(actionText)) {
|
|
164
|
+
violations.push({
|
|
165
|
+
rule,
|
|
166
|
+
reason: `Action references forbidden alternative "${parsed.forbidden}" instead of preferred "${parsed.preferred}"`
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
} else if (parsed.polarity === 'NEGATIVE' && parsed.subjects.length > 0) {
|
|
170
|
+
// Check if candidate action explicitly invokes forbidden subject as a word/token
|
|
171
|
+
const matches = parsed.subjects.filter(s => {
|
|
172
|
+
const regex = buildTokenBoundaryRegex(s);
|
|
173
|
+
return regex.test(actionText);
|
|
174
|
+
});
|
|
175
|
+
if (matches.length > 0) {
|
|
176
|
+
violations.push({
|
|
177
|
+
rule,
|
|
178
|
+
reason: `Action violates negative invariant by operating on forbidden subject(s): ${matches.join(', ')}`
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
} else if (parsed.polarity === 'POSITIVE' && parsed.subjects.length > 0) {
|
|
182
|
+
// Check if action explicitly skips, bypasses, disables, or negates required positive subjects
|
|
183
|
+
const contradictedSubjects = [];
|
|
184
|
+
for (const s of parsed.subjects) {
|
|
185
|
+
// Pattern 1: Negation prefix within 0-3 words before subject (e.g. "skip verification tests")
|
|
186
|
+
const r1 = new RegExp(`\\b${NEGATION_BYPASS_PREFIX}\\s+(?:\\w+\\s+){0,3}\\b${escapeRegex(s)}\\b`, 'i');
|
|
187
|
+
// Pattern 2: Subject followed by passive negation (e.g. "verification is disabled")
|
|
188
|
+
const r2 = new RegExp(`\\b${escapeRegex(s)}\\s+(?:(?:is|are|was|were)\\s+)?(?:skip(?:ped)?|disabl(?:ed)?|bypassed|omit(?:ted)?|ignor(?:ed)?)\\b`, 'i');
|
|
189
|
+
// Pattern 3: CLI flags like --no-verify, --skip-tests
|
|
190
|
+
const r3 = new RegExp(`(?:--no-|--skip-)${escapeRegex(s)}`, 'i');
|
|
191
|
+
|
|
192
|
+
if (r1.test(actionText) || r2.test(actionText) || r3.test(actionText)) {
|
|
193
|
+
contradictedSubjects.push(s);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (contradictedSubjects.length > 0) {
|
|
197
|
+
violations.push({
|
|
198
|
+
rule,
|
|
199
|
+
reason: `Action contradicts positive invariant by omitting, skipping, or negating required subject(s): ${contradictedSubjects.join(', ')}`
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
return violations;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Normalizes hypothesis string for loop comparison.
|
|
210
|
+
*
|
|
211
|
+
* @param {string} hyp
|
|
212
|
+
* @returns {string}
|
|
213
|
+
*/
|
|
214
|
+
function normalizeHypothesis(hyp = '') {
|
|
215
|
+
return String(hyp || '')
|
|
216
|
+
.toLowerCase()
|
|
217
|
+
.replace(/[^a-z0-9]/g, ' ')
|
|
218
|
+
.trim()
|
|
219
|
+
.split(/\s+/)
|
|
220
|
+
.slice(0, 15)
|
|
221
|
+
.join(' ');
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Audits recent turns for repeating falsified hypotheses across >= 3 turns.
|
|
226
|
+
*
|
|
227
|
+
* @param {Array<object>} recentTurns
|
|
228
|
+
* @returns {{ isLoop: boolean, hypothesis: string | null, failedCount: number }}
|
|
229
|
+
*/
|
|
230
|
+
export function auditHypothesisLoop(recentTurns = []) {
|
|
231
|
+
if (!Array.isArray(recentTurns) || recentTurns.length < 3) {
|
|
232
|
+
return { isLoop: false, hypothesis: null, failedCount: 0 };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
let consecutiveFails = 0;
|
|
236
|
+
let lastNormHyp = null;
|
|
237
|
+
let rawHyp = null;
|
|
238
|
+
|
|
239
|
+
for (let i = recentTurns.length - 1; i >= 0; i--) {
|
|
240
|
+
const turn = recentTurns[i];
|
|
241
|
+
if (!turn) break;
|
|
242
|
+
|
|
243
|
+
const isFailed = turn.outcome === 'failed' || turn.status === 'failed' || turn.error;
|
|
244
|
+
if (!isFailed) break;
|
|
245
|
+
|
|
246
|
+
const hyp = turn.hypothesis || turn.assumption || turn.description || '';
|
|
247
|
+
const norm = normalizeHypothesis(hyp);
|
|
248
|
+
|
|
249
|
+
if (!norm) {
|
|
250
|
+
if (consecutiveFails === 0) {
|
|
251
|
+
lastNormHyp = 'unspecified_failure';
|
|
252
|
+
rawHyp = hyp || 'repeated failed step';
|
|
253
|
+
}
|
|
254
|
+
consecutiveFails++;
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
if (consecutiveFails === 0) {
|
|
259
|
+
lastNormHyp = norm;
|
|
260
|
+
rawHyp = hyp;
|
|
261
|
+
consecutiveFails = 1;
|
|
262
|
+
} else if (lastNormHyp === norm || (norm.length > 10 && (lastNormHyp.includes(norm) || norm.includes(lastNormHyp)))) {
|
|
263
|
+
consecutiveFails++;
|
|
264
|
+
} else {
|
|
265
|
+
break;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const isLoop = consecutiveFails >= 3;
|
|
270
|
+
return {
|
|
271
|
+
isLoop,
|
|
272
|
+
hypothesis: isLoop ? rawHyp : null,
|
|
273
|
+
failedCount: consecutiveFails
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Evaluates DET-32 IOEDR / REMORY semantic drift.
|
|
279
|
+
*
|
|
280
|
+
* @param {object} turnContext
|
|
281
|
+
* @param {string[]} [turnContext.invariants] - Explicit locked invariant rule strings
|
|
282
|
+
* @param {string} [turnContext.taskMdContent] - Raw content of task.md to parse invariants from
|
|
283
|
+
* @param {object} [turnContext.candidateAction] - Action proposed in the current turn
|
|
284
|
+
* @param {Array<object>} [turnContext.recentTurns] - Recent turn records with { hypothesis, outcome: 'passed'|'failed', turn }
|
|
285
|
+
* @param {string} [turnContext.flightMode='COACH'] - 'COACH' | 'AUTO_PILOT'
|
|
286
|
+
* @returns {object} Evaluation result
|
|
287
|
+
*/
|
|
288
|
+
export function evaluateSemanticDrift(turnContext = {}) {
|
|
289
|
+
const invariants = Array.isArray(turnContext.invariants) && turnContext.invariants.length > 0
|
|
290
|
+
? turnContext.invariants
|
|
291
|
+
: extractLockedInvariants(turnContext.taskMdContent);
|
|
292
|
+
|
|
293
|
+
const candidateAction = turnContext.candidateAction || null;
|
|
294
|
+
const recentTurns = turnContext.recentTurns || [];
|
|
295
|
+
const flightMode = turnContext.flightMode || 'COACH';
|
|
296
|
+
|
|
297
|
+
const invariantViolations = candidateAction ? auditInvariantContradiction(candidateAction, invariants) : [];
|
|
298
|
+
const hypothesisAudit = auditHypothesisLoop(recentTurns);
|
|
299
|
+
|
|
300
|
+
const violations = [];
|
|
301
|
+
if (invariantViolations.length > 0) {
|
|
302
|
+
for (const v of invariantViolations) {
|
|
303
|
+
violations.push({
|
|
304
|
+
type: 'INVARIANT_CONTRADICTION',
|
|
305
|
+
rule: v.rule,
|
|
306
|
+
detail: v.reason
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (hypothesisAudit.isLoop) {
|
|
312
|
+
violations.push({
|
|
313
|
+
type: 'HYPOTHESIS_LOOP',
|
|
314
|
+
hypothesis: hypothesisAudit.hypothesis,
|
|
315
|
+
failedCount: hypothesisAudit.failedCount,
|
|
316
|
+
detail: `Repeating falsified hypothesis across ${hypothesisAudit.failedCount} consecutive failed turns: "${hypothesisAudit.hypothesis}"`
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const triggered = violations.length > 0;
|
|
321
|
+
|
|
322
|
+
if (!triggered) {
|
|
323
|
+
return {
|
|
324
|
+
detectorId: 'DET-32',
|
|
325
|
+
slug: 'semantic-drift-guard',
|
|
326
|
+
triggered: false,
|
|
327
|
+
decision: 'allow',
|
|
328
|
+
violations: [],
|
|
329
|
+
reanchoringDirective: null,
|
|
330
|
+
reason: null
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// Defensive truncation: bounded conflict lines (max 3 items, max 120 chars each)
|
|
335
|
+
const conflictLines = violations.slice(0, 3).map(v => {
|
|
336
|
+
if (v.type === 'INVARIANT_CONTRADICTION') {
|
|
337
|
+
const r = (v.rule || '').slice(0, 50);
|
|
338
|
+
const d = (v.detail || '').slice(0, 50);
|
|
339
|
+
return `- Invariant Conflict: Rule "${r}" (${d})`.slice(0, 120);
|
|
340
|
+
}
|
|
341
|
+
return `- Hypothesis Loop: ${(v.detail || '')}`.slice(0, 120);
|
|
342
|
+
}).join('\n');
|
|
343
|
+
|
|
344
|
+
// Concise <300 token re-anchoring directive
|
|
345
|
+
const rawDirective = [
|
|
346
|
+
'[DET-32 Re-anchoring Directive]',
|
|
347
|
+
'Semantic drift detected:',
|
|
348
|
+
conflictLines,
|
|
349
|
+
'Mandatory Remediation:',
|
|
350
|
+
'1. Re-anchor to task.md invariants. Never attempt forbidden actions or reverse required constraints.',
|
|
351
|
+
'2. Formulate a new, alternative hypothesis grounded in actual test output rather than repeating prior failed attempts.',
|
|
352
|
+
'3. Verify the next proposed step conforms to all locked invariants before executing.'
|
|
353
|
+
].join('\n');
|
|
354
|
+
|
|
355
|
+
// Defensive hard cap: <= 1200 chars (< 300 tokens)
|
|
356
|
+
const reanchoringDirective = rawDirective.length > 1150
|
|
357
|
+
? rawDirective.slice(0, 1140) + '\n...'
|
|
358
|
+
: rawDirective;
|
|
359
|
+
|
|
360
|
+
const reason = violations.map(v => v.detail).join('; ');
|
|
361
|
+
const decision = flightMode === 'AUTO_PILOT' ? 'deny' : 'warn';
|
|
362
|
+
|
|
363
|
+
return {
|
|
364
|
+
detectorId: 'DET-32',
|
|
365
|
+
slug: 'semantic-drift-guard',
|
|
366
|
+
triggered: true,
|
|
367
|
+
decision,
|
|
368
|
+
violations,
|
|
369
|
+
reanchoringDirective,
|
|
370
|
+
reason
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
export default {
|
|
375
|
+
escapeRegex,
|
|
376
|
+
buildTokenBoundaryRegex,
|
|
377
|
+
parseDirectivePolarity,
|
|
378
|
+
extractLockedInvariants,
|
|
379
|
+
auditInvariantContradiction,
|
|
380
|
+
auditHypothesisLoop,
|
|
381
|
+
evaluateSemanticDrift
|
|
382
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/diagnostics/index.mjs
|
|
3
|
+
* Isomorphic diagnostics, drift metrics, and topology summarizers.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export * from '../telemetry/sprintMetrics.mjs';
|
|
7
|
+
export * from '../telemetry/swarmTopology.mjs';
|
|
8
|
+
export * from '../catalog/detectorCatalog.mjs';
|
|
9
|
+
export * from './drift_guard.mjs';
|