How context-compat.ts Tracks the Active Marker After Context Compaction
The latestMarkerIsActive function in extensions/context-compat.ts performs a linear scan through normalized context entries, toggling an internal flag whenever it encounters an activation marker (activeType) or deactivation marker (disabledType), ensuring the final boolean reflects the most recent marker state even after aggressive context compaction.
The i-have-adhd repository provides a compatibility layer that enables runtime environments to determine whether ADHD-friendly rules are currently active within a session context. Tracking how context-compat.ts maintains this state requires examining its normalization utilities and the linear scanning algorithm that survives context compaction.
The Two-Function Architecture for Marker Tracking
The compatibility layer exposes two coordinated utilities that abstract differences between OMP and Pi API styles while determining marker state.
Normalizing Session Contexts with contextMessages
Located at lines 12-39 in extensions/context-compat.ts, the contextMessages function standardizes disparate session manager APIs into a uniform array of markers. The function first validates that the supplied sessionManager is an object, then attempts to call the OMP-style buildSessionContext() method, extracting the messages array if present. If that interface is unavailable, it falls back to the Pi-style buildContextEntries() method. Any errors or unsupported shapes return an empty array, preventing runtime crashes while allowing the caller to continue safely.
Determining Active State with latestMarkerIsActive
The latestMarkerIsActive function implements the core logic for determining whether rules are currently active. Implemented at lines 46-61 of extensions/context-compat.ts, this utility accepts an array of messages, an activeType string, and a disabledType string.
The function iterates through every entry (lines 46-58), filtering for custom-type markers identified by either role: "custom" or type: "custom_message". When encountering a message whose customType matches the activeType, it sets a local active flag to true; when encountering the disabledType, it clears the flag to false. After processing the entire array, the function returns the final boolean value at lines 60-61, representing whether the most recent relevant marker was an activation or deactivation command.
How Linear Scanning Survives Context Compaction
During context compaction, the runtime may merge adjacent messages or reorder entries to optimize token usage, but the relative chronological order of custom markers is preserved. Because latestMarkerIsActive walks the array sequentially and updates the active flag in place, the final result automatically reflects the state after any amount of compaction.
The algorithm requires no additional bookkeeping or metadata; a simple linear sweep is sufficient because the last occurring marker of either type deterministically governs the outcome. This design ensures that context compaction never corrupts the active state tracking.
Implementation Details in context-compat.ts
The marker tracking system relies on specific type checking and validation to ensure cross-platform compatibility.
Marker Identification Logic
Within the loop at lines 46-58, the function strictly validates marker types before processing. Only entries with role: "custom" (OMP style) or type: "custom_message" (Pi style) are examined for their customType property. This filtering ensures that system messages or user content do not inadvertently trigger state changes.
Verification Through Testing
The correctness of this approach is verified by scripts/check_context_compat.ts, which constructs synthetic OMP and Pi message arrays and asserts expected boolean outputs. Lines 50-73 of the test script specifically validate that latestMarkerIsActive correctly handles mixed marker sequences, confirming that later disabled markers properly override earlier activation markers regardless of compaction simulation.
Practical Usage Examples
The following examples demonstrate how to integrate the compatibility layer with different session manager APIs.
OMP-Style Session Manager
import {
contextMessages,
latestMarkerIsActive,
} from "./extensions/context-compat";
// OMP-style session manager with buildSessionContext
const ompMgr = {
buildSessionContext: () => ({
messages: [
{ role: "custom", customType: "i-have-adhd-rules" }, // activate
{ role: "custom", customType: "i-have-adhd-disabled" } // later disable
]
})
};
const msgs = contextMessages(ompMgr);
const active = latestMarkerIsActive(
msgs,
"i-have-adhd-rules", // activeType
"i-have-adhd-disabled" // disabledType
);
// active === false because the disabled marker appears later
console.log(`Rules active? ${active}`);
Pi-Style Context Entries
// Pi-style context entries (no OMP API)
const piMgr = {
buildContextEntries: () => [
{ type: "custom_message", customType: "i-have-adhd-rules" }
]
};
const piMsgs = contextMessages(piMgr);
const piActive = latestMarkerIsActive(
piMsgs,
"i-have-adhd-rules",
"i-have-adhd-disabled"
);
// piActive === true – no later disabling marker
console.log(`Pi rules active? ${piActive}`);
Summary
contextMessagesnormalizes both OMP and Pi session manager APIs into a uniform message array, handling errors gracefully by returning empty arrays for unsupported interfaces.latestMarkerIsActiveuses a linear scan algorithm (lines 46-61) to toggle a boolean flag based on the most recent activation or deactivation marker encountered.- The scanning approach inherently supports context compaction because it relies only on the relative order of markers, not their absolute positions or metadata.
- Custom markers are strictly identified by
role: "custom"ortype: "custom_message"properties to prevent interference from standard messages. - The implementation is verified by
scripts/check_context_compat.ts, which validates synthetic marker sequences including compaction scenarios.
Frequently Asked Questions
What happens if both marker types appear multiple times in the sequence?
The latestMarkerIsActive function processes every message in order, updating the internal active flag each time it encounters either the activeType or disabledType. Consequently, the final value reflects only the last occurrence of either marker in the array, effectively ignoring all previous toggles while preserving the net state.
Does context compaction affect the accuracy of the marker tracking?
No. While compaction may merge or reorder messages to optimize context windows, the chronological sequence of custom markers is preserved. Since the algorithm depends solely on the relative order of markers rather than their indices or surrounding metadata, the linear scan produces correct results even after aggressive compaction.
How does the system handle unsupported session manager APIs?
The contextMessages function implements defensive programming at lines 12-39. If the session manager lacks both buildSessionContext and buildContextEntries methods, or if either method throws an exception, the function returns an empty array. This allows latestMarkerIsActive to process an empty message list and return false safely without crashing the runtime.
Where is this tracking logic actually used in the codebase?
The marker tracking system is consumed by extensions/i-have-adhd.ts, which imports these utilities to determine whether to inject ADHD-friendly formatting rules into the current session context. The extension calls latestMarkerIsActive to check the latest marker state before modifying the conversation context.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →