@unerr-ai/unerr 0.2.1 → 0.2.3
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/README.md +36 -45
- package/dist/cli.js +37443 -36022
- package/package.json +2 -1
- package/dist/behaviors/agent-llm-bridge.js +0 -166
- package/dist/behaviors/architecture-guard.js +0 -256
- package/dist/behaviors/auto-doc.js +0 -247
- package/dist/behaviors/cascade-guard.js +0 -289
- package/dist/behaviors/change-narrative.js +0 -270
- package/dist/behaviors/convention-drift.js +0 -290
- package/dist/behaviors/framework.js +0 -235
- package/dist/behaviors/guard-formatter.js +0 -44
- package/dist/behaviors/incomplete-work.js +0 -270
- package/dist/behaviors/loop-breaker.js +0 -300
- package/dist/behaviors/session-continuity.js +0 -208
- package/dist/commands/branches.js +0 -97
- package/dist/commands/check-commit.js +0 -225
- package/dist/commands/compress-output.js +0 -64
- package/dist/commands/config-verify.js +0 -243
- package/dist/commands/daemon.js +0 -905
- package/dist/commands/dashboard.js +0 -52
- package/dist/commands/debug.js +0 -200
- package/dist/commands/enrich.js +0 -184
- package/dist/commands/exec.js +0 -233
- package/dist/commands/gain.js +0 -156
- package/dist/commands/hook.js +0 -88
- package/dist/commands/index.js +0 -88
- package/dist/commands/init.js +0 -74
- package/dist/commands/install.js +0 -505
- package/dist/commands/learn.js +0 -116
- package/dist/commands/manifest.js +0 -193
- package/dist/commands/rewind.js +0 -103
- package/dist/commands/serve.js +0 -19
- package/dist/commands/setup-wizard.js +0 -414
- package/dist/commands/skills.js +0 -64
- package/dist/commands/stats.js +0 -20
- package/dist/commands/status.js +0 -654
- package/dist/commands/timeline.js +0 -139
- package/dist/commands/uninstall.js +0 -230
- package/dist/components/App.js +0 -109
- package/dist/components/Banner.js +0 -12
- package/dist/components/ConfirmPrompt.js +0 -25
- package/dist/components/DriftSummary.js +0 -23
- package/dist/components/GradeBadge.js +0 -15
- package/dist/components/HealthCard.js +0 -18
- package/dist/components/InkSpinner.js +0 -22
- package/dist/components/InputBox.js +0 -17
- package/dist/components/KeyValue.js +0 -13
- package/dist/components/MessageList.js +0 -14
- package/dist/components/ProgressBar.js +0 -26
- package/dist/components/Section.js +0 -16
- package/dist/components/SessionSummaryCard.js +0 -73
- package/dist/components/StartupDisplay.js +0 -24
- package/dist/components/StatusDashboard.js +0 -57
- package/dist/components/StatusLine.js +0 -8
- package/dist/components/StepLine.js +0 -22
- package/dist/components/Theme.js +0 -20
- package/dist/components/ToolProgress.js +0 -8
- package/dist/components/ViolationList.js +0 -21
- package/dist/components/render.js +0 -13
- package/dist/config/agent-registry.js +0 -237
- package/dist/config/claude-settings-hooks.js +0 -304
- package/dist/config/hook-installer.js +0 -65
- package/dist/config/instruction-writer.js +0 -388
- package/dist/config/mcp-config-writer.js +0 -266
- package/dist/config/settings.js +0 -174
- package/dist/config/tool-detector.js +0 -42
- package/dist/config/value-surfacing.js +0 -119
- package/dist/core/context-assembly.js +0 -108
- package/dist/core/conversation.js +0 -33
- package/dist/core/local-chat-provider.js +0 -475
- package/dist/core/provider-factory.js +0 -55
- package/dist/core/providers.js +0 -90
- package/dist/core/query-engine.js +0 -174
- package/dist/daemon/api.js +0 -312
- package/dist/daemon/autostart.js +0 -119
- package/dist/daemon/bootstrap.js +0 -39
- package/dist/daemon/client.js +0 -164
- package/dist/daemon/detect-ci.js +0 -81
- package/dist/daemon/platform-linux.js +0 -146
- package/dist/daemon/platform-macos.js +0 -134
- package/dist/daemon/platform-windows.js +0 -116
- package/dist/daemon/process-manager.js +0 -299
- package/dist/daemon/protocol.js +0 -23
- package/dist/daemon/registry.js +0 -270
- package/dist/daemon/settings-schema.js +0 -72
- package/dist/daemon/system-health.js +0 -134
- package/dist/daemon/version-checker.js +0 -262
- package/dist/daemon/warm-start.js +0 -223
- package/dist/entrypoints/cli.js +0 -1043
- package/dist/entrypoints/daemon.js +0 -380
- package/dist/entrypoints/repl.js +0 -147
- package/dist/hooks/adapters/claude-code.js +0 -90
- package/dist/hooks/adapters/cline.js +0 -100
- package/dist/hooks/adapters/cursor.js +0 -98
- package/dist/hooks/hook-dedup.js +0 -79
- package/dist/hooks/hook-runner.js +0 -113
- package/dist/hooks/navigation-hooks.js +0 -175
- package/dist/hooks/prompt-hooks.js +0 -63
- package/dist/hooks/shell-hooks.js +0 -47
- package/dist/ignore.js +0 -111
- package/dist/intelligence/approach-suggester.js +0 -61
- package/dist/intelligence/ast-extractor.js +0 -2615
- package/dist/intelligence/ast-worker.js +0 -34
- package/dist/intelligence/background-indexer.js +0 -121
- package/dist/intelligence/blast-radius.js +0 -200
- package/dist/intelligence/community-detection.js +0 -691
- package/dist/intelligence/community-detector.js +0 -184
- package/dist/intelligence/computation-scheduler.js +0 -75
- package/dist/intelligence/confidence-propagation.js +0 -47
- package/dist/intelligence/convention-detector.js +0 -242
- package/dist/intelligence/convention-learner.js +0 -205
- package/dist/intelligence/convention-matcher.js +0 -205
- package/dist/intelligence/cozo-schema.js +0 -376
- package/dist/intelligence/decision-point-detector.js +0 -90
- package/dist/intelligence/deep-dive-tools.js +0 -586
- package/dist/intelligence/durability-scorer.js +0 -84
- package/dist/intelligence/exploration-cost.js +0 -204
- package/dist/intelligence/exploration-pattern-tracker.js +0 -61
- package/dist/intelligence/fact-generator.js +0 -322
- package/dist/intelligence/facts-schema.js +0 -90
- package/dist/intelligence/file-intelligence.js +0 -59
- package/dist/intelligence/graph-holder.js +0 -220
- package/dist/intelligence/graph-temporal-joiner.js +0 -238
- package/dist/intelligence/health-grade.js +0 -423
- package/dist/intelligence/health-grader.js +0 -200
- package/dist/intelligence/health-map-data.js +0 -259
- package/dist/intelligence/import-symbols.js +0 -136
- package/dist/intelligence/incremental-indexer.js +0 -658
- package/dist/intelligence/indexer/centrality.js +0 -62
- package/dist/intelligence/indexer/cfg-context.js +0 -95
- package/dist/intelligence/indexer/confidence.js +0 -34
- package/dist/intelligence/indexer/cross-file-resolver.js +0 -104
- package/dist/intelligence/indexer/edge-repair.js +0 -89
- package/dist/intelligence/indexer/entity-key.js +0 -17
- package/dist/intelligence/indexer/export-map.js +0 -132
- package/dist/intelligence/indexer/git-cochange.js +0 -128
- package/dist/intelligence/indexer/graph-patch.js +0 -147
- package/dist/intelligence/indexer/incremental.js +0 -78
- package/dist/intelligence/indexer/ingest.js +0 -160
- package/dist/intelligence/indexer/language-detect.js +0 -226
- package/dist/intelligence/indexer/metadata.js +0 -63
- package/dist/intelligence/indexer/mutation-tracker.js +0 -79
- package/dist/intelligence/indexer/orchestrator.js +0 -155
- package/dist/intelligence/indexer/plugin-interface.js +0 -31
- package/dist/intelligence/indexer/plugins/csharp.js +0 -440
- package/dist/intelligence/indexer/plugins/go.js +0 -335
- package/dist/intelligence/indexer/plugins/java.js +0 -370
- package/dist/intelligence/indexer/plugins/python.js +0 -358
- package/dist/intelligence/indexer/plugins/regex-fallback.js +0 -82
- package/dist/intelligence/indexer/plugins/ruby.js +0 -290
- package/dist/intelligence/indexer/plugins/rust.js +0 -484
- package/dist/intelligence/indexer/plugins/tier2-generic.js +0 -310
- package/dist/intelligence/indexer/plugins/typescript.js +0 -456
- package/dist/intelligence/indexer/resource-monitor.js +0 -93
- package/dist/intelligence/indexer/scip/decoder.js +0 -253
- package/dist/intelligence/indexer/scip/detector.js +0 -232
- package/dist/intelligence/indexer/scip/downloader.js +0 -427
- package/dist/intelligence/indexer/scip/fallback.js +0 -34
- package/dist/intelligence/indexer/scip/merger.js +0 -109
- package/dist/intelligence/indexer/scip/orchestrator.js +0 -433
- package/dist/intelligence/indexer/scip/runner.js +0 -98
- package/dist/intelligence/indexer/snapshot.js +0 -66
- package/dist/intelligence/indexer/test-detector.js +0 -196
- package/dist/intelligence/indexer/watch-integration.js +0 -61
- package/dist/intelligence/indexer/worker.js +0 -85
- package/dist/intelligence/local-convention-detector.js +0 -437
- package/dist/intelligence/local-embeddings.js +0 -190
- package/dist/intelligence/local-graph.js +0 -1946
- package/dist/intelligence/local-indexer.js +0 -1575
- package/dist/intelligence/local-llm.js +0 -163
- package/dist/intelligence/local-rule-generator.js +0 -154
- package/dist/intelligence/local-snapshot.js +0 -213
- package/dist/intelligence/negative-knowledge.js +0 -103
- package/dist/intelligence/persistent-db.js +0 -85
- package/dist/intelligence/query-router.js +0 -2556
- package/dist/intelligence/risk-classifier.js +0 -116
- package/dist/intelligence/rule-evaluator.js +0 -380
- package/dist/intelligence/rule-generator.js +0 -49
- package/dist/intelligence/search-index.js +0 -173
- package/dist/intelligence/semantic/docstring-extractor.js +0 -67
- package/dist/intelligence/semantic/embedding-store.js +0 -52
- package/dist/intelligence/semantic/enrichment-orchestrator.js +0 -48
- package/dist/intelligence/semantic/git-message-miner.js +0 -114
- package/dist/intelligence/semantic/identifier-tokenizer.js +0 -51
- package/dist/intelligence/semantic/node2vec-embeddings.js +0 -71
- package/dist/intelligence/semantic/node2vec-walks.js +0 -103
- package/dist/intelligence/semantic/path-domain-inference.js +0 -112
- package/dist/intelligence/semantic/similarity-engine.js +0 -60
- package/dist/intelligence/semantic/tfidf-vectors.js +0 -88
- package/dist/intelligence/session-brief-builder.js +0 -159
- package/dist/intelligence/session-context.js +0 -221
- package/dist/intelligence/session-health-monitor.js +0 -211
- package/dist/intelligence/session-narrative.js +0 -197
- package/dist/intelligence/session-pattern-analyzer.js +0 -218
- package/dist/intelligence/signal-scorer.js +0 -390
- package/dist/intelligence/signal-show-store.js +0 -182
- package/dist/intelligence/smart-truncate.js +0 -158
- package/dist/intelligence/subgraph-cache.js +0 -88
- package/dist/intelligence/temporal-facts.js +0 -494
- package/dist/intelligence/token-estimator.js +0 -100
- package/dist/intelligence/tool-injector.js +0 -87
- package/dist/intelligence/tree-sitter-loader.js +0 -71
- package/dist/intelligence/worker-pool.js +0 -116
- package/dist/proxy/arg-validator.js +0 -79
- package/dist/proxy/auto-bootstrap.js +0 -167
- package/dist/proxy/bridge.js +0 -147
- package/dist/proxy/budget-enforcer.js +0 -70
- package/dist/proxy/compression-quality-monitor.js +0 -160
- package/dist/proxy/compression-stats.js +0 -51
- package/dist/proxy/context-rot-detector.js +0 -137
- package/dist/proxy/drift-detector.js +0 -139
- package/dist/proxy/efficiency-tracker.js +0 -79
- package/dist/proxy/fact-ranking.js +0 -154
- package/dist/proxy/format-encoder.js +0 -266
- package/dist/proxy/http-transport.js +0 -90
- package/dist/proxy/lifecycle-actor.js +0 -55
- package/dist/proxy/lifecycle-machine.js +0 -187
- package/dist/proxy/log-tailer.js +0 -265
- package/dist/proxy/model-pricing.js +0 -98
- package/dist/proxy/network-firewall.js +0 -141
- package/dist/proxy/nudge-state.js +0 -93
- package/dist/proxy/output-compressor.js +0 -185
- package/dist/proxy/pid-lock.js +0 -291
- package/dist/proxy/proxy-context.js +0 -11
- package/dist/proxy/proxy.js +0 -2633
- package/dist/proxy/response-enrichment.js +0 -32
- package/dist/proxy/response-envelope.js +0 -313
- package/dist/proxy/session-dedup.js +0 -82
- package/dist/proxy/session-legend.js +0 -30
- package/dist/proxy/session-persistence.js +0 -210
- package/dist/proxy/session-resume.js +0 -94
- package/dist/proxy/session-stats.js +0 -513
- package/dist/proxy/shell-classifier.js +0 -1346
- package/dist/proxy/shell-compression-log.js +0 -93
- package/dist/proxy/shell-compressor.js +0 -390
- package/dist/proxy/shell-graph-boost.js +0 -202
- package/dist/proxy/shell-monitor-map.js +0 -18
- package/dist/proxy/shell-stats.js +0 -54
- package/dist/proxy/shell-strategies/cloud.js +0 -215
- package/dist/proxy/shell-strategies/diff.js +0 -159
- package/dist/proxy/shell-strategies/error-diagnostic.js +0 -796
- package/dist/proxy/shell-strategies/filter-dsl.js +0 -358
- package/dist/proxy/shell-strategies/git-status.js +0 -177
- package/dist/proxy/shell-strategies/key-value.js +0 -193
- package/dist/proxy/shell-strategies/log-text.js +0 -154
- package/dist/proxy/shell-strategies/omni.js +0 -188
- package/dist/proxy/shell-strategies/progress.js +0 -55
- package/dist/proxy/shell-strategies/redact.js +0 -76
- package/dist/proxy/shell-strategies/structured.js +0 -241
- package/dist/proxy/shell-strategies/tabular.js +0 -243
- package/dist/proxy/shell-strategies/test-results-types.js +0 -13
- package/dist/proxy/shell-strategies/test-results.js +0 -784
- package/dist/proxy/shell-strategies/tree-paths.js +0 -144
- package/dist/proxy/shell-strategies/yaml.js +0 -182
- package/dist/proxy/shell-tee.js +0 -111
- package/dist/proxy/signal-dedup.js +0 -171
- package/dist/proxy/startup-renderer.js +0 -158
- package/dist/proxy/task-token-display.js +0 -38
- package/dist/proxy/token-counter.js +0 -61
- package/dist/proxy/tool-clusters.js +0 -273
- package/dist/proxy/tool-definitions.js +0 -525
- package/dist/proxy/transport-mux.js +0 -229
- package/dist/proxy/wire-cap.js +0 -268
- package/dist/rules/developer.mozilla.org.json +0 -9
- package/dist/rules/github.com.json +0 -21
- package/dist/schemas/api/skills.js +0 -19
- package/dist/schemas/common/errors.js +0 -7
- package/dist/schemas/common/headers.js +0 -5
- package/dist/schemas/entities/edge.js +0 -25
- package/dist/schemas/entities/entity.js +0 -22
- package/dist/schemas/entities/rule.js +0 -18
- package/dist/schemas/index.js +0 -14
- package/dist/server/event-bus.js +0 -59
- package/dist/server/http.js +0 -156
- package/dist/server/middleware.js +0 -70
- package/dist/server/routes/drift.js +0 -97
- package/dist/server/routes/intelligence.js +0 -1217
- package/dist/server/routes/reasoning-quality.js +0 -444
- package/dist/server/routes/session.js +0 -86
- package/dist/server/routes/stream.js +0 -120
- package/dist/server/routes/system.js +0 -73
- package/dist/server/routes/temporal.js +0 -170
- package/dist/server/routes/timeline.js +0 -232
- package/dist/server/routes/token-flow.js +0 -403
- package/dist/skills/effectiveness-tracker.js +0 -93
- package/dist/skills/local-pack.js +0 -380
- package/dist/skills/resolver.js +0 -495
- package/dist/state-detector.js +0 -83
- package/dist/timeline/intent-detector.js +0 -263
- package/dist/timeline/loop-miner.js +0 -140
- package/dist/timeline/open-threads.js +0 -49
- package/dist/timeline/signal-reinforcer.js +0 -62
- package/dist/timeline/timeline-bootstrap.js +0 -151
- package/dist/timeline/timeline-store.js +0 -618
- package/dist/tools/coding/bash.js +0 -49
- package/dist/tools/coding/file-edit.js +0 -72
- package/dist/tools/coding/file-outline.js +0 -227
- package/dist/tools/coding/file-read-protocol.js +0 -425
- package/dist/tools/coding/file-read.js +0 -35
- package/dist/tools/coding/file-write.js +0 -43
- package/dist/tools/coding/glob-tool.js +0 -109
- package/dist/tools/coding/grep.js +0 -162
- package/dist/tools/coding/index.js +0 -27
- package/dist/tools/intelligence/index.js +0 -269
- package/dist/tools/intelligence/record-fact.js +0 -48
- package/dist/tools/intelligence/timeline-markers.js +0 -130
- package/dist/tools/registry.js +0 -47
- package/dist/tools/types.js +0 -8
- package/dist/tracking/auto-snapshot-triggers.js +0 -246
- package/dist/tracking/branch-context.js +0 -115
- package/dist/tracking/branch-snapshot.js +0 -217
- package/dist/tracking/causal-bridge.js +0 -317
- package/dist/tracking/circuit-breaker.js +0 -147
- package/dist/tracking/commit-watcher.js +0 -114
- package/dist/tracking/context-ledger.js +0 -119
- package/dist/tracking/correction-detector.js +0 -324
- package/dist/tracking/drift-tracker.js +0 -874
- package/dist/tracking/durability-tracker.js +0 -94
- package/dist/tracking/entity-rewind.js +0 -200
- package/dist/tracking/file-hash-state.js +0 -114
- package/dist/tracking/git-attribution.js +0 -132
- package/dist/tracking/git-trailers.js +0 -171
- package/dist/tracking/intelligence-counter.js +0 -46
- package/dist/tracking/intent-correlator.js +0 -202
- package/dist/tracking/intent-encoder.js +0 -52
- package/dist/tracking/intent-token-tracker.js +0 -159
- package/dist/tracking/ledger-archiver.js +0 -94
- package/dist/tracking/ledger-chains.js +0 -245
- package/dist/tracking/metrics-store.js +0 -361
- package/dist/tracking/native-watcher.js +0 -131
- package/dist/tracking/offline-rewind.js +0 -295
- package/dist/tracking/pending-violations.js +0 -74
- package/dist/tracking/persistence-effectiveness.js +0 -167
- package/dist/tracking/prompt-durability.js +0 -202
- package/dist/tracking/quality-signals.js +0 -213
- package/dist/tracking/redactor.js +0 -73
- package/dist/tracking/rewind-engine.js +0 -161
- package/dist/tracking/session-history.js +0 -128
- package/dist/tracking/session-receipt.js +0 -88
- package/dist/tracking/session-summary-writer.js +0 -157
- package/dist/tracking/shadow-ledger.js +0 -321
- package/dist/tracking/stash-manager.js +0 -258
- package/dist/tracking/timeline-fork.js +0 -213
- package/dist/tracking/timeline.js +0 -69
- package/dist/tracking/token-flow.js +0 -276
- package/dist/tracking/turn-segmenter.js +0 -122
- package/dist/tracking/weekly-accumulator.js +0 -179
- package/dist/tracking/working-snapshots.js +0 -188
- package/dist/tracking/workspace-manifest.js +0 -176
- package/dist/transport/http.js +0 -102
- package/dist/utils/counterfactual.js +0 -65
- package/dist/utils/deep-link.js +0 -34
- package/dist/utils/detect.js +0 -193
- package/dist/utils/exec.js +0 -73
- package/dist/utils/file-logger.js +0 -87
- package/dist/utils/format-error.js +0 -29
- package/dist/utils/git.js +0 -181
- package/dist/utils/log.js +0 -57
- package/dist/utils/logger.js +0 -35
- package/dist/utils/mcp-content-json.js +0 -8
- package/dist/utils/session-logger.js +0 -154
- package/dist/utils/startup-log.js +0 -512
- package/dist/utils/ui.js +0 -56
|
@@ -1,211 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Session Health Monitor — detects session degradation via 6 signal types.
|
|
3
|
-
*
|
|
4
|
-
* Tracks tool call patterns, entity targeting, convention violations, and
|
|
5
|
-
* context depth to produce a composite health score (0.0–1.0) and actionable
|
|
6
|
-
* recommendations. Designed to detect when an AI agent is struggling and
|
|
7
|
-
* suggest course corrections before the session spirals.
|
|
8
|
-
*
|
|
9
|
-
* Signal types:
|
|
10
|
-
* 1. repeated_query: same entity queried 3+ times (agent is looping)
|
|
11
|
-
* 2. low_durability_targeting: targeting entity with durability < 0.3
|
|
12
|
-
* 3. expanding_blast_radius: blast radius growing across queries
|
|
13
|
-
* 4. convention_violation_spike: 3+ violations within 5 minutes
|
|
14
|
-
* 5. tool_call_acceleration: tool call rate exceeding 10/min
|
|
15
|
-
* 6. context_depth_warning: estimated context tokens exceeding 80K
|
|
16
|
-
*
|
|
17
|
-
* Health score: starts at 1.0 (perfect), each signal reduces it.
|
|
18
|
-
*/
|
|
19
|
-
import { createModuleLogger } from "../utils/logger.js";
|
|
20
|
-
const log = createModuleLogger("session-health");
|
|
21
|
-
const REPEATED_QUERY_THRESHOLD = 3;
|
|
22
|
-
const LOW_DURABILITY_THRESHOLD = 0.3;
|
|
23
|
-
const VIOLATION_SPIKE_THRESHOLD = 3;
|
|
24
|
-
const VIOLATION_WINDOW_MS = 5 * 60 * 1000;
|
|
25
|
-
const TOOL_CALL_RATE_THRESHOLD = 10;
|
|
26
|
-
const CONTEXT_TOKEN_WARNING = 80_000;
|
|
27
|
-
const CONTEXT_TOKEN_CRITICAL = 120_000;
|
|
28
|
-
const SIGNAL_WEIGHTS = {
|
|
29
|
-
repeated_query: 0.1,
|
|
30
|
-
low_durability_targeting: 0.08,
|
|
31
|
-
expanding_blast_radius: 0.12,
|
|
32
|
-
convention_violation_spike: 0.15,
|
|
33
|
-
tool_call_acceleration: 0.1,
|
|
34
|
-
context_depth_warning: 0.2,
|
|
35
|
-
};
|
|
36
|
-
const TOKENS_PER_TOOL_CALL = 800;
|
|
37
|
-
/**
|
|
38
|
-
* Creates a session health monitor that accumulates signals over time
|
|
39
|
-
* and provides a composite health assessment on demand.
|
|
40
|
-
*/
|
|
41
|
-
export function createSessionHealthMonitor() {
|
|
42
|
-
let toolCalls = [];
|
|
43
|
-
let conventionViolations = [];
|
|
44
|
-
let blastRadiusHistory = [];
|
|
45
|
-
const entityDurability = new Map();
|
|
46
|
-
const entityQueryCounts = new Map();
|
|
47
|
-
function recordToolCall(name, entityKey) {
|
|
48
|
-
const now = Date.now();
|
|
49
|
-
toolCalls.push({ name, entityKey, timestamp: now });
|
|
50
|
-
if (entityKey) {
|
|
51
|
-
const count = entityQueryCounts.get(entityKey) ?? 0;
|
|
52
|
-
entityQueryCounts.set(entityKey, count + 1);
|
|
53
|
-
}
|
|
54
|
-
pruneOldRecords(now);
|
|
55
|
-
}
|
|
56
|
-
function recordConventionViolation() {
|
|
57
|
-
conventionViolations.push(Date.now());
|
|
58
|
-
}
|
|
59
|
-
function recordBlastRadius(entityKey, radius) {
|
|
60
|
-
blastRadiusHistory.push({
|
|
61
|
-
entityKey,
|
|
62
|
-
radius,
|
|
63
|
-
timestamp: Date.now(),
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
function recordDurability(entityKey, durability) {
|
|
67
|
-
entityDurability.set(entityKey, durability);
|
|
68
|
-
}
|
|
69
|
-
function getHealth() {
|
|
70
|
-
const now = Date.now();
|
|
71
|
-
const signals = [];
|
|
72
|
-
detectRepeatedQueries(signals);
|
|
73
|
-
detectLowDurabilityTargeting(signals);
|
|
74
|
-
detectExpandingBlastRadius(signals);
|
|
75
|
-
detectConventionViolationSpike(signals, now);
|
|
76
|
-
detectToolCallAcceleration(signals, now);
|
|
77
|
-
detectContextDepthWarning(signals);
|
|
78
|
-
const health = computeHealthScore(signals);
|
|
79
|
-
const recommendation = deriveRecommendation(health, signals);
|
|
80
|
-
return { health, signals, recommendation };
|
|
81
|
-
}
|
|
82
|
-
function reset() {
|
|
83
|
-
toolCalls = [];
|
|
84
|
-
conventionViolations = [];
|
|
85
|
-
blastRadiusHistory = [];
|
|
86
|
-
entityDurability.clear();
|
|
87
|
-
entityQueryCounts.clear();
|
|
88
|
-
}
|
|
89
|
-
function detectRepeatedQueries(signals) {
|
|
90
|
-
for (const [entity, count] of entityQueryCounts) {
|
|
91
|
-
if (count >= REPEATED_QUERY_THRESHOLD) {
|
|
92
|
-
signals.push({ type: "repeated_query", entity, count });
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
function detectLowDurabilityTargeting(signals) {
|
|
97
|
-
const recentEntities = new Set();
|
|
98
|
-
const recentCalls = toolCalls.slice(-20);
|
|
99
|
-
for (const call of recentCalls) {
|
|
100
|
-
if (call.entityKey)
|
|
101
|
-
recentEntities.add(call.entityKey);
|
|
102
|
-
}
|
|
103
|
-
for (const entity of recentEntities) {
|
|
104
|
-
const durability = entityDurability.get(entity);
|
|
105
|
-
if (durability !== undefined && durability < LOW_DURABILITY_THRESHOLD) {
|
|
106
|
-
signals.push({
|
|
107
|
-
type: "low_durability_targeting",
|
|
108
|
-
entity,
|
|
109
|
-
durability,
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
function detectExpandingBlastRadius(signals) {
|
|
115
|
-
if (blastRadiusHistory.length < 2)
|
|
116
|
-
return;
|
|
117
|
-
const sorted = [...blastRadiusHistory].sort((a, b) => a.timestamp - b.timestamp);
|
|
118
|
-
const firstThird = sorted.slice(0, Math.max(1, Math.floor(sorted.length / 3)));
|
|
119
|
-
const lastThird = sorted.slice(Math.max(0, sorted.length - Math.floor(sorted.length / 3)));
|
|
120
|
-
const initialAvg = firstThird.reduce((sum, r) => sum + r.radius, 0) / firstThird.length;
|
|
121
|
-
const currentAvg = lastThird.reduce((sum, r) => sum + r.radius, 0) / lastThird.length;
|
|
122
|
-
if (currentAvg > initialAvg * 1.5 && currentAvg > 5) {
|
|
123
|
-
signals.push({
|
|
124
|
-
type: "expanding_blast_radius",
|
|
125
|
-
initial: Math.round(initialAvg),
|
|
126
|
-
current: Math.round(currentAvg),
|
|
127
|
-
});
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
function detectConventionViolationSpike(signals, now) {
|
|
131
|
-
const windowStart = now - VIOLATION_WINDOW_MS;
|
|
132
|
-
const recentViolations = conventionViolations.filter((ts) => ts >= windowStart);
|
|
133
|
-
if (recentViolations.length >= VIOLATION_SPIKE_THRESHOLD) {
|
|
134
|
-
signals.push({
|
|
135
|
-
type: "convention_violation_spike",
|
|
136
|
-
count: recentViolations.length,
|
|
137
|
-
window_min: VIOLATION_WINDOW_MS / 60_000,
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
function detectToolCallAcceleration(signals, now) {
|
|
142
|
-
const oneMinuteAgo = now - 60_000;
|
|
143
|
-
const recentCalls = toolCalls.filter((tc) => tc.timestamp >= oneMinuteAgo);
|
|
144
|
-
if (recentCalls.length >= TOOL_CALL_RATE_THRESHOLD) {
|
|
145
|
-
signals.push({
|
|
146
|
-
type: "tool_call_acceleration",
|
|
147
|
-
rate_per_min: recentCalls.length,
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
function detectContextDepthWarning(signals) {
|
|
152
|
-
const estimatedTokens = toolCalls.length * TOKENS_PER_TOOL_CALL;
|
|
153
|
-
if (estimatedTokens >= CONTEXT_TOKEN_WARNING) {
|
|
154
|
-
signals.push({
|
|
155
|
-
type: "context_depth_warning",
|
|
156
|
-
estimated_tokens: estimatedTokens,
|
|
157
|
-
});
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
function pruneOldRecords(now) {
|
|
161
|
-
const sessionWindow = 60 * 60 * 1000;
|
|
162
|
-
const cutoff = now - sessionWindow;
|
|
163
|
-
toolCalls = toolCalls.filter((tc) => tc.timestamp >= cutoff);
|
|
164
|
-
conventionViolations = conventionViolations.filter((ts) => ts >= cutoff);
|
|
165
|
-
blastRadiusHistory = blastRadiusHistory.filter((br) => br.timestamp >= cutoff);
|
|
166
|
-
}
|
|
167
|
-
return {
|
|
168
|
-
recordToolCall,
|
|
169
|
-
recordConventionViolation,
|
|
170
|
-
recordBlastRadius,
|
|
171
|
-
recordDurability,
|
|
172
|
-
getHealth,
|
|
173
|
-
reset,
|
|
174
|
-
};
|
|
175
|
-
}
|
|
176
|
-
function computeHealthScore(signals) {
|
|
177
|
-
let health = 1.0;
|
|
178
|
-
const signalsByType = new Map();
|
|
179
|
-
for (const signal of signals) {
|
|
180
|
-
const count = signalsByType.get(signal.type) ?? 0;
|
|
181
|
-
signalsByType.set(signal.type, count + 1);
|
|
182
|
-
}
|
|
183
|
-
for (const [type, count] of signalsByType) {
|
|
184
|
-
const weight = SIGNAL_WEIGHTS[type];
|
|
185
|
-
const scaledPenalty = weight * Math.min(count, 3);
|
|
186
|
-
health -= scaledPenalty;
|
|
187
|
-
if (type === "context_depth_warning") {
|
|
188
|
-
const contextSignal = signals.find((s) => s.type === "context_depth_warning");
|
|
189
|
-
if (contextSignal &&
|
|
190
|
-
contextSignal.estimated_tokens >= CONTEXT_TOKEN_CRITICAL) {
|
|
191
|
-
health -= 0.15;
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
return Math.round(Math.max(0, Math.min(1, health)) * 100) / 100;
|
|
196
|
-
}
|
|
197
|
-
function deriveRecommendation(health, signals) {
|
|
198
|
-
if (health >= 0.8)
|
|
199
|
-
return "continue";
|
|
200
|
-
const hasContextWarning = signals.some((s) => s.type === "context_depth_warning");
|
|
201
|
-
const hasRepeatedQueries = signals.some((s) => s.type === "repeated_query");
|
|
202
|
-
if (health < 0.3)
|
|
203
|
-
return "suggest_new_session";
|
|
204
|
-
if (hasContextWarning && health < 0.6)
|
|
205
|
-
return "inject_context_refresh";
|
|
206
|
-
if (hasRepeatedQueries && health < 0.6)
|
|
207
|
-
return "suggest_pause";
|
|
208
|
-
if (health < 0.5)
|
|
209
|
-
return "suggest_pause";
|
|
210
|
-
return "inject_context_refresh";
|
|
211
|
-
}
|
|
@@ -1,197 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Session Narrative Capture — records what was built, why, and how as episodic facts.
|
|
3
|
-
*
|
|
4
|
-
* Works in BOTH `unerr` (daemon) and `unerr --mcp` (headless) modes.
|
|
5
|
-
* Does NOT depend on the behavior framework (which is daemon-only).
|
|
6
|
-
*
|
|
7
|
-
* Two capture points:
|
|
8
|
-
* 1. After each edit-type tool call → captures the investigation chain leading to the edit
|
|
9
|
-
* 2. At session shutdown → synthesizes a session summary
|
|
10
|
-
*
|
|
11
|
-
* All narratives are stored as episodic facts (decay_rate=0.00, never expires).
|
|
12
|
-
*/
|
|
13
|
-
/** Tool intent classification. */
|
|
14
|
-
const TOOL_INTENT = {
|
|
15
|
-
file_read: "exploration",
|
|
16
|
-
file_outline: "exploration",
|
|
17
|
-
get_entity: "investigation",
|
|
18
|
-
get_references: "investigation",
|
|
19
|
-
get_imports: "investigation",
|
|
20
|
-
search_code: "navigation",
|
|
21
|
-
get_file: "navigation",
|
|
22
|
-
get_conventions: "investigation",
|
|
23
|
-
get_critical_nodes: "analysis",
|
|
24
|
-
get_cross_boundary_links: "analysis",
|
|
25
|
-
get_project_stats: "analysis",
|
|
26
|
-
file_connections: "analysis",
|
|
27
|
-
get_test_coverage: "analysis",
|
|
28
|
-
};
|
|
29
|
-
/** Edit-type tool names (from agents' built-in tools). */
|
|
30
|
-
const EDIT_TOOLS = new Set([
|
|
31
|
-
"file_write",
|
|
32
|
-
"write_file",
|
|
33
|
-
"edit_file",
|
|
34
|
-
"str_replace_editor",
|
|
35
|
-
"Write",
|
|
36
|
-
"Edit",
|
|
37
|
-
]);
|
|
38
|
-
/** Extract feature area from file path (second directory segment). */
|
|
39
|
-
function extractFeatureArea(filePath) {
|
|
40
|
-
if (!filePath)
|
|
41
|
-
return "unknown";
|
|
42
|
-
const parts = filePath.replace(/^\.?\//, "").split("/");
|
|
43
|
-
// "src/proxy/foo.ts" → "proxy", "src/intelligence/bar.ts" → "intelligence"
|
|
44
|
-
return parts.length >= 2 ? (parts[1] ?? "unknown") : (parts[0] ?? "unknown");
|
|
45
|
-
}
|
|
46
|
-
/** Classify tool intent. */
|
|
47
|
-
function classifyToolIntent(toolName) {
|
|
48
|
-
return (TOOL_INTENT[toolName] ??
|
|
49
|
-
(EDIT_TOOLS.has(toolName) ? "modification" : "other"));
|
|
50
|
-
}
|
|
51
|
-
/** Summarize a tool call for sequence display. */
|
|
52
|
-
function summarizeToolCall(entry) {
|
|
53
|
-
const args = entry.args_summary;
|
|
54
|
-
const key = args.key ??
|
|
55
|
-
args.entity ??
|
|
56
|
-
args.file_path ??
|
|
57
|
-
"";
|
|
58
|
-
const shortKey = key.length > 40 ? `...${key.slice(-37)}` : key;
|
|
59
|
-
return shortKey ? `${entry.tool}(${shortKey})` : entry.tool;
|
|
60
|
-
}
|
|
61
|
-
export class SessionNarrativeCapture {
|
|
62
|
-
factStore;
|
|
63
|
-
ledger;
|
|
64
|
-
narratives = [];
|
|
65
|
-
filesModified = new Set();
|
|
66
|
-
constructor(factStore, ledger) {
|
|
67
|
-
this.factStore = factStore;
|
|
68
|
-
this.ledger = ledger;
|
|
69
|
-
}
|
|
70
|
-
/**
|
|
71
|
-
* Called after each edit-type tool call. Captures the investigation chain
|
|
72
|
-
* leading to the edit as an episodic fact. Non-blocking (caller should use setImmediate).
|
|
73
|
-
*/
|
|
74
|
-
async captureEditNarrative(editEntry) {
|
|
75
|
-
const filePath = editEntry.args_summary.file_path ??
|
|
76
|
-
editEntry.args_summary.path ??
|
|
77
|
-
"unknown";
|
|
78
|
-
this.filesModified.add(filePath);
|
|
79
|
-
// Get recent entries in the correlation window (30s before this edit)
|
|
80
|
-
const recent = this.ledger.getRecentEntries(50);
|
|
81
|
-
const editTs = new Date(editEntry.ts).getTime();
|
|
82
|
-
const windowMs = 30_000;
|
|
83
|
-
// Find preceding tool calls in the same correlation window
|
|
84
|
-
const chain = recent.filter((e) => {
|
|
85
|
-
if (e.id === editEntry.id)
|
|
86
|
-
return false;
|
|
87
|
-
const entryTs = new Date(e.ts).getTime();
|
|
88
|
-
return entryTs >= editTs - windowMs && entryTs <= editTs;
|
|
89
|
-
});
|
|
90
|
-
// Build the narrative from the investigation chain
|
|
91
|
-
const sequence = chain.map(summarizeToolCall);
|
|
92
|
-
sequence.push(summarizeToolCall(editEntry));
|
|
93
|
-
// Derive "what" from the edit target
|
|
94
|
-
const entity = editEntry.args_summary.entity ??
|
|
95
|
-
editEntry.args_summary.key ??
|
|
96
|
-
"";
|
|
97
|
-
const what = entity
|
|
98
|
-
? `Modified ${entity} in ${filePath}`
|
|
99
|
-
: `Modified ${filePath}`;
|
|
100
|
-
// Derive "why" from the investigation chain
|
|
101
|
-
const investigationTools = chain.filter((e) => classifyToolIntent(e.tool) === "investigation");
|
|
102
|
-
const why = investigationTools.length > 0
|
|
103
|
-
? `Investigated via ${investigationTools.map((e) => e.tool).join(" → ")} before modifying`
|
|
104
|
-
: "Direct modification";
|
|
105
|
-
// Derive "how" from the sequence
|
|
106
|
-
const how = sequence.length > 1
|
|
107
|
-
? sequence.join(" → ")
|
|
108
|
-
: `Direct edit: ${summarizeToolCall(editEntry)}`;
|
|
109
|
-
const changeType = editEntry.change_type ?? "modification";
|
|
110
|
-
const narrative = {
|
|
111
|
-
file_path: filePath,
|
|
112
|
-
what,
|
|
113
|
-
why,
|
|
114
|
-
how,
|
|
115
|
-
sequence,
|
|
116
|
-
change_type: changeType,
|
|
117
|
-
};
|
|
118
|
-
this.narratives.push(narrative);
|
|
119
|
-
// Store as episodic fact (decay=0.00, never expires)
|
|
120
|
-
const sessionId = this.ledger.getSessionId();
|
|
121
|
-
const content = `What: ${what}. Why: ${why}. How: ${how}. Sequence: ${sequence.join(", ")}`;
|
|
122
|
-
await this.factStore.createFact({
|
|
123
|
-
fact_type: "episodic",
|
|
124
|
-
scope: filePath,
|
|
125
|
-
subject: `edit:${sessionId}:${Date.now()}`,
|
|
126
|
-
content: content.slice(0, 800),
|
|
127
|
-
source: "session_analysis",
|
|
128
|
-
confidence: 0.6,
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
/**
|
|
132
|
-
* Called at session shutdown. Synthesizes a session summary from accumulated narratives.
|
|
133
|
-
* Works in both `unerr` and `unerr --mcp` modes.
|
|
134
|
-
*/
|
|
135
|
-
async captureSessionSummary(sessionId) {
|
|
136
|
-
const files = [...this.filesModified];
|
|
137
|
-
if (this.narratives.length === 0) {
|
|
138
|
-
return {
|
|
139
|
-
narratives: [],
|
|
140
|
-
filesModified: files,
|
|
141
|
-
summary: "No modifications captured.",
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
// Group narratives by feature area
|
|
145
|
-
const byArea = new Map();
|
|
146
|
-
for (const n of this.narratives) {
|
|
147
|
-
const area = extractFeatureArea(n.file_path);
|
|
148
|
-
let list = byArea.get(area);
|
|
149
|
-
if (!list) {
|
|
150
|
-
list = [];
|
|
151
|
-
byArea.set(area, list);
|
|
152
|
-
}
|
|
153
|
-
list.push(n);
|
|
154
|
-
}
|
|
155
|
-
// Build summary
|
|
156
|
-
const areaSummaries = [...byArea.entries()]
|
|
157
|
-
.map(([area, entries]) => {
|
|
158
|
-
const whats = entries.map((e) => e.what).slice(0, 3);
|
|
159
|
-
return `${area}: ${whats.join("; ")}`;
|
|
160
|
-
})
|
|
161
|
-
.slice(0, 5);
|
|
162
|
-
const summary = `Session modified ${files.length} file(s) across ${byArea.size} area(s). ${areaSummaries.join(". ")}`;
|
|
163
|
-
// Store session summary as episodic fact
|
|
164
|
-
await this.factStore.createFact({
|
|
165
|
-
fact_type: "episodic",
|
|
166
|
-
scope: "project",
|
|
167
|
-
subject: `session:${sessionId}`,
|
|
168
|
-
content: summary.slice(0, 800),
|
|
169
|
-
source: "session_analysis",
|
|
170
|
-
confidence: 0.7,
|
|
171
|
-
});
|
|
172
|
-
return { narratives: this.narratives, filesModified: files, summary };
|
|
173
|
-
}
|
|
174
|
-
/** Get narratives captured so far (for display/API). */
|
|
175
|
-
getNarratives() {
|
|
176
|
-
return this.narratives;
|
|
177
|
-
}
|
|
178
|
-
/** Get files modified this session. */
|
|
179
|
-
getFilesModified() {
|
|
180
|
-
return [...this.filesModified];
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Populate shadow ledger intent fields before append.
|
|
185
|
-
* Call this to derive change_type, feature_area, plan_summary from tool call context.
|
|
186
|
-
*/
|
|
187
|
-
export function deriveIntentFields(toolName, args, recentEntries) {
|
|
188
|
-
const filePath = args.file_path ??
|
|
189
|
-
args.path ??
|
|
190
|
-
args.key?.split("::")[0];
|
|
191
|
-
const change_type = classifyToolIntent(toolName);
|
|
192
|
-
const feature_area = extractFeatureArea(filePath);
|
|
193
|
-
// Build plan summary from last 3-5 tool calls in correlation window
|
|
194
|
-
const lastFew = recentEntries.slice(-5);
|
|
195
|
-
const plan_summary = lastFew.map(summarizeToolCall).join(" → ");
|
|
196
|
-
return { change_type, feature_area, plan_summary };
|
|
197
|
-
}
|
|
@@ -1,218 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Sprint 5: Session Pattern Analyzer — auto-detects facts from coding session patterns.
|
|
3
|
-
*
|
|
4
|
-
* Runs async (not in hot path) at two trigger points:
|
|
5
|
-
* 1. Every 20 tool calls (daemon mode only, via setImmediate)
|
|
6
|
-
* 2. At session shutdown (both unerr and unerr --mcp modes)
|
|
7
|
-
*
|
|
8
|
-
* Four sub-analyzers (all heuristic, no LLM):
|
|
9
|
-
* A. Entity Access Frequency — entities accessed 3+ times → procedural fact
|
|
10
|
-
* B. File Coupling — files co-occurring in correlation window 3+ times → semantic fact
|
|
11
|
-
* C. Hot File Detection — files read 5+ times → procedural fact
|
|
12
|
-
* D. Convention Stability — conventions stable across runs → high-confidence convention fact
|
|
13
|
-
*
|
|
14
|
-
* All use existing createFact() dedup: duplicate (fact_type, scope, subject) → reinforceFact().
|
|
15
|
-
*
|
|
16
|
-
* ── Content shape is forward-only ──────────────────────────────────────
|
|
17
|
-
* Fact content strings here are persisted to facts.db. Rewriting the
|
|
18
|
-
* template strings below (e.g., nudge wording v2.1 → v2.2) does NOT
|
|
19
|
-
* backfill existing rows — old facts keep their original content until
|
|
20
|
-
* the underlying signal disappears or is dedup-reinforced with new text.
|
|
21
|
-
* If a future rewrite needs to migrate stored facts, add an explicit
|
|
22
|
-
* one-shot migration that rewrites by (fact_type, scope, subject) match.
|
|
23
|
-
*/
|
|
24
|
-
/** Correlation window for grouping related tool calls. */
|
|
25
|
-
const CORRELATION_WINDOW_MS = 30_000;
|
|
26
|
-
/** Minimum access count thresholds (Sprint 7: raised to reduce noise). */
|
|
27
|
-
const ENTITY_ACCESS_THRESHOLD = 5;
|
|
28
|
-
const FILE_COUPLING_THRESHOLD = 3; // Already reasonable — keep
|
|
29
|
-
const HOT_FILE_THRESHOLD = 8;
|
|
30
|
-
/** Sprint 7: Minimum actionability — facts below this confidence are noise. */
|
|
31
|
-
const MIN_FACT_CONFIDENCE = 0.4;
|
|
32
|
-
/**
|
|
33
|
-
* Analyze session patterns from shadow ledger entries and create/reinforce facts.
|
|
34
|
-
*
|
|
35
|
-
* Designed to be called asynchronously — not in the tool-call hot path.
|
|
36
|
-
* Safe to call multiple times (idempotent via createFact dedup).
|
|
37
|
-
*/
|
|
38
|
-
export async function analyzeSessionPatterns(input) {
|
|
39
|
-
const { ledgerEntries, factStore, sessionId } = input;
|
|
40
|
-
const result = {
|
|
41
|
-
factsCreated: 0,
|
|
42
|
-
factsReinforced: 0,
|
|
43
|
-
patternsDetected: [],
|
|
44
|
-
};
|
|
45
|
-
if (ledgerEntries.length === 0)
|
|
46
|
-
return result;
|
|
47
|
-
// Run all sub-analyzers
|
|
48
|
-
const [entityResults, couplingResults, hotFileResults] = await Promise.all([
|
|
49
|
-
analyzeEntityAccess(ledgerEntries, factStore, sessionId),
|
|
50
|
-
analyzeFileCoupling(ledgerEntries, factStore),
|
|
51
|
-
analyzeHotFiles(ledgerEntries, factStore),
|
|
52
|
-
]);
|
|
53
|
-
// Aggregate results
|
|
54
|
-
for (const sub of [entityResults, couplingResults, hotFileResults]) {
|
|
55
|
-
result.factsCreated += sub.factsCreated;
|
|
56
|
-
result.factsReinforced += sub.factsReinforced;
|
|
57
|
-
result.patternsDetected.push(...sub.patternsDetected);
|
|
58
|
-
}
|
|
59
|
-
return result;
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Sub-analyzer A: Entity Access Frequency.
|
|
63
|
-
* Entities accessed >= 3 times → procedural fact about entity importance.
|
|
64
|
-
*/
|
|
65
|
-
async function analyzeEntityAccess(entries, factStore, sessionId) {
|
|
66
|
-
const result = {
|
|
67
|
-
factsCreated: 0,
|
|
68
|
-
factsReinforced: 0,
|
|
69
|
-
patternsDetected: [],
|
|
70
|
-
};
|
|
71
|
-
// Count entity accesses from tool args
|
|
72
|
-
const entityCounts = new Map();
|
|
73
|
-
for (const entry of entries) {
|
|
74
|
-
const entityKey = entry.args_summary.key ??
|
|
75
|
-
entry.args_summary.entity;
|
|
76
|
-
const filePath = entry.args_summary.file_path ??
|
|
77
|
-
entry.args_summary.path;
|
|
78
|
-
if (entityKey) {
|
|
79
|
-
const existing = entityCounts.get(entityKey);
|
|
80
|
-
if (existing) {
|
|
81
|
-
existing.count++;
|
|
82
|
-
if (filePath)
|
|
83
|
-
existing.file = filePath;
|
|
84
|
-
}
|
|
85
|
-
else {
|
|
86
|
-
entityCounts.set(entityKey, {
|
|
87
|
-
count: 1,
|
|
88
|
-
file: filePath ?? "unknown",
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
// Create facts for frequently accessed entities
|
|
94
|
-
for (const [entityKey, data] of entityCounts) {
|
|
95
|
-
const confidence = Math.min(0.5 + data.count * 0.05, 0.85);
|
|
96
|
-
if (data.count >= ENTITY_ACCESS_THRESHOLD &&
|
|
97
|
-
confidence >= MIN_FACT_CONFIDENCE) {
|
|
98
|
-
await factStore.createFact({
|
|
99
|
-
fact_type: "procedural",
|
|
100
|
-
scope: data.file,
|
|
101
|
-
subject: entityKey,
|
|
102
|
-
content: `${entityKey} — key entity (accessed ${data.count}× in session ${sessionId}) — pin via record_fact if it's a stable invariant`,
|
|
103
|
-
source: "session_analysis",
|
|
104
|
-
confidence,
|
|
105
|
-
});
|
|
106
|
-
result.factsCreated++;
|
|
107
|
-
result.patternsDetected.push(`entity:${entityKey}(${data.count}x)`);
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
return result;
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* Sub-analyzer B: File Coupling.
|
|
114
|
-
* Files co-occurring in correlation windows >= 3 times → semantic fact.
|
|
115
|
-
*/
|
|
116
|
-
async function analyzeFileCoupling(entries, factStore) {
|
|
117
|
-
const result = {
|
|
118
|
-
factsCreated: 0,
|
|
119
|
-
factsReinforced: 0,
|
|
120
|
-
patternsDetected: [],
|
|
121
|
-
};
|
|
122
|
-
// Group entries into correlation windows
|
|
123
|
-
const windows = [];
|
|
124
|
-
let currentWindow = [];
|
|
125
|
-
for (const entry of entries) {
|
|
126
|
-
const ts = new Date(entry.ts).getTime();
|
|
127
|
-
if (currentWindow.length === 0 ||
|
|
128
|
-
ts - new Date(currentWindow[0].ts).getTime() <= CORRELATION_WINDOW_MS) {
|
|
129
|
-
currentWindow.push(entry);
|
|
130
|
-
}
|
|
131
|
-
else {
|
|
132
|
-
if (currentWindow.length > 0)
|
|
133
|
-
windows.push(currentWindow);
|
|
134
|
-
currentWindow = [entry];
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
if (currentWindow.length > 0)
|
|
138
|
-
windows.push(currentWindow);
|
|
139
|
-
// Count file co-occurrences within windows
|
|
140
|
-
const coOccurrences = new Map();
|
|
141
|
-
for (const window of windows) {
|
|
142
|
-
const filesInWindow = new Set();
|
|
143
|
-
for (const entry of window) {
|
|
144
|
-
const filePath = entry.args_summary.file_path ??
|
|
145
|
-
entry.args_summary.path;
|
|
146
|
-
if (filePath)
|
|
147
|
-
filesInWindow.add(filePath);
|
|
148
|
-
}
|
|
149
|
-
// Generate sorted pairs
|
|
150
|
-
const fileList = [...filesInWindow].sort();
|
|
151
|
-
for (let i = 0; i < fileList.length; i++) {
|
|
152
|
-
for (let j = i + 1; j < fileList.length; j++) {
|
|
153
|
-
const pairKey = `${fileList[i]}↔${fileList[j]}`;
|
|
154
|
-
coOccurrences.set(pairKey, (coOccurrences.get(pairKey) ?? 0) + 1);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
// Create facts for frequently coupled files
|
|
159
|
-
for (const [pairKey, count] of coOccurrences) {
|
|
160
|
-
const confidence = Math.min(0.5 + count * 0.05, 0.85);
|
|
161
|
-
if (count >= FILE_COUPLING_THRESHOLD && confidence >= MIN_FACT_CONFIDENCE) {
|
|
162
|
-
const [fileA, fileB] = pairKey.split("↔");
|
|
163
|
-
await factStore.createFact({
|
|
164
|
-
fact_type: "semantic",
|
|
165
|
-
scope: "project",
|
|
166
|
-
subject: `coupling:${pairKey}`,
|
|
167
|
-
content: `${fileA} ↔ ${fileB} co-change (${count}×) — open both before editing either`,
|
|
168
|
-
source: "session_analysis",
|
|
169
|
-
confidence,
|
|
170
|
-
});
|
|
171
|
-
result.factsCreated++;
|
|
172
|
-
result.patternsDetected.push(`coupling:${shortPath(fileA)}↔${shortPath(fileB)}(${count}x)`);
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
return result;
|
|
176
|
-
}
|
|
177
|
-
/**
|
|
178
|
-
* Sub-analyzer C: Hot File Detection.
|
|
179
|
-
* Files accessed via file_read >= 5 times → procedural fact about file importance.
|
|
180
|
-
*/
|
|
181
|
-
async function analyzeHotFiles(entries, factStore) {
|
|
182
|
-
const result = {
|
|
183
|
-
factsCreated: 0,
|
|
184
|
-
factsReinforced: 0,
|
|
185
|
-
patternsDetected: [],
|
|
186
|
-
};
|
|
187
|
-
const fileCounts = new Map();
|
|
188
|
-
for (const entry of entries) {
|
|
189
|
-
const filePath = entry.args_summary.file_path ??
|
|
190
|
-
entry.args_summary.path;
|
|
191
|
-
if (filePath) {
|
|
192
|
-
fileCounts.set(filePath, (fileCounts.get(filePath) ?? 0) + 1);
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
for (const [filePath, count] of fileCounts) {
|
|
196
|
-
const confidence = Math.min(0.5 + count * 0.03, 0.8);
|
|
197
|
-
if (count >= HOT_FILE_THRESHOLD && confidence >= MIN_FACT_CONFIDENCE) {
|
|
198
|
-
await factStore.createFact({
|
|
199
|
-
fact_type: "procedural",
|
|
200
|
-
scope: filePath,
|
|
201
|
-
subject: "hot-file",
|
|
202
|
-
// Imperative tail so the agent has a concrete follow-up — bare
|
|
203
|
-
// "hot file (N accesses)" is descriptive only and gets discarded.
|
|
204
|
-
content: `${filePath} — hot file (${count} accesses) — call get_test_coverage to verify it has coverage`,
|
|
205
|
-
source: "session_analysis",
|
|
206
|
-
confidence,
|
|
207
|
-
});
|
|
208
|
-
result.factsCreated++;
|
|
209
|
-
result.patternsDetected.push(`hot-file:${shortPath(filePath)}(${count}x)`);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
return result;
|
|
213
|
-
}
|
|
214
|
-
/** Shorten a file path for display (last 2 segments). */
|
|
215
|
-
function shortPath(filePath) {
|
|
216
|
-
const parts = filePath.split("/");
|
|
217
|
-
return parts.length > 2 ? parts.slice(-2).join("/") : filePath;
|
|
218
|
-
}
|