observability-toolkit-hooks 0.0.0-stage → 1.0.1
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/CONFIG.md +144 -0
- package/LICENSE +95 -0
- package/README.md +201 -2
- package/dist/handlers/compact.js +38 -0
- package/dist/handlers/mcp-status.js +66 -0
- package/dist/handlers/notification.js +45 -0
- package/dist/handlers/post-tool-agent.js +157 -0
- package/dist/handlers/post-tool-changelog-sync.js +148 -0
- package/dist/handlers/post-tool-code-structure.js +116 -0
- package/dist/handlers/post-tool-edit-ledger.js +15 -0
- package/dist/handlers/post-tool-failure.js +83 -0
- package/dist/handlers/post-tool-git.js +79 -0
- package/dist/handlers/post-tool-mcp.js +105 -0
- package/dist/handlers/post-tool-outcome.js +48 -0
- package/dist/handlers/post-tool-task-state.js +74 -0
- package/dist/handlers/post-tool.js +132 -0
- package/dist/handlers/pre-tool-agent.js +192 -0
- package/dist/handlers/pre-tool.js +218 -0
- package/dist/handlers/session-end.js +39 -0
- package/dist/handlers/session-start.js +262 -0
- package/dist/handlers/stop-error-reminder.js +195 -0
- package/dist/handlers/stop-quality-evaluation.js +58 -0
- package/dist/handlers/stop-session-summary.js +62 -0
- package/dist/handlers/stop-token-metrics.js +83 -0
- package/dist/handlers/stop.js +25 -0
- package/dist/handlers/subagent.js +105 -0
- package/dist/handlers/tool-event-router.js +39 -0
- package/dist/handlers/user-prompt.js +218 -0
- package/dist/hook-runner.js +10 -0
- package/dist/hook-runner.js.map +7 -0
- package/dist/lib/agent/agent-context.js +123 -0
- package/dist/lib/agent/agent-evaluations.js +155 -0
- package/dist/lib/agent/agent-file-budget.js +65 -0
- package/dist/lib/agent/agent-sources.js +165 -0
- package/dist/lib/agent/synth-spans.js +51 -0
- package/dist/lib/core/bounded-label.js +6 -0
- package/dist/lib/core/category-rules.js +11 -0
- package/dist/lib/core/child-result.js +19 -0
- package/dist/lib/core/config-dir-recovery.js +22 -0
- package/dist/lib/core/constants.js +171 -0
- package/dist/lib/core/detached-runner.js +55 -0
- package/dist/lib/core/file-utils.js +353 -0
- package/dist/lib/core/format-utils.js +51 -0
- package/dist/lib/core/http-utils.js +74 -0
- package/dist/lib/core/http1-fetch.js +14 -0
- package/dist/lib/core/identity-key-resolver.js +149 -0
- package/dist/lib/core/jsonl-tail.js +207 -0
- package/dist/lib/core/load-envrc.js +72 -0
- package/dist/lib/core/parsers.js +43 -0
- package/dist/lib/core/regex.js +27 -0
- package/dist/lib/core/settings-env.js +31 -0
- package/dist/lib/core/shell-command.js +122 -0
- package/dist/lib/core/units.js +97 -0
- package/dist/lib/git/git-cache.js +158 -0
- package/dist/lib/git/git-commit.js +189 -0
- package/dist/lib/git/git-exec.js +30 -0
- package/dist/lib/mcp/mcp-completeness.js +40 -0
- package/dist/lib/mcp/mcp-config.js +118 -0
- package/dist/lib/mcp/mcp-failure-latch.js +22 -0
- package/dist/lib/mcp/mcp-identity-launcher.js +43 -0
- package/dist/lib/otel/attributes.js +322 -0
- package/dist/lib/otel/evaluation-attrs.js +51 -0
- package/dist/lib/otel/file-exporters.js +169 -0
- package/dist/lib/otel/host-resource.js +61 -0
- package/dist/lib/otel/otel-headers-helper.js +26 -0
- package/dist/lib/otel/otel-monitor.js +181 -0
- package/dist/lib/otel/otel.js +235 -0
- package/dist/lib/otel/otlp-headers.js +101 -0
- package/dist/lib/otel/otlp-post.js +122 -0
- package/dist/lib/otel/otlp-serialize.js +142 -0
- package/dist/lib/otel/otlp-signal.js +2 -0
- package/dist/lib/otel/remote-spans.js +142 -0
- package/dist/lib/otel/service-identity.js +10 -0
- package/dist/lib/otel/telemetry-alerts.js +43 -0
- package/dist/lib/otel/token-metrics.js +122 -0
- package/dist/lib/otel/trace-context.js +81 -0
- package/dist/lib/quality/judge-meta-eval.js +70 -0
- package/dist/lib/quality/judge-prompts.js +104 -0
- package/dist/lib/quality/judge-providers.js +193 -0
- package/dist/lib/quality/judge-transport.js +93 -0
- package/dist/lib/quality/llm-judge.js +170 -0
- package/dist/lib/quality/quality-budget.js +99 -0
- package/dist/lib/quality/quality-degradation.js +156 -0
- package/dist/lib/quality/quality-eval-handoff.js +74 -0
- package/dist/lib/quality/quality-evaluator.js +178 -0
- package/dist/lib/quality/quality-sampler.js +43 -0
- package/dist/lib/quality/quality-signals.js +150 -0
- package/dist/lib/runtime/categorizers.js +101 -0
- package/dist/lib/runtime/hook-input.js +16 -0
- package/dist/lib/runtime/hook-output.js +50 -0
- package/dist/lib/runtime/output-analyzer.js +160 -0
- package/dist/lib/runtime/run-handlers.js +32 -0
- package/dist/lib/runtime/tool-input.js +111 -0
- package/dist/lib/runtime/tool-output.js +44 -0
- package/dist/lib/runtime/unknown-tool.js +32 -0
- package/dist/lib/session/edit-ledger.js +29 -0
- package/dist/lib/session/forked-skill.js +39 -0
- package/dist/lib/session/handoffs.js +77 -0
- package/dist/lib/session/session-state.js +169 -0
- package/dist/lib/session/skill-rules.js +196 -0
- package/dist/lib/session/task-tracker.js +83 -0
- package/dist/lib/shipper/shipper-credentials.js +38 -0
- package/dist/lib/shipper/shipper-cursor.js +89 -0
- package/dist/lib/shipper/shipper-status.js +174 -0
- package/dist/lib/shipper/span-shipper.js +272 -0
- package/dist/lib/shipper/telemetry-shipper.js +39 -0
- package/dist/lib/transcript/agent-transcript-metrics.js +34 -0
- package/dist/lib/transcript/context-breakdown.js +134 -0
- package/dist/lib/transcript/context-history.js +69 -0
- package/dist/lib/transcript/context-tracker.js +226 -0
- package/dist/lib/transcript/message-count.js +49 -0
- package/dist/lib/transcript/model-ids.js +36 -0
- package/dist/lib/transcript/model-pricing.js +153 -0
- package/dist/lib/transcript/token-metrics-checkpoint.js +152 -0
- package/dist/lib/transcript/tool-call-durations.js +64 -0
- package/dist/lib/transcript/transcript-entry.js +67 -0
- package/dist/lib/transcript/transcript-fold.js +130 -0
- package/dist/lib/transcript/transcript-layout.js +39 -0
- package/dist/lib/transcript/transcript-parser.js +117 -0
- package/dist/runner/agent-context-4XTCLMLZ.js +23 -0
- package/dist/runner/agent-context-4XTCLMLZ.js.map +7 -0
- package/dist/runner/agent-file-budget-Q33ESBBE.js +68 -0
- package/dist/runner/agent-file-budget-Q33ESBBE.js.map +7 -0
- package/dist/runner/agent-transcript-metrics-W5CZZFMI.js +39 -0
- package/dist/runner/agent-transcript-metrics-W5CZZFMI.js.map +7 -0
- package/dist/runner/chunk-2NTNAJZE.js +49 -0
- package/dist/runner/chunk-2NTNAJZE.js.map +7 -0
- package/dist/runner/chunk-4KWBQTTG.js +78 -0
- package/dist/runner/chunk-4KWBQTTG.js.map +7 -0
- package/dist/runner/chunk-52RY6LQT.js +699 -0
- package/dist/runner/chunk-52RY6LQT.js.map +7 -0
- package/dist/runner/chunk-7OM5CYES.js +8695 -0
- package/dist/runner/chunk-7OM5CYES.js.map +7 -0
- package/dist/runner/chunk-7PEOKGYR.js +1568 -0
- package/dist/runner/chunk-7PEOKGYR.js.map +7 -0
- package/dist/runner/chunk-AGSGKELQ.js +126 -0
- package/dist/runner/chunk-AGSGKELQ.js.map +7 -0
- package/dist/runner/chunk-AVM7PJFW.js +12 -0
- package/dist/runner/chunk-AVM7PJFW.js.map +7 -0
- package/dist/runner/chunk-C3WHUMU5.js +178 -0
- package/dist/runner/chunk-C3WHUMU5.js.map +7 -0
- package/dist/runner/chunk-DGB4NSSD.js +157 -0
- package/dist/runner/chunk-DGB4NSSD.js.map +7 -0
- package/dist/runner/chunk-DNSTWC26.js +151 -0
- package/dist/runner/chunk-DNSTWC26.js.map +7 -0
- package/dist/runner/chunk-FDJJ3TYU.js +449 -0
- package/dist/runner/chunk-FDJJ3TYU.js.map +7 -0
- package/dist/runner/chunk-FGKYDQHZ.js +137 -0
- package/dist/runner/chunk-FGKYDQHZ.js.map +7 -0
- package/dist/runner/chunk-GG2I4TGI.js +582 -0
- package/dist/runner/chunk-GG2I4TGI.js.map +7 -0
- package/dist/runner/chunk-GNNKUMRF.js +60 -0
- package/dist/runner/chunk-GNNKUMRF.js.map +7 -0
- package/dist/runner/chunk-I7TD2QVR.js +118 -0
- package/dist/runner/chunk-I7TD2QVR.js.map +7 -0
- package/dist/runner/chunk-IJ4SLUBV.js +78 -0
- package/dist/runner/chunk-IJ4SLUBV.js.map +7 -0
- package/dist/runner/chunk-IY7AP7NA.js +32 -0
- package/dist/runner/chunk-IY7AP7NA.js.map +7 -0
- package/dist/runner/chunk-J3F3Z3EQ.js +177 -0
- package/dist/runner/chunk-J3F3Z3EQ.js.map +7 -0
- package/dist/runner/chunk-JLEO5OHU.js +104 -0
- package/dist/runner/chunk-JLEO5OHU.js.map +7 -0
- package/dist/runner/chunk-JRNNLOPR.js +168 -0
- package/dist/runner/chunk-JRNNLOPR.js.map +7 -0
- package/dist/runner/chunk-KGSA5JYP.js +82 -0
- package/dist/runner/chunk-KGSA5JYP.js.map +7 -0
- package/dist/runner/chunk-LBCZAYFR.js +125 -0
- package/dist/runner/chunk-LBCZAYFR.js.map +7 -0
- package/dist/runner/chunk-LHWRXY2G.js +41 -0
- package/dist/runner/chunk-LHWRXY2G.js.map +7 -0
- package/dist/runner/chunk-LQ2LGUYJ.js +41 -0
- package/dist/runner/chunk-LQ2LGUYJ.js.map +7 -0
- package/dist/runner/chunk-LYY6RCIE.js +158 -0
- package/dist/runner/chunk-LYY6RCIE.js.map +7 -0
- package/dist/runner/chunk-M4R4QIQH.js +41 -0
- package/dist/runner/chunk-M4R4QIQH.js.map +7 -0
- package/dist/runner/chunk-MC75VXMX.js +207 -0
- package/dist/runner/chunk-MC75VXMX.js.map +7 -0
- package/dist/runner/chunk-NKZU4RRG.js +104 -0
- package/dist/runner/chunk-NKZU4RRG.js.map +7 -0
- package/dist/runner/chunk-PJHWHJ3K.js +56 -0
- package/dist/runner/chunk-PJHWHJ3K.js.map +7 -0
- package/dist/runner/chunk-RIGVYJ2O.js +114 -0
- package/dist/runner/chunk-RIGVYJ2O.js.map +7 -0
- package/dist/runner/chunk-RWRGC7ZK.js +93 -0
- package/dist/runner/chunk-RWRGC7ZK.js.map +7 -0
- package/dist/runner/chunk-SRMAJQMV.js +54 -0
- package/dist/runner/chunk-SRMAJQMV.js.map +7 -0
- package/dist/runner/chunk-TRMFD36J.js +47 -0
- package/dist/runner/chunk-TRMFD36J.js.map +7 -0
- package/dist/runner/chunk-U4IOZYQ3.js +21 -0
- package/dist/runner/chunk-U4IOZYQ3.js.map +7 -0
- package/dist/runner/chunk-UEXDE3WP.js +83 -0
- package/dist/runner/chunk-UEXDE3WP.js.map +7 -0
- package/dist/runner/chunk-UW3GQZSM.js +50 -0
- package/dist/runner/chunk-UW3GQZSM.js.map +7 -0
- package/dist/runner/chunk-V2GSP6VR.js +46 -0
- package/dist/runner/chunk-V2GSP6VR.js.map +7 -0
- package/dist/runner/chunk-VOV4Y5VU.js +81 -0
- package/dist/runner/chunk-VOV4Y5VU.js.map +7 -0
- package/dist/runner/chunk-VT5T6OEI.js +65 -0
- package/dist/runner/chunk-VT5T6OEI.js.map +7 -0
- package/dist/runner/chunk-VUYVFWIN.js +12 -0
- package/dist/runner/chunk-VUYVFWIN.js.map +7 -0
- package/dist/runner/chunk-VVGOPPEN.js +36 -0
- package/dist/runner/chunk-VVGOPPEN.js.map +7 -0
- package/dist/runner/chunk-VXFSLM6P.js +14 -0
- package/dist/runner/chunk-VXFSLM6P.js.map +7 -0
- package/dist/runner/chunk-W3EK7JUT.js +26125 -0
- package/dist/runner/chunk-W3EK7JUT.js.map +7 -0
- package/dist/runner/chunk-WJHNCOUF.js +52 -0
- package/dist/runner/chunk-WJHNCOUF.js.map +7 -0
- package/dist/runner/chunk-WU7ANGCW.js +269 -0
- package/dist/runner/chunk-WU7ANGCW.js.map +7 -0
- package/dist/runner/chunk-X7XLMSZX.js +44 -0
- package/dist/runner/chunk-X7XLMSZX.js.map +7 -0
- package/dist/runner/chunk-XSO3B4QN.js +124 -0
- package/dist/runner/chunk-XSO3B4QN.js.map +7 -0
- package/dist/runner/chunk-YGFN3LN2.js +174 -0
- package/dist/runner/chunk-YGFN3LN2.js.map +7 -0
- package/dist/runner/chunk-YHYDBLVB.js +33 -0
- package/dist/runner/chunk-YHYDBLVB.js.map +7 -0
- package/dist/runner/compact-36NP3PKT.js +60 -0
- package/dist/runner/compact-36NP3PKT.js.map +7 -0
- package/dist/runner/getMachineId-bsd-AGENNHN6.js +42 -0
- package/dist/runner/getMachineId-bsd-AGENNHN6.js.map +7 -0
- package/dist/runner/getMachineId-bsd-I5WZGCL4.js +33 -0
- package/dist/runner/getMachineId-bsd-I5WZGCL4.js.map +7 -0
- package/dist/runner/getMachineId-bsd-ZXK225P7.js +33 -0
- package/dist/runner/getMachineId-bsd-ZXK225P7.js.map +7 -0
- package/dist/runner/getMachineId-darwin-47GDLEXL.js +42 -0
- package/dist/runner/getMachineId-darwin-47GDLEXL.js.map +7 -0
- package/dist/runner/getMachineId-darwin-5CRLMDD6.js +33 -0
- package/dist/runner/getMachineId-darwin-5CRLMDD6.js.map +7 -0
- package/dist/runner/getMachineId-darwin-ADG4I32N.js +33 -0
- package/dist/runner/getMachineId-darwin-ADG4I32N.js.map +7 -0
- package/dist/runner/getMachineId-linux-5KVS3T2M.js +27 -0
- package/dist/runner/getMachineId-linux-5KVS3T2M.js.map +7 -0
- package/dist/runner/getMachineId-linux-GDFB5GSO.js +34 -0
- package/dist/runner/getMachineId-linux-GDFB5GSO.js.map +7 -0
- package/dist/runner/getMachineId-linux-NQMWCRO3.js +27 -0
- package/dist/runner/getMachineId-linux-NQMWCRO3.js.map +7 -0
- package/dist/runner/getMachineId-unsupported-5PFIGMVX.js +18 -0
- package/dist/runner/getMachineId-unsupported-5PFIGMVX.js.map +7 -0
- package/dist/runner/getMachineId-unsupported-DW27K3ZX.js +18 -0
- package/dist/runner/getMachineId-unsupported-DW27K3ZX.js.map +7 -0
- package/dist/runner/getMachineId-unsupported-XV3FHTHD.js +25 -0
- package/dist/runner/getMachineId-unsupported-XV3FHTHD.js.map +7 -0
- package/dist/runner/getMachineId-win-5JVMW3EI.js +44 -0
- package/dist/runner/getMachineId-win-5JVMW3EI.js.map +7 -0
- package/dist/runner/getMachineId-win-SNESQF7R.js +35 -0
- package/dist/runner/getMachineId-win-SNESQF7R.js.map +7 -0
- package/dist/runner/getMachineId-win-UJYHSBM2.js +35 -0
- package/dist/runner/getMachineId-win-UJYHSBM2.js.map +7 -0
- package/dist/runner/git-commit-BA53DOJQ.js +30 -0
- package/dist/runner/git-commit-BA53DOJQ.js.map +7 -0
- package/dist/runner/hook-runner-JHH6PGKE.js +220 -0
- package/dist/runner/hook-runner-JHH6PGKE.js.map +7 -0
- package/dist/runner/judge-transport-R4TF5LEH.js +91 -0
- package/dist/runner/judge-transport-R4TF5LEH.js.map +7 -0
- package/dist/runner/mcp-status-QEUH2KGX.js +89 -0
- package/dist/runner/mcp-status-QEUH2KGX.js.map +7 -0
- package/dist/runner/notification-FKMBCSXF.js +69 -0
- package/dist/runner/notification-FKMBCSXF.js.map +7 -0
- package/dist/runner/post-tool-3MRHTBKH.js +192 -0
- package/dist/runner/post-tool-3MRHTBKH.js.map +7 -0
- package/dist/runner/post-tool-agent-BB34MNHI.js +370 -0
- package/dist/runner/post-tool-agent-BB34MNHI.js.map +7 -0
- package/dist/runner/post-tool-changelog-sync-OP2TT2I7.js +147 -0
- package/dist/runner/post-tool-changelog-sync-OP2TT2I7.js.map +7 -0
- package/dist/runner/post-tool-code-structure-LE7J2SC2.js +130 -0
- package/dist/runner/post-tool-code-structure-LE7J2SC2.js.map +7 -0
- package/dist/runner/post-tool-edit-ledger-IJMEYHKF.js +30 -0
- package/dist/runner/post-tool-edit-ledger-IJMEYHKF.js.map +7 -0
- package/dist/runner/post-tool-failure-XTH2I2Z7.js +111 -0
- package/dist/runner/post-tool-failure-XTH2I2Z7.js.map +7 -0
- package/dist/runner/post-tool-git-E46HZGZO.js +94 -0
- package/dist/runner/post-tool-git-E46HZGZO.js.map +7 -0
- package/dist/runner/post-tool-mcp-AMCDY5GH.js +144 -0
- package/dist/runner/post-tool-mcp-AMCDY5GH.js.map +7 -0
- package/dist/runner/post-tool-task-state-TLDOI33H.js +100 -0
- package/dist/runner/post-tool-task-state-TLDOI33H.js.map +7 -0
- package/dist/runner/pre-tool-SQE2FZQO.js +245 -0
- package/dist/runner/pre-tool-SQE2FZQO.js.map +7 -0
- package/dist/runner/pre-tool-agent-OZUPVFUI.js +218 -0
- package/dist/runner/pre-tool-agent-OZUPVFUI.js.map +7 -0
- package/dist/runner/quality-evaluator-XYNDKDRG.js +901 -0
- package/dist/runner/quality-evaluator-XYNDKDRG.js.map +7 -0
- package/dist/runner/session-end-3MJTDLLA.js +57 -0
- package/dist/runner/session-end-3MJTDLLA.js.map +7 -0
- package/dist/runner/session-start-5ZMCLKBS.js +352 -0
- package/dist/runner/session-start-5ZMCLKBS.js.map +7 -0
- package/dist/runner/shipper-status-MADX6SPG.js +37 -0
- package/dist/runner/shipper-status-MADX6SPG.js.map +7 -0
- package/dist/runner/span-shipper-4HQDHC47.js +3408 -0
- package/dist/runner/span-shipper-4HQDHC47.js.map +7 -0
- package/dist/runner/stop-RTKSIYJV.js +596 -0
- package/dist/runner/stop-RTKSIYJV.js.map +7 -0
- package/dist/runner/subagent-CBCG4OLZ.js +116 -0
- package/dist/runner/subagent-CBCG4OLZ.js.map +7 -0
- package/dist/runner/token-metrics-AD2RAFGM.js +31 -0
- package/dist/runner/token-metrics-AD2RAFGM.js.map +7 -0
- package/dist/runner/user-prompt-T5NZ2UJD.js +376 -0
- package/dist/runner/user-prompt-T5NZ2UJD.js.map +7 -0
- package/package.json +70 -5
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/** PreToolUse router: agent scope guards first, then MCP / plugin / agent / builtin instrumentation. */
|
|
2
|
+
import { getSkillSourceType } from '../lib/agent/agent-sources.js';
|
|
3
|
+
import { BUILTIN_TOOLS, INPUT_PREVIEW_CHARS } from '../lib/core/constants.js';
|
|
4
|
+
import { writeStderr } from '../lib/core/format-utils.js';
|
|
5
|
+
import { parseSkillName, parseMcpToolName, getInputSummary, mcpLabelsOf, pluginLabelsOf } from '../lib/core/parsers.js';
|
|
6
|
+
import { commandInvocations, isOptionArg, programOf } from '../lib/core/shell-command.js';
|
|
7
|
+
import { UNITS } from '../lib/core/units.js';
|
|
8
|
+
import { FILE_PATH_ATTR, HOOK_NAMES, HOOK_TYPE_ATTR, MCP_ATTRS, PLUGIN_ATTRS } from '../lib/otel/attributes.js';
|
|
9
|
+
import { instrumentHook } from '../lib/otel/otel-monitor.js';
|
|
10
|
+
import { categorizeSkill, builtinToolLabels } from '../lib/runtime/categorizers.js';
|
|
11
|
+
import { lazy } from '../lib/runtime/run-handlers.js';
|
|
12
|
+
import { getFileExtension, getReplacedText, getScalarText, getStringField, getTargetPath, getWrittenText, isEditTool, mayRunGitCommit } from '../lib/runtime/tool-input.js';
|
|
13
|
+
import { routeToolEvent } from './tool-event-router.js';
|
|
14
|
+
const handleAgentScopeGuards = lazy(async () => (await import('./pre-tool-agent.js')).handleAgentScopeGuards);
|
|
15
|
+
const handleAgentPreTool = lazy(async () => (await import('./pre-tool-agent.js')).handleAgentPreTool);
|
|
16
|
+
// ==================== MCP Pre-Tool ====================
|
|
17
|
+
async function handleMcpPreTool(input) {
|
|
18
|
+
const mcpInfo = parseMcpToolName(input.tool_name);
|
|
19
|
+
if (!mcpInfo)
|
|
20
|
+
return;
|
|
21
|
+
await instrumentHook(HOOK_NAMES.MCP_PRE_TOOL, (ctx) => {
|
|
22
|
+
const toolInput = input.tool_input ?? {};
|
|
23
|
+
const mcpLabels = mcpLabelsOf(mcpInfo);
|
|
24
|
+
ctx.addAttributes({
|
|
25
|
+
...mcpLabels,
|
|
26
|
+
[MCP_ATTRS.FULL_NAME]: mcpInfo.fullName,
|
|
27
|
+
'integritystudio.mcp.input_params': Object.keys(toolInput).join(','),
|
|
28
|
+
'integritystudio.mcp.input_count': Object.keys(toolInput).length,
|
|
29
|
+
});
|
|
30
|
+
ctx.logger.info('MCP tool invoked', {
|
|
31
|
+
...mcpLabels,
|
|
32
|
+
'integritystudio.mcp.params': getInputSummary(toolInput),
|
|
33
|
+
});
|
|
34
|
+
ctx.recordMetric('integritystudio.mcp.invocations', 1, mcpLabels, { unit: UNITS.INVOCATION });
|
|
35
|
+
writeStderr(`[MCP] ${mcpInfo.server}/${mcpInfo.tool}`);
|
|
36
|
+
}, { [HOOK_TYPE_ATTR]: 'mcp' });
|
|
37
|
+
}
|
|
38
|
+
// ==================== Plugin Pre-Tool ====================
|
|
39
|
+
async function handlePluginPreTool(input) {
|
|
40
|
+
const skillName = getStringField(input, 'skill');
|
|
41
|
+
if (!skillName)
|
|
42
|
+
return;
|
|
43
|
+
await instrumentHook(HOOK_NAMES.PLUGIN_PRE_TOOL, (ctx) => {
|
|
44
|
+
const skillInfo = parseSkillName(skillName);
|
|
45
|
+
const category = categorizeSkill(skillName);
|
|
46
|
+
const sourceType = getSkillSourceType(skillInfo.name);
|
|
47
|
+
const pluginLabels = {
|
|
48
|
+
'integritystudio.plugin.category': category,
|
|
49
|
+
'integritystudio.plugin.source_type': sourceType,
|
|
50
|
+
};
|
|
51
|
+
// Log and metric carry the namespace defaulted; the span sets it only when present.
|
|
52
|
+
const pluginMetricLabels = { ...pluginLabelsOf(skillInfo), ...pluginLabels };
|
|
53
|
+
ctx.addAttributes({
|
|
54
|
+
[PLUGIN_ATTRS.NAME]: skillInfo.name,
|
|
55
|
+
...pluginLabels,
|
|
56
|
+
'integritystudio.plugin.full_name': skillInfo.fullName,
|
|
57
|
+
'integritystudio.plugin.has_args': !!getStringField(input, 'args'),
|
|
58
|
+
...(skillInfo.namespace ? { [PLUGIN_ATTRS.NAMESPACE]: skillInfo.namespace } : {}),
|
|
59
|
+
});
|
|
60
|
+
ctx.logger.info('Plugin invoked', pluginMetricLabels);
|
|
61
|
+
ctx.recordMetric('integritystudio.plugin.invocations', 1, pluginMetricLabels, { unit: UNITS.INVOCATION });
|
|
62
|
+
const namespacePrefix = skillInfo.namespace ? `${skillInfo.namespace}:` : '';
|
|
63
|
+
writeStderr(`[Plugin] ${namespacePrefix}${skillInfo.name} [${category}] (${sourceType})`);
|
|
64
|
+
}, { [HOOK_TYPE_ATTR]: 'plugin' });
|
|
65
|
+
}
|
|
66
|
+
/** Input fields copied onto the span as text when non-empty, keyed input field → attribute. */
|
|
67
|
+
const TEXT_ATTRS = {
|
|
68
|
+
Glob: {
|
|
69
|
+
pattern: 'integritystudio.glob.pattern',
|
|
70
|
+
path: 'integritystudio.glob.path',
|
|
71
|
+
},
|
|
72
|
+
Grep: {
|
|
73
|
+
pattern: 'integritystudio.grep.pattern',
|
|
74
|
+
glob: 'integritystudio.grep.glob',
|
|
75
|
+
type: 'integritystudio.grep.type',
|
|
76
|
+
output_mode: 'integritystudio.grep.output_mode',
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
/** Input fields recorded as `true` when truthy, keyed input field → attribute. */
|
|
80
|
+
const FLAG_ATTRS = {
|
|
81
|
+
Edit: { replace_all: 'integritystudio.edit.replace_all' },
|
|
82
|
+
Bash: {
|
|
83
|
+
run_in_background: 'integritystudio.bash.background',
|
|
84
|
+
dangerouslyDisableSandbox: 'integritystudio.bash.sandbox_disabled',
|
|
85
|
+
},
|
|
86
|
+
Grep: {
|
|
87
|
+
multiline: 'integritystudio.grep.multiline',
|
|
88
|
+
'-i': 'integritystudio.grep.case_insensitive',
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
function fileContext(toolInput, toolName) {
|
|
92
|
+
const context = {};
|
|
93
|
+
const filePath = getTargetPath(toolInput);
|
|
94
|
+
if (filePath) {
|
|
95
|
+
context[FILE_PATH_ATTR] = filePath;
|
|
96
|
+
context['file.extension'] = getFileExtension(filePath);
|
|
97
|
+
}
|
|
98
|
+
if (isEditTool(toolName)) {
|
|
99
|
+
const replaced = getReplacedText(toolInput, toolName);
|
|
100
|
+
if (replaced)
|
|
101
|
+
context['integritystudio.edit.old_string_length'] = replaced.length;
|
|
102
|
+
const written = getWrittenText(toolInput, toolName);
|
|
103
|
+
if (written)
|
|
104
|
+
context['integritystudio.edit.new_string_length'] = written.text.length;
|
|
105
|
+
}
|
|
106
|
+
return context;
|
|
107
|
+
}
|
|
108
|
+
function bashContext(toolInput) {
|
|
109
|
+
const context = {};
|
|
110
|
+
const command = getScalarText(toolInput, 'command');
|
|
111
|
+
if (command) {
|
|
112
|
+
context['integritystudio.bash.command_length'] = command.length;
|
|
113
|
+
context['integritystudio.bash.command_type'] = bashCommandType(command);
|
|
114
|
+
}
|
|
115
|
+
if (toolInput.timeout)
|
|
116
|
+
context['integritystudio.bash.timeout'] = toolInput.timeout;
|
|
117
|
+
return context;
|
|
118
|
+
}
|
|
119
|
+
const CD_PROGRAM = 'cd';
|
|
120
|
+
const WHITESPACE = /\s+/;
|
|
121
|
+
/**
|
|
122
|
+
* The program a command runs, past `FOO=1`, `env`, a `/usr/bin/` prefix and an opening `cd …&&`.
|
|
123
|
+
* A lone `cd` is still `cd`; when no program resolves (`sudo -u app …` leaves an option first,
|
|
124
|
+
* `FOO=1` alone leaves nothing) the first word stands in. Exported for tests.
|
|
125
|
+
*/
|
|
126
|
+
export function bashCommandType(command) {
|
|
127
|
+
const programs = commandInvocations(command).map(programOf).filter((program) => !isOptionArg(program));
|
|
128
|
+
return programs.find((program) => program !== CD_PROGRAM) ?? programs[0] ?? command.trim().split(WHITESPACE, 1)[0] ?? '';
|
|
129
|
+
}
|
|
130
|
+
const INVALID_URL_DOMAIN = 'invalid';
|
|
131
|
+
function urlDomain(url) {
|
|
132
|
+
try {
|
|
133
|
+
return new URL(url).hostname;
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return INVALID_URL_DOMAIN;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function webContext(toolInput) {
|
|
140
|
+
const context = {};
|
|
141
|
+
const url = getScalarText(toolInput, 'url');
|
|
142
|
+
if (url)
|
|
143
|
+
context['url.domain'] = urlDomain(url);
|
|
144
|
+
const query = getScalarText(toolInput, 'query');
|
|
145
|
+
if (query)
|
|
146
|
+
context['integritystudio.web.query_length'] = query.length;
|
|
147
|
+
const prompt = getScalarText(toolInput, 'prompt');
|
|
148
|
+
if (prompt)
|
|
149
|
+
context['integritystudio.web.prompt_preview'] = prompt.slice(0, INPUT_PREVIEW_CHARS);
|
|
150
|
+
return context;
|
|
151
|
+
}
|
|
152
|
+
function todoContext(toolInput) {
|
|
153
|
+
return Array.isArray(toolInput.todos) ? { 'integritystudio.todo.count': toolInput.todos.length } : {};
|
|
154
|
+
}
|
|
155
|
+
/** Tools whose context needs more than the TEXT_ATTRS / FLAG_ATTRS tables. */
|
|
156
|
+
const CONTEXT_EXTRACTORS = {
|
|
157
|
+
Read: fileContext,
|
|
158
|
+
Write: fileContext,
|
|
159
|
+
Edit: fileContext,
|
|
160
|
+
MultiEdit: fileContext,
|
|
161
|
+
NotebookEdit: fileContext,
|
|
162
|
+
Bash: bashContext,
|
|
163
|
+
WebFetch: webContext,
|
|
164
|
+
WebSearch: webContext,
|
|
165
|
+
TodoWrite: todoContext,
|
|
166
|
+
};
|
|
167
|
+
function getBuiltinToolContext(toolName, toolInput) {
|
|
168
|
+
if (!BUILTIN_TOOLS.has(toolName))
|
|
169
|
+
return {};
|
|
170
|
+
const tool = toolName;
|
|
171
|
+
const context = { ...CONTEXT_EXTRACTORS[tool]?.(toolInput, toolName) };
|
|
172
|
+
for (const [key, attr] of Object.entries(TEXT_ATTRS[tool] ?? {})) {
|
|
173
|
+
const value = getScalarText(toolInput, key);
|
|
174
|
+
if (value)
|
|
175
|
+
context[attr] = value;
|
|
176
|
+
}
|
|
177
|
+
for (const [key, attr] of Object.entries(FLAG_ATTRS[tool] ?? {})) {
|
|
178
|
+
if (toolInput[key])
|
|
179
|
+
context[attr] = true;
|
|
180
|
+
}
|
|
181
|
+
return context;
|
|
182
|
+
}
|
|
183
|
+
async function handleBuiltinPreTool(input) {
|
|
184
|
+
const toolName = input.tool_name;
|
|
185
|
+
await instrumentHook(HOOK_NAMES.BUILTIN_PRE_TOOL, (ctx) => {
|
|
186
|
+
const toolInput = input.tool_input ?? {};
|
|
187
|
+
const toolContext = getBuiltinToolContext(toolName, toolInput);
|
|
188
|
+
const toolLabels = builtinToolLabels(toolName);
|
|
189
|
+
ctx.addAttributes({
|
|
190
|
+
...toolLabels,
|
|
191
|
+
...toolContext,
|
|
192
|
+
});
|
|
193
|
+
ctx.logger.info('Built-in tool invoked', toolLabels);
|
|
194
|
+
ctx.recordMetric('integritystudio.tool.invocations', 1, toolLabels, { unit: UNITS.INVOCATION });
|
|
195
|
+
}, { [HOOK_TYPE_ATTR]: 'builtin' });
|
|
196
|
+
}
|
|
197
|
+
/** HEAD snapshot for PostToolUse's quiet-commit detection (HSF10); run beside the builtin handler so its git spawn overlaps. */
|
|
198
|
+
async function recordCommitHead(input) {
|
|
199
|
+
if (!mayRunGitCommit(input))
|
|
200
|
+
return;
|
|
201
|
+
const { recordCommitHeadSnapshot } = await import('../lib/git/git-commit.js');
|
|
202
|
+
await recordCommitHeadSnapshot(input);
|
|
203
|
+
}
|
|
204
|
+
// ==================== Main Handler ====================
|
|
205
|
+
export async function handlePreTool(input, subType) {
|
|
206
|
+
// Guards first: a denial exits the process before any telemetry work starts.
|
|
207
|
+
// Guarded by agent_type to avoid loading pre-tool-agent.ts on non-agent events.
|
|
208
|
+
if (input.agent_type)
|
|
209
|
+
await handleAgentScopeGuards(input);
|
|
210
|
+
await routeToolEvent(input, subType, {
|
|
211
|
+
mcp: () => handleMcpPreTool(input),
|
|
212
|
+
plugin: () => handlePluginPreTool(input),
|
|
213
|
+
agent: () => handleAgentPreTool(input),
|
|
214
|
+
builtin: () => input.tool_name === 'Bash'
|
|
215
|
+
? Promise.all([handleBuiltinPreTool(input), recordCommitHead(input)]).then(() => undefined)
|
|
216
|
+
: handleBuiltinPreTool(input),
|
|
217
|
+
});
|
|
218
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SessionEnd (CCH4): record the end reason and spawn the shipper so spans after
|
|
3
|
+
* the final turn are not left for the next session's first Stop.
|
|
4
|
+
*
|
|
5
|
+
* Hard budget: Claude Code runs the whole SessionEnd phase under one `timeoutMs`
|
|
6
|
+
* shared by every registered hook, 1500 ms unless raised by
|
|
7
|
+
* `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` (CONFIG.md § Register Hooks). Nothing
|
|
8
|
+
* network-bound or transcript-sized belongs here; put it in `stop.ts`.
|
|
9
|
+
*/
|
|
10
|
+
import { boundedLabel } from '../lib/core/bounded-label.js';
|
|
11
|
+
import { UNITS } from '../lib/core/units.js';
|
|
12
|
+
import { HOOK_NAMES, HOOK_TYPE_ATTR, SESSION_ATTRIBUTES } from '../lib/otel/attributes.js';
|
|
13
|
+
import { instrumentHook } from '../lib/otel/otel-monitor.js';
|
|
14
|
+
import { spawnTelemetryShipper } from '../lib/shipper/telemetry-shipper.js';
|
|
15
|
+
/** Claude Code's `reason` enum as of 2.1.319; anything else is labeled `other`. */
|
|
16
|
+
const SESSION_END_REASONS = new Set([
|
|
17
|
+
'clear',
|
|
18
|
+
'resume',
|
|
19
|
+
'logout',
|
|
20
|
+
'prompt_input_exit',
|
|
21
|
+
'other',
|
|
22
|
+
]);
|
|
23
|
+
const END_REASON_ATTR = 'integritystudio.session.end_reason';
|
|
24
|
+
export async function handleSessionEnd(input) {
|
|
25
|
+
await instrumentHook(HOOK_NAMES.SESSION_END, (ctx) => {
|
|
26
|
+
const raw = input.reason ?? '';
|
|
27
|
+
// Bounded in the metric, raw on the span, so payload drift is visible without a new series.
|
|
28
|
+
const reason = boundedLabel(raw, SESSION_END_REASONS);
|
|
29
|
+
ctx.addAttributes({
|
|
30
|
+
[END_REASON_ATTR]: reason,
|
|
31
|
+
'integritystudio.session.end_reason_raw': raw,
|
|
32
|
+
});
|
|
33
|
+
ctx.logger.info('Session ended', { [END_REASON_ATTR]: reason });
|
|
34
|
+
ctx.recordMetric('integritystudio.session.ends', 1, { [END_REASON_ATTR]: reason }, { unit: UNITS.SESSION });
|
|
35
|
+
// OBP12: unlike session.start, no previous_id on end.
|
|
36
|
+
ctx.recordEvent('session.end', { [SESSION_ATTRIBUTES.SESSION_ID]: input.session_id });
|
|
37
|
+
spawnTelemetryShipper();
|
|
38
|
+
}, { [HOOK_TYPE_ATTR]: 'session' });
|
|
39
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/** SessionStart: trace context, session identity, state reset, and the startup banner. */
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import * as os from 'node:os';
|
|
4
|
+
import * as path from 'node:path';
|
|
5
|
+
import { clearSession as clearAgentContext } from '../lib/agent/agent-context.js';
|
|
6
|
+
import { THRESHOLDS, GIT_TIMEOUT_MS } from '../lib/core/constants.js';
|
|
7
|
+
import { loadJson } from '../lib/core/file-utils.js';
|
|
8
|
+
import { writeStderr } from '../lib/core/format-utils.js';
|
|
9
|
+
import { TRANSCRIPT_PROJECT_SLUG_PATTERN } from '../lib/core/regex.js';
|
|
10
|
+
import { formatPercent, PERCENT_PER_UNIT, UNITS } from '../lib/core/units.js';
|
|
11
|
+
import { probeGitStatus, readHeadBranch, splitOwnerRepo } from '../lib/git/git-cache.js';
|
|
12
|
+
import { resetFailureTracking } from '../lib/mcp/mcp-failure-latch.js';
|
|
13
|
+
import { SESSION_ATTRIBUTES, GIT_ATTRIBUTES, PROCESS_ATTRIBUTES, VCS_ATTRIBUTES, CONTEXT_ATTRIBUTES, HOOK_TYPE_ATTR, HOOK_NAMES, } from '../lib/otel/attributes.js';
|
|
14
|
+
import { instrumentHook, persistSpanContext } from '../lib/otel/otel-monitor.js';
|
|
15
|
+
import { saveSessionContext, recordSessionPredecessor } from '../lib/otel/trace-context.js';
|
|
16
|
+
import { shouldSampleSession } from '../lib/quality/quality-sampler.js';
|
|
17
|
+
import { SESSION_START_SOURCE } from '../lib/runtime/hook-input.js';
|
|
18
|
+
import { writePlainContext } from '../lib/runtime/hook-output.js';
|
|
19
|
+
import { findPendingHandoffs, formatHandoffBanner } from '../lib/session/handoffs.js';
|
|
20
|
+
import { CONVERSATION_ID_ENV, conversationIdOf, saveCurrentSessionId, saveSessionStartBranch, } from '../lib/session/session-state.js';
|
|
21
|
+
import { activeTaskCompletion } from '../lib/session/task-tracker.js';
|
|
22
|
+
import { formatShipperWarning, isShipperHealthy, readShipperStatus } from '../lib/shipper/shipper-status.js';
|
|
23
|
+
import { trackSessionContext, trackSessionContextFast } from '../lib/transcript/context-tracker.js';
|
|
24
|
+
/** A fresh session shows its context block only once the estimate passes this */
|
|
25
|
+
const CONTEXT_BANNER_MIN_TOKENS = 10_000;
|
|
26
|
+
const TOKENS_PER_MILLION = 1_000_000;
|
|
27
|
+
const TOKENS_PER_THOUSAND = 1_000;
|
|
28
|
+
const FULL_UTILIZATION_PERCENT = PERCENT_PER_UNIT;
|
|
29
|
+
const UTILIZATION_HIGH_PERCENT = 70;
|
|
30
|
+
const UTILIZATION_WARN_PERCENT = 50;
|
|
31
|
+
const DEFAULT_ACTIVE_TASKS_SUBDIR = path.join('dev', 'active');
|
|
32
|
+
const UNKNOWN_PROJECT_NAME = 'unknown';
|
|
33
|
+
/** Starts that continue an existing transcript: `--resume`, with or without `--fork-session`. */
|
|
34
|
+
const CONTINUING_SOURCES = new Set([SESSION_START_SOURCE.RESUME, SESSION_START_SOURCE.FORK]);
|
|
35
|
+
/** The first firing of a conversation; an absent source is an older Claude Code's startup. */
|
|
36
|
+
const isFreshStart = (source) => source === undefined || source === SESSION_START_SOURCE.STARTUP;
|
|
37
|
+
const continuesTranscript = (source) => source !== undefined && CONTINUING_SOURCES.has(source);
|
|
38
|
+
export async function handleSessionStart(input) {
|
|
39
|
+
await instrumentHook(HOOK_NAMES.SESSION_START, async (ctx) => {
|
|
40
|
+
const cwd = process.cwd();
|
|
41
|
+
const sessionId = input.session_id;
|
|
42
|
+
// Awaited below, so the git subprocesses overlap the sync work in between.
|
|
43
|
+
const gitStatus = probeGitStatus(cwd, GIT_TIMEOUT_MS.HOOK_PATH).catch(() => null);
|
|
44
|
+
// So later hooks in this session create child spans under the same traceId.
|
|
45
|
+
persistSpanContext(ctx, sessionId, saveSessionContext);
|
|
46
|
+
recordSessionIdentity(ctx, input);
|
|
47
|
+
ctx.logger.info('Session starting', {
|
|
48
|
+
[PROCESS_ATTRIBUTES.WORKING_DIRECTORY]: cwd, [SESSION_ATTRIBUTES.SESSION_ID]: sessionId,
|
|
49
|
+
});
|
|
50
|
+
prepareSessionState(ctx, sessionId);
|
|
51
|
+
const isResume = continuesTranscript(input.source);
|
|
52
|
+
const sections = [
|
|
53
|
+
reportContext(ctx, input, cwd, isResume),
|
|
54
|
+
isResume ? reportRestoredTasks(ctx, sessionId) : null,
|
|
55
|
+
];
|
|
56
|
+
const git = await gitStatus;
|
|
57
|
+
sections.push(reportEnvironment(ctx, cwd), reportProject(ctx, cwd), reportActiveTasks(ctx), git ? reportGit(ctx, git) : null);
|
|
58
|
+
const notices = [...shipperNotice(ctx), ...handoffNotice(ctx, cwd)];
|
|
59
|
+
const checksPerformed = sections.filter((section) => section !== null).length;
|
|
60
|
+
ctx.addAttribute('integritystudio.session.checks_performed', checksPerformed);
|
|
61
|
+
ctx.recordMetric('integritystudio.session.checks', checksPerformed, undefined, {
|
|
62
|
+
description: 'Startup checks performed per session',
|
|
63
|
+
unit: UNITS.CHECK,
|
|
64
|
+
});
|
|
65
|
+
const banner = [...sections.flatMap((section) => section ?? []), ...notices];
|
|
66
|
+
if (banner.length === 0)
|
|
67
|
+
return;
|
|
68
|
+
const bannerText = banner.join('\n');
|
|
69
|
+
writePlainContext(bannerText);
|
|
70
|
+
ctx.logger.info(bannerText);
|
|
71
|
+
}, { [HOOK_TYPE_ATTR]: 'session' });
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Grouping attributes, predecessor edge and `session.start` event (OBP3, OBP12).
|
|
75
|
+
* The project slug must not occupy gen_ai.conversation.id: a project holds many
|
|
76
|
+
* conversations, and that key carries a genuine thread id only.
|
|
77
|
+
*/
|
|
78
|
+
function recordSessionIdentity(ctx, input) {
|
|
79
|
+
const projectSlug = deriveProjectSlug(input.transcript_path);
|
|
80
|
+
if (projectSlug)
|
|
81
|
+
ctx.addAttribute(SESSION_ATTRIBUTES.PROJECT_SLUG, projectSlug);
|
|
82
|
+
const conversationId = conversationIdOf(input.session_id);
|
|
83
|
+
if (conversationId)
|
|
84
|
+
ctx.addAttribute(SESSION_ATTRIBUTES.CONVERSATION_ID, conversationId);
|
|
85
|
+
const sessionId = input.session_id;
|
|
86
|
+
const previousId = recordPredecessor(input.source, sessionId, process.env[CONVERSATION_ID_ENV] || projectSlug);
|
|
87
|
+
if (previousId)
|
|
88
|
+
ctx.addAttribute(SESSION_ATTRIBUTES.PREVIOUS_ID, previousId);
|
|
89
|
+
ctx.recordEvent('session.start', {
|
|
90
|
+
[SESSION_ATTRIBUTES.SESSION_ID]: sessionId,
|
|
91
|
+
...(previousId ? { [SESSION_ATTRIBUTES.PREVIOUS_ID]: previousId } : {}),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Only the 'startup' firing (or an absent source) touches the store: 'resume', 'fork',
|
|
96
|
+
* 'clear' and 'compact' re-fire this hook and would record a backwards edge (OTEL5-8).
|
|
97
|
+
*/
|
|
98
|
+
function recordPredecessor(source, sessionId, groupingKey) {
|
|
99
|
+
if (!isFreshStart(source) || !groupingKey)
|
|
100
|
+
return null;
|
|
101
|
+
return distinctPredecessor(recordSessionPredecessor(groupingKey, sessionId), sessionId);
|
|
102
|
+
}
|
|
103
|
+
function prepareSessionState(ctx, sessionId) {
|
|
104
|
+
// Both stores outlive the process, so a session reusing this id would inherit them.
|
|
105
|
+
resetFailureTracking(sessionId);
|
|
106
|
+
clearAgentContext(sessionId);
|
|
107
|
+
// GCS1/GCS2: session id and start branch for the git pre-commit scope guard, which
|
|
108
|
+
// runs in every repo; an unset CLAUDE_PROJECT_DIR leaves it warn-only. The branch
|
|
109
|
+
// is read uncached: the git probe's cache is stale precisely in the shared checkout.
|
|
110
|
+
const projectDir = process.env.CLAUDE_PROJECT_DIR;
|
|
111
|
+
if (projectDir) {
|
|
112
|
+
saveCurrentSessionId(sessionId, projectDir);
|
|
113
|
+
const startBranch = readHeadBranch(projectDir);
|
|
114
|
+
if (startBranch)
|
|
115
|
+
saveSessionStartBranch(sessionId, startBranch);
|
|
116
|
+
}
|
|
117
|
+
ctx.addAttribute('integritystudio.quality.eval_sampled', shouldSampleSession(sessionId));
|
|
118
|
+
}
|
|
119
|
+
/** The fast path renders the banner with no I/O; the deferred full scan is the sole recorder of metrics (HRV2). Resume scans immediately. */
|
|
120
|
+
function reportContext(ctx, input, cwd, isResume) {
|
|
121
|
+
const trackParams = {
|
|
122
|
+
sessionId: input.session_id,
|
|
123
|
+
transcriptPath: input.transcript_path,
|
|
124
|
+
isResume,
|
|
125
|
+
attributes: { [PROCESS_ATTRIBUTES.WORKING_DIRECTORY]: cwd },
|
|
126
|
+
};
|
|
127
|
+
const contextData = isResume ? trackSessionContext(trackParams) : trackSessionContextFast(trackParams);
|
|
128
|
+
// `clear` and `compact` re-fire mid-run with the transcript already on disk; recording
|
|
129
|
+
// them would add session starts the conversation never had, so only a fresh start scans.
|
|
130
|
+
if (!isResume && isFreshStart(input.source)) {
|
|
131
|
+
setImmediate(() => {
|
|
132
|
+
try {
|
|
133
|
+
trackSessionContext(trackParams);
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
// The banner already rendered from the fast path.
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
ctx.addAttributes(contextSpanAttributes(contextData));
|
|
141
|
+
const headline = {
|
|
142
|
+
[CONTEXT_ATTRIBUTES.UTILIZATION_PERCENT]: contextData.utilizationPercent,
|
|
143
|
+
[CONTEXT_ATTRIBUTES.ESTIMATED_TOKENS]: contextData.estimatedTokens,
|
|
144
|
+
};
|
|
145
|
+
if (contextData.utilizationPercent > FULL_UTILIZATION_PERCENT) {
|
|
146
|
+
ctx.recordEvent('integritystudio.context.overflow', headline);
|
|
147
|
+
writeStderr(`[OVERFLOW] Context utilization exceeded ${FULL_UTILIZATION_PERCENT}%: ${contextData.utilizationPercent.toFixed(1)}%`);
|
|
148
|
+
}
|
|
149
|
+
ctx.logger.debug('Context tracked', { ...headline, [CONTEXT_ATTRIBUTES.FREE_SPACE]: contextData.freeSpace });
|
|
150
|
+
if (!contextData.isResume && contextData.estimatedTokens <= CONTEXT_BANNER_MIN_TOKENS)
|
|
151
|
+
return null;
|
|
152
|
+
const { estimatedTokens, utilizationPercent, freeSpace } = contextData;
|
|
153
|
+
return [
|
|
154
|
+
`Context: ${formatTokens(estimatedTokens)} tokens (${utilizationPercent.toFixed(1)}%, ${utilizationLabel(utilizationPercent)}), ${formatTokens(freeSpace)} free`,
|
|
155
|
+
];
|
|
156
|
+
}
|
|
157
|
+
function contextSpanAttributes(contextData) {
|
|
158
|
+
return {
|
|
159
|
+
[CONTEXT_ATTRIBUTES.ESTIMATED_TOKENS]: contextData.estimatedTokens,
|
|
160
|
+
[CONTEXT_ATTRIBUTES.UTILIZATION_PERCENT]: contextData.utilizationPercent,
|
|
161
|
+
[CONTEXT_ATTRIBUTES.FREE_SPACE]: contextData.freeSpace,
|
|
162
|
+
[CONTEXT_ATTRIBUTES.TRANSCRIPT_SIZE]: contextData.transcriptSize,
|
|
163
|
+
[CONTEXT_ATTRIBUTES.MESSAGE_COUNT]: contextData.messageCount,
|
|
164
|
+
[CONTEXT_ATTRIBUTES.IS_RESUME]: contextData.isResume,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function reportRestoredTasks(ctx, sessionId) {
|
|
168
|
+
const tasks = activeTaskCompletion(sessionId);
|
|
169
|
+
if (!tasks)
|
|
170
|
+
return null;
|
|
171
|
+
const { active, ratio } = tasks;
|
|
172
|
+
ctx.addAttributes({
|
|
173
|
+
'integritystudio.task.restored_count': active.length,
|
|
174
|
+
'integritystudio.task.completion_ratio': ratio,
|
|
175
|
+
});
|
|
176
|
+
ctx.recordMetric('integritystudio.session.task_completion', ratio, undefined, { unit: UNITS.RATIO });
|
|
177
|
+
const lines = [`Tasks: ${active.length} restored (${formatPercent(ratio)} complete)`];
|
|
178
|
+
if (ratio < THRESHOLDS.TASK_COMPLETION_RATIO) {
|
|
179
|
+
lines.push(` [!] Low completion ratio: ${ratio.toFixed(2)}`);
|
|
180
|
+
}
|
|
181
|
+
return lines;
|
|
182
|
+
}
|
|
183
|
+
function reportEnvironment(ctx, cwd) {
|
|
184
|
+
ctx.addAttribute(PROCESS_ATTRIBUTES.RUNTIME_VERSION, process.version);
|
|
185
|
+
ctx.logger.debug('Environment check passed', { [PROCESS_ATTRIBUTES.RUNTIME_VERSION]: process.version });
|
|
186
|
+
ctx.addAttribute(PROCESS_ATTRIBUTES.WORKING_DIRECTORY, cwd);
|
|
187
|
+
return [];
|
|
188
|
+
}
|
|
189
|
+
function reportProject(ctx, cwd) {
|
|
190
|
+
const pkg = loadJson(path.join(cwd, 'package.json'));
|
|
191
|
+
if (!pkg)
|
|
192
|
+
return null;
|
|
193
|
+
const projectName = pkg.name || UNKNOWN_PROJECT_NAME;
|
|
194
|
+
ctx.addAttribute(SESSION_ATTRIBUTES.PROJECT_NAME, projectName);
|
|
195
|
+
return [];
|
|
196
|
+
}
|
|
197
|
+
function reportActiveTasks(ctx) {
|
|
198
|
+
const activeDir = process.env.ACTIVE_TASKS_DIR || path.join(os.homedir(), DEFAULT_ACTIVE_TASKS_SUBDIR);
|
|
199
|
+
if (!fs.existsSync(activeDir))
|
|
200
|
+
return null;
|
|
201
|
+
const taskNames = fs.readdirSync(activeDir);
|
|
202
|
+
ctx.addAttribute('integritystudio.tasks.active', taskNames.length);
|
|
203
|
+
ctx.recordMetric('integritystudio.session.active_tasks', taskNames.length, undefined, { unit: UNITS.TASK });
|
|
204
|
+
return taskNames.length > 0 ? [`Active tasks (${taskNames.length}): ${taskNames.join(', ')}`] : [];
|
|
205
|
+
}
|
|
206
|
+
function reportGit(ctx, { branch, uncommitted, repository }) {
|
|
207
|
+
ctx.addAttribute(VCS_ATTRIBUTES.REF_HEAD_NAME, branch);
|
|
208
|
+
ctx.addAttribute(GIT_ATTRIBUTES.UNCOMMITTED, uncommitted);
|
|
209
|
+
if (repository) {
|
|
210
|
+
const { owner, name } = splitOwnerRepo(repository);
|
|
211
|
+
ctx.addAttribute(VCS_ATTRIBUTES.REPOSITORY_NAME, name);
|
|
212
|
+
if (owner)
|
|
213
|
+
ctx.addAttribute(VCS_ATTRIBUTES.OWNER_NAME, owner);
|
|
214
|
+
}
|
|
215
|
+
return [uncommitted > 0 ? `Git: ${branch} (${uncommitted} uncommitted changes)` : `Git: ${branch} (clean)`];
|
|
216
|
+
}
|
|
217
|
+
/** The only place the shipper's diagnostics reach a person; printed only when unhealthy so it is not tuned out (CCH6a). */
|
|
218
|
+
function shipperNotice(ctx) {
|
|
219
|
+
const shipperStatus = readShipperStatus();
|
|
220
|
+
if (!shipperStatus || isShipperHealthy(shipperStatus.outcome))
|
|
221
|
+
return [];
|
|
222
|
+
ctx.addAttribute('integritystudio.telemetry.shipper.outcome', shipperStatus.outcome);
|
|
223
|
+
return [formatShipperWarning(shipperStatus)];
|
|
224
|
+
}
|
|
225
|
+
/** The previous session's note to this one; silent when docs/handoffs/ is absent. */
|
|
226
|
+
function handoffNotice(ctx, cwd) {
|
|
227
|
+
const handoffs = findPendingHandoffs(cwd);
|
|
228
|
+
if (handoffs.length === 0)
|
|
229
|
+
return [];
|
|
230
|
+
ctx.addAttribute('integritystudio.session.handoffs_pending', handoffs.length);
|
|
231
|
+
return formatHandoffBanner(handoffs);
|
|
232
|
+
}
|
|
233
|
+
/** The directory name above the session JSONL (lib/transcript/transcript-layout.ts). Exported for tests. */
|
|
234
|
+
export function deriveProjectSlug(transcriptPath) {
|
|
235
|
+
if (!transcriptPath)
|
|
236
|
+
return null;
|
|
237
|
+
return transcriptPath.match(TRANSCRIPT_PROJECT_SLUG_PATTERN)?.[1] ?? null;
|
|
238
|
+
}
|
|
239
|
+
/** The prior session's id when it exists and differs (session.previous_id spec MUST). */
|
|
240
|
+
export function distinctPredecessor(priorSessionId, currentSessionId) {
|
|
241
|
+
return priorSessionId && priorSessionId !== currentSessionId ? priorSessionId : null;
|
|
242
|
+
}
|
|
243
|
+
function formatTokens(tokens) {
|
|
244
|
+
if (tokens >= TOKENS_PER_MILLION) {
|
|
245
|
+
return `${(tokens / TOKENS_PER_MILLION).toFixed(1)}M`;
|
|
246
|
+
}
|
|
247
|
+
if (tokens >= TOKENS_PER_THOUSAND) {
|
|
248
|
+
return `${(tokens / TOKENS_PER_THOUSAND).toFixed(0)}K`;
|
|
249
|
+
}
|
|
250
|
+
return String(tokens);
|
|
251
|
+
}
|
|
252
|
+
/** Exported for tests. */
|
|
253
|
+
export function utilizationLabel(percent) {
|
|
254
|
+
const safePct = Number.isFinite(percent) ? percent : 0;
|
|
255
|
+
if (safePct > FULL_UTILIZATION_PERCENT)
|
|
256
|
+
return 'OVERFLOW';
|
|
257
|
+
if (safePct >= UTILIZATION_HIGH_PERCENT)
|
|
258
|
+
return 'HIGH';
|
|
259
|
+
if (safePct >= UTILIZATION_WARN_PERCENT)
|
|
260
|
+
return 'WARN';
|
|
261
|
+
return 'OK';
|
|
262
|
+
}
|