@0xkahi/pi-qol 0.1.1 → 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.
Files changed (44) hide show
  1. package/README.md +13 -0
  2. package/assets/config.schema.json +12 -0
  3. package/package.json +4 -4
  4. package/src/codemap.md +26 -16
  5. package/src/config-loader.ts +4 -0
  6. package/src/constants.ts +1 -0
  7. package/src/extensions/auto-session-name/codemap.md +17 -12
  8. package/src/extensions/auto-session-name/title-generator.ts +1 -1
  9. package/src/extensions/codemap.md +173 -13
  10. package/src/extensions/context-view/capture.ts +394 -0
  11. package/src/extensions/context-view/codemap.md +213 -0
  12. package/src/extensions/context-view/constants.ts +4 -0
  13. package/src/extensions/context-view/context-view-controller.ts +67 -0
  14. package/src/extensions/context-view/index.ts +120 -0
  15. package/src/extensions/context-view/measure.ts +307 -0
  16. package/src/extensions/context-view/model.ts +207 -0
  17. package/src/extensions/context-view/ui/codemap.md +82 -0
  18. package/src/extensions/context-view/ui/context-view-dialog.ts +59 -0
  19. package/src/extensions/context-view/ui/injections-model.ts +118 -0
  20. package/src/extensions/context-view/ui/injections-view.ts +264 -0
  21. package/src/extensions/context-view/ui/skill-preview.ts +82 -0
  22. package/src/extensions/context-view/ui/usage-map.ts +133 -0
  23. package/src/extensions/context-view/ui/usage-view.ts +613 -0
  24. package/src/extensions/context-view/usage.ts +432 -0
  25. package/src/extensions/model-select/codemap.md +34 -17
  26. package/src/extensions/model-select/model-select-dialog.ts +85 -324
  27. package/src/index.ts +2 -0
  28. package/src/libs/codemap.md +8 -1
  29. package/src/libs/modal/README.md +212 -0
  30. package/src/libs/modal/codemap.md +34 -0
  31. package/src/libs/modal/index.ts +29 -0
  32. package/src/libs/modal/list-navigator.ts +167 -0
  33. package/src/libs/modal/modal-dialog.ts +297 -0
  34. package/src/libs/modal/navigation/pi-scheme.ts +33 -0
  35. package/src/libs/modal/navigation/vim-scheme.ts +56 -0
  36. package/src/libs/modal/preview-layer.ts +87 -0
  37. package/src/libs/modal/render-cache.ts +33 -0
  38. package/src/libs/modal/tab-strip.ts +87 -0
  39. package/src/libs/modal/tabs/list-tab.ts +159 -0
  40. package/src/libs/modal/text.ts +88 -0
  41. package/src/libs/modal/types.ts +70 -0
  42. package/src/schemas/codemap.md +100 -18
  43. package/src/schemas/config.schema.ts +3 -0
  44. package/src/schemas/context-view.config.schema.ts +13 -0
@@ -0,0 +1,264 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /**
3
+ * Focused `/context injections` tab: hierarchical Initial snapshot rows. The
4
+ * Runtime label stays hidden until the runtime-inspection roadmap step.
5
+ * Modal plumbing — frame, navigation dispatch, previews, dismissal — is owned
6
+ * by the shared modal library; this tab owns only its content.
7
+ */
8
+ import type { Theme } from '@earendil-works/pi-coding-agent';
9
+ import { visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
10
+
11
+ import {
12
+ BODY_INDENT,
13
+ calculateViewport,
14
+ fitLine,
15
+ type Hint,
16
+ ListNavigator,
17
+ type ModalTab,
18
+ type ModalTabContext,
19
+ type NavigationAction,
20
+ PreviewLayer,
21
+ RenderCache,
22
+ wrapDescriptionLines,
23
+ } from '../../../libs/modal';
24
+ import type { InitialSnapshot, InjectionItem } from '../model';
25
+ import { buildInjectionRows, collectItemsById, type InjectionRow, normalizeInlineText, normalizePreviewText } from './injections-model';
26
+
27
+ const LIST_DESCRIPTION = 'Injections into the model context for the first turn, with token estimates.';
28
+ const CURSOR_COLUMN_WIDTH = 2;
29
+ const MAX_TOKEN_VALUE_COLUMN = 54;
30
+ const TOKEN_LEADER_GAP = 4;
31
+
32
+ /** Everything the Injections view renders. */
33
+ export interface InjectionsViewInput {
34
+ readonly snapshot: InitialSnapshot;
35
+ }
36
+
37
+ /** Shared token-value column measured after the fixed cursor column. */
38
+ interface InjectionColumns {
39
+ readonly value: number;
40
+ }
41
+
42
+ /** Stateful Injections tab retained by the Context View dialog. */
43
+ export class InjectionsView implements ModalTab {
44
+ private readonly theme: Theme;
45
+ private readonly rows: InjectionRow[];
46
+ private readonly navigator: ListNavigator;
47
+ private readonly itemsById: Map<string, InjectionItem>;
48
+ private readonly cache = new RenderCache();
49
+ private context: ModalTabContext | undefined;
50
+ private previewItem: InjectionItem | undefined;
51
+ private previewLines: string[] | undefined;
52
+ private previewWrapWidth: number | undefined;
53
+
54
+ public constructor(theme: Theme, input: InjectionsViewInput) {
55
+ this.theme = theme;
56
+ this.rows = buildInjectionRows(input.snapshot);
57
+ this.navigator = new ListNavigator(this.rows.length, 1, this.rows.length - 2);
58
+ this.itemsById = collectItemsById(input.snapshot);
59
+ }
60
+
61
+ public get label(): string {
62
+ return '[Injections]';
63
+ }
64
+
65
+ public attach(context: ModalTabContext): void {
66
+ this.context = context;
67
+ }
68
+
69
+ public hints(): Hint[] {
70
+ return [['Enter', 'Preview']];
71
+ }
72
+
73
+ public handleInput(_data: string): void {
74
+ // All Injections keys are semantic navigation actions handled by the shell.
75
+ }
76
+
77
+ /** Apply semantic movement in the hierarchy, or open an item preview. */
78
+ public handleNavigation(action: NavigationAction): void {
79
+ const changed =
80
+ action === 'step-back'
81
+ ? this.navigator.moveBy(-1)
82
+ : action === 'step-forward'
83
+ ? this.navigator.moveBy(1)
84
+ : action === 'page-back'
85
+ ? this.navigator.page(-1)
86
+ : action === 'page-forward'
87
+ ? this.navigator.page(1)
88
+ : action === 'first'
89
+ ? this.navigator.moveTo(0)
90
+ : action === 'last'
91
+ ? this.navigator.moveTo(this.rows.length - 1)
92
+ : false;
93
+ if (changed) this.cache.clear();
94
+ if (action === 'confirm') this.openPreview();
95
+ }
96
+
97
+ public render(width: number, height: number | undefined): string[] {
98
+ const cached = this.cache.read(width, height);
99
+ if (cached !== undefined) return cached;
100
+
101
+ const terminalRows = height ?? this.rows.length + 10;
102
+ const headerLines = this.headerLines(width);
103
+ const descriptionLines = wrapDescriptionLines(this.theme, LIST_DESCRIPTION, 'dim', width);
104
+ const viewport = calculateViewport(this.rows.length, terminalRows, headerLines.length + descriptionLines.length + 2);
105
+ this.navigator.setVisibleCount(viewport.visibleCount);
106
+
107
+ const lines: string[] = [...headerLines, ''];
108
+ const listLines = this.listLines(width);
109
+ lines.push(...listLines);
110
+ if (viewport.showScroll) lines.push(this.scrollLine(width));
111
+ const paddingCount = viewport.visibleCount - listLines.length;
112
+ for (let pad = 0; pad < paddingCount; pad++) lines.push('');
113
+ lines.push('', ...descriptionLines);
114
+
115
+ return this.cache.write(width, height, lines);
116
+ }
117
+
118
+ public invalidate(): void {
119
+ this.cache.clear();
120
+ }
121
+
122
+ // === Preview ===
123
+
124
+ /** Open the selected item's content preview as a shell-managed layer. */
125
+ private openPreview(): void {
126
+ const row = this.rows[this.navigator.selected];
127
+ if (row?.kind !== 'item') return;
128
+ const item = this.itemsById.get(row.itemId);
129
+ if (item === undefined) return;
130
+ this.previewItem = item;
131
+ this.previewLines = undefined;
132
+ this.previewWrapWidth = undefined;
133
+
134
+ const source = normalizeInlineText(item.source.label);
135
+ this.context?.pushLayer(
136
+ new PreviewLayer(this.theme, {
137
+ title: () => this.theme.fg('accent', this.theme.bold(normalizeInlineText(item.label))),
138
+ meta: () => this.theme.fg('muted', `${source} · ${item.tokens.toLocaleString('en-US')} tokens`),
139
+ body: width => this.getPreviewLines(width, item),
140
+ }),
141
+ );
142
+ }
143
+
144
+ private getPreviewLines(width: number, item: InjectionItem): string[] {
145
+ const wrapWidth = Math.max(10, width - BODY_INDENT.length - 1);
146
+ if (this.previewItem === item && this.previewLines !== undefined && this.previewWrapWidth === wrapWidth) {
147
+ return this.previewLines;
148
+ }
149
+ const text = normalizePreviewText(item.text);
150
+ const lines: string[] = [];
151
+ for (const paragraph of text.split('\n')) {
152
+ const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
153
+ if (wrapped.length === 0) {
154
+ lines.push('');
155
+ continue;
156
+ }
157
+ for (const line of wrapped) lines.push(`${BODY_INDENT}${line}`);
158
+ }
159
+ this.previewLines = lines;
160
+ this.previewWrapWidth = wrapWidth;
161
+ return lines;
162
+ }
163
+
164
+ // === List rendering ===
165
+
166
+ /** Keep title/label together when possible; give the narrow label its own breathing room. */
167
+ private headerLines(width: number): string[] {
168
+ const theme = this.theme;
169
+ const title = theme.fg('accent', theme.bold('Context Injections'));
170
+ const separator = theme.fg('dim', ' · ');
171
+ // Runtime remains unimplemented, so only the Initial label is shown.
172
+ const tabs = theme.fg('mdHeading', theme.bold('[INITIAL]'));
173
+ const combined = `${title}${separator}${tabs}`;
174
+ if (visibleWidth(combined) <= width) return [this.fit(combined, width)];
175
+ return [this.fit(title, width), '', this.fit(tabs, width)];
176
+ }
177
+
178
+ /** Render the current hierarchy viewport against one stable, nearby value column. */
179
+ private listLines(width: number): string[] {
180
+ const theme = this.theme;
181
+ const lines: string[] = [];
182
+ const contentWidth = Math.max(1, width - CURSOR_COLUMN_WIDTH);
183
+ const columns = this.injectionColumns(contentWidth);
184
+ const start = this.navigator.offset;
185
+ const end = start + this.navigator.windowSize;
186
+ for (let index = start; index < end; index++) {
187
+ const row = this.rows[index];
188
+ if (row === undefined) break;
189
+ if (row.kind === 'separator') {
190
+ lines.push('');
191
+ continue;
192
+ }
193
+ const selected = row.kind !== 'total' && index === this.navigator.selected;
194
+ const cursor = selected ? theme.fg('accent', '→ ') : BODY_INDENT;
195
+ const content = this.injectionLine(row, columns, contentWidth, selected);
196
+ lines.push(this.fit(`${cursor}${content}`, width));
197
+ }
198
+ return lines;
199
+ }
200
+
201
+ /** Choose the earliest useful shared value column, capped on wide terminals. */
202
+ private injectionColumns(width: number): InjectionColumns {
203
+ const contentRows = this.rows.filter(row => row.kind !== 'separator');
204
+ const labelWidth = Math.max(1, ...contentRows.map(row => visibleWidth(this.plainRowLabel(row))));
205
+ const tokenWidth = Math.max(1, ...contentRows.map(row => row.tokens.toLocaleString('en-US').length));
206
+ const idealValue = Math.min(MAX_TOKEN_VALUE_COLUMN, labelWidth + TOKEN_LEADER_GAP);
207
+ return { value: Math.max(1, Math.min(idealValue, width - tokenWidth)) };
208
+ }
209
+
210
+ /** One hierarchy row with dim leaders and a full token estimate when width permits. */
211
+ private injectionLine(
212
+ row: Exclude<InjectionRow, { readonly kind: 'separator' }>,
213
+ columns: InjectionColumns,
214
+ width: number,
215
+ selected: boolean,
216
+ ): string {
217
+ const labelWidth = Math.max(1, columns.value - 1);
218
+ const left = fitLine(this.styledRowLabel(row, selected), labelWidth);
219
+ const leader = this.tokenLeader(columns.value - visibleWidth(left));
220
+ const value = row.tokens.toLocaleString('en-US');
221
+ const tokens = row.kind === 'total' ? this.theme.bold(this.theme.fg('text', value)) : this.theme.fg(selected ? 'accent' : 'muted', value);
222
+ return fitLine(`${left}${leader}${tokens}`, width);
223
+ }
224
+
225
+ /** Fill a label/value gap with dim dots, retaining spaces at both ends. */
226
+ private tokenLeader(width: number): string {
227
+ if (width < 3) return ' '.repeat(Math.max(0, width));
228
+ return ` ${this.theme.fg('dim', '.'.repeat(width - 2))} `;
229
+ }
230
+
231
+ /** Unstyled hierarchy label used to keep the value column stable while scrolling. */
232
+ private plainRowLabel(row: Exclude<InjectionRow, { readonly kind: 'separator' }>): string {
233
+ const label = normalizeInlineText(row.label);
234
+ return row.kind === 'item' ? `${this.treePrefix(row)}${label}` : label;
235
+ }
236
+
237
+ /** Themed hierarchy label with connectors intentionally dim even on selection. */
238
+ private styledRowLabel(row: Exclude<InjectionRow, { readonly kind: 'separator' }>, selected: boolean): string {
239
+ const theme = this.theme;
240
+ const label = normalizeInlineText(row.label);
241
+ if (row.kind === 'group' || row.kind === 'total') {
242
+ return theme.bold(theme.fg(selected ? 'accent' : 'text', label));
243
+ }
244
+ const prefix = theme.fg('dim', this.treePrefix(row));
245
+ const color = selected ? 'accent' : row.depth === 1 ? 'muted' : 'dim';
246
+ return `${prefix}${theme.fg(color, label)}`;
247
+ }
248
+
249
+ /** Tree branch and ancestor continuation prefix for one item row. */
250
+ private treePrefix(row: Extract<InjectionRow, { readonly kind: 'item' }>): string {
251
+ const branch = row.isLast ? '└─ ' : '├─ ';
252
+ if (row.depth === 1) return branch;
253
+ return `${row.parentContinues === true ? '│ ' : ' '}${branch}`;
254
+ }
255
+
256
+ private scrollLine(width: number): string {
257
+ if (!this.navigator.hasOverflow) return this.fit('', width);
258
+ return this.fit(this.theme.fg('dim', `${BODY_INDENT}(${this.navigator.selectedOrdinal + 1}/${this.navigator.selectableCount})`), width);
259
+ }
260
+
261
+ private fit(line: string, width: number): string {
262
+ return fitLine(line, width);
263
+ }
264
+ }
@@ -0,0 +1,82 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /**
3
+ * Preview-only recognition of complete pi skill-expansion wrappers. The
4
+ * returned segments retain ordinary and malformed text verbatim; callers are
5
+ * responsible for terminal sanitization before parsing or rendering.
6
+ */
7
+
8
+ const SKILL_OPEN_TAG = /^<skill name="([^"\r\n]+)"(?: location="[^"\r\n]*")?>\r?$/gm;
9
+ const ANY_SKILL_OPEN_TAG = /^<skill(?:\s|>)[^\r\n]*\r?$/gm;
10
+ const SKILL_CLOSE_TAG = /^<\/skill>\r?$/gm;
11
+
12
+ /** One display segment from a user message containing attached skills. */
13
+ export type SkillPreviewSegment = { readonly type: 'text'; readonly text: string } | { readonly type: 'skill'; readonly name: string };
14
+
15
+ interface TagSpan {
16
+ readonly start: number;
17
+ readonly end: number;
18
+ }
19
+
20
+ interface SkillOpenTag extends TagSpan {
21
+ readonly name: string;
22
+ }
23
+
24
+ /**
25
+ * Replace no content directly: split complete skill wrappers into named
26
+ * segments so the UI can render compact badges while retaining unmatched
27
+ * wrappers as text. A later complete wrapper is still recognized when an
28
+ * earlier opening tag is malformed or unclosed.
29
+ */
30
+ export function splitSkillPreview(text: string): SkillPreviewSegment[] {
31
+ const openings = collectOpenTags(text);
32
+ const openingBoundaries = collectTagSpans(text, ANY_SKILL_OPEN_TAG);
33
+ const closings = collectTagSpans(text, SKILL_CLOSE_TAG);
34
+ const segments: SkillPreviewSegment[] = [];
35
+ let textStart = 0;
36
+ let openingBoundaryIndex = 0;
37
+ let closingIndex = 0;
38
+
39
+ for (let openingIndex = 0; openingIndex < openings.length; openingIndex++) {
40
+ const opening = openings[openingIndex];
41
+ if (opening === undefined || opening.start < textStart) continue;
42
+ while ((closings[closingIndex]?.start ?? text.length) < opening.end) closingIndex++;
43
+ const closing = closings[closingIndex];
44
+ if (closing === undefined) continue;
45
+
46
+ while ((openingBoundaries[openingBoundaryIndex]?.start ?? text.length) <= opening.start) {
47
+ openingBoundaryIndex++;
48
+ }
49
+ const nextOpening = openingBoundaries[openingBoundaryIndex];
50
+ if (nextOpening !== undefined && nextOpening.start < closing.start) continue;
51
+
52
+ pushTextSegment(segments, text.slice(textStart, opening.start));
53
+ segments.push({ type: 'skill', name: opening.name });
54
+ textStart = closing.end;
55
+ closingIndex++;
56
+ }
57
+
58
+ pushTextSegment(segments, text.slice(textStart));
59
+ return segments;
60
+ }
61
+
62
+ /** Collect structurally valid opening tags and their skill names. */
63
+ function collectOpenTags(text: string): SkillOpenTag[] {
64
+ return [...text.matchAll(SKILL_OPEN_TAG)].map(match => ({
65
+ start: match.index,
66
+ end: match.index + match[0].length,
67
+ name: match[1] ?? '',
68
+ }));
69
+ }
70
+
71
+ /** Collect complete line-delimited tag spans for one global expression. */
72
+ function collectTagSpans(text: string, expression: RegExp): TagSpan[] {
73
+ return [...text.matchAll(expression)].map(match => ({
74
+ start: match.index,
75
+ end: match.index + match[0].length,
76
+ }));
77
+ }
78
+
79
+ /** Append non-empty ordinary text without merging it into skill segments. */
80
+ function pushTextSegment(segments: SkillPreviewSegment[], text: string): void {
81
+ if (text.length > 0) segments.push({ type: 'text', text });
82
+ }
@@ -0,0 +1,133 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /**
3
+ * Pure proportional-cell model for the Usage view's 14×14 context map. The
4
+ * map uses estimated category totals against the selected Window/Fit scale.
5
+ * Pi's separately reported occupied tokens may differ because of tokenizer,
6
+ * serialization, caching, and last-response timing.
7
+ */
8
+ import type { ContextUsageSnapshot } from '../model';
9
+
10
+ export const DEFAULT_MAP_COLUMNS = 14;
11
+ export const DEFAULT_MAP_ROWS = 14;
12
+
13
+ const FIT_SCALE_PERCENT = 115;
14
+ const PERCENT_DENOMINATOR = 100;
15
+ const MINIMUM_FIT_SCALE_TOKENS = 10_000;
16
+ const FIT_SCALE_SIGNIFICANT_DIGITS = 2;
17
+
18
+ /** One visual map cell assigned to a category, the auto-compact buffer, or remaining free space. */
19
+ export interface UsageMapCell {
20
+ readonly categoryId?: string;
21
+ readonly fill: 'full' | 'partial' | 'buffer' | 'free';
22
+ }
23
+
24
+ /** Rectangular context-usage map in row-major order. */
25
+ export interface UsageMap {
26
+ readonly columns: number;
27
+ readonly rows: number;
28
+ readonly cells: readonly UsageMapCell[];
29
+ }
30
+
31
+ interface MapSegment {
32
+ readonly categoryId: string;
33
+ readonly start: number;
34
+ readonly end: number;
35
+ }
36
+
37
+ /**
38
+ * Calculate a Fit denominator from estimated occupancy: 15% headroom,
39
+ * rounded upward to two significant digits, with the documented floor/cap.
40
+ */
41
+ export function calculateFitMapScale(usage: ContextUsageSnapshot): number | undefined {
42
+ const contextWindow = usage.reported?.contextWindow;
43
+ if (contextWindow === undefined || !Number.isFinite(contextWindow) || contextWindow <= 0) return undefined;
44
+
45
+ const estimatedTotal = usage.categories.reduce((sum, category) => sum + category.tokens, 0);
46
+ const withHeadroom = (Math.max(0, estimatedTotal) * FIT_SCALE_PERCENT) / PERCENT_DENOMINATOR;
47
+ const rounded = roundUpToSignificantDigits(withHeadroom, FIT_SCALE_SIGNIFICANT_DIGITS);
48
+ return Math.min(contextWindow, Math.max(MINIMUM_FIT_SCALE_TOKENS, rounded));
49
+ }
50
+
51
+ /**
52
+ * Build a proportional map from estimated categories. `scaleTokens` changes
53
+ * only the mapped denominator; buffer placement remains anchored to the true
54
+ * context window. Returns undefined without a usable denominator.
55
+ */
56
+ export function buildUsageMap(
57
+ usage: ContextUsageSnapshot,
58
+ columns = DEFAULT_MAP_COLUMNS,
59
+ rows = DEFAULT_MAP_ROWS,
60
+ scaleTokens?: number,
61
+ ): UsageMap | undefined {
62
+ const contextWindow = usage.reported?.contextWindow;
63
+ if (contextWindow === undefined || !Number.isFinite(contextWindow) || contextWindow <= 0 || columns <= 0 || rows <= 0) return undefined;
64
+
65
+ const requestedScale = scaleTokens ?? contextWindow;
66
+ if (!Number.isFinite(requestedScale) || requestedScale <= 0) return undefined;
67
+ const mapScale = Math.min(contextWindow, requestedScale);
68
+ const cellCount = Math.floor(columns) * Math.floor(rows);
69
+ const estimatedTotal = usage.categories.reduce((sum, category) => sum + category.tokens, 0);
70
+ const occupiedTokens = clamp(estimatedTotal, 0, mapScale);
71
+ const occupiedCells = (occupiedTokens / mapScale) * cellCount;
72
+ // Fit reserves its headroom as visible free space; the true-window buffer remains outside the mapped range.
73
+ const windowOccupancy = clamp(estimatedTotal, 0, contextWindow);
74
+ const bufferTokens = mapScale < contextWindow ? 0 : clamp(usage.autoCompactReserveTokens ?? 0, 0, contextWindow - windowOccupancy);
75
+ const bufferStart = ((contextWindow - bufferTokens) / mapScale) * cellCount;
76
+ const segments = createSegments(usage, estimatedTotal, occupiedCells);
77
+ const cells = Array.from({ length: cellCount }, (_, index) => createCell(index, occupiedCells, bufferStart, segments));
78
+ return { columns: Math.floor(columns), rows: Math.floor(rows), cells };
79
+ }
80
+
81
+ /** Scale estimated category shares into the occupied map range. */
82
+ function createSegments(usage: ContextUsageSnapshot, estimatedTotal: number, occupiedCells: number): MapSegment[] {
83
+ if (estimatedTotal <= 0 || occupiedCells <= 0) return [];
84
+ const segments: MapSegment[] = [];
85
+ let cursor = 0;
86
+ for (const category of usage.categories) {
87
+ const size = (category.tokens / estimatedTotal) * occupiedCells;
88
+ segments.push({ categoryId: category.id, start: cursor, end: cursor + size });
89
+ cursor += size;
90
+ }
91
+ return segments;
92
+ }
93
+
94
+ /** Assign one map cell to its largest category overlap and classify its fill. */
95
+ function createCell(index: number, occupiedCells: number, bufferStart: number, segments: readonly MapSegment[]): UsageMapCell {
96
+ const occupiedOverlap = overlap(index, index + 1, 0, occupiedCells);
97
+ if (occupiedOverlap <= 0) {
98
+ // An unoccupied cell belongs to the buffer when at least half of it lies past the trigger point.
99
+ return overlap(index, index + 1, bufferStart, index + 1) >= 0.5 ? { fill: 'buffer' } : { fill: 'free' };
100
+ }
101
+
102
+ let categoryId: string | undefined;
103
+ let categoryOverlap = 0;
104
+ for (const segment of segments) {
105
+ const currentOverlap = overlap(index, index + 1, segment.start, segment.end);
106
+ if (currentOverlap > categoryOverlap) {
107
+ categoryId = segment.categoryId;
108
+ categoryOverlap = currentOverlap;
109
+ }
110
+ }
111
+ return {
112
+ categoryId,
113
+ fill: categoryOverlap >= 0.7 ? 'full' : 'partial',
114
+ };
115
+ }
116
+
117
+ /** Length shared by two half-open numeric ranges. */
118
+ function overlap(aStart: number, aEnd: number, bStart: number, bEnd: number): number {
119
+ return Math.max(0, Math.min(aEnd, bEnd) - Math.max(aStart, bStart));
120
+ }
121
+
122
+ /** Round a positive value upward at the requested significant-digit boundary. */
123
+ function roundUpToSignificantDigits(value: number, significantDigits: number): number {
124
+ if (!Number.isFinite(value) || value <= 0) return 0;
125
+ const boundary = 10 ** (Math.floor(Math.log10(value)) - significantDigits + 1);
126
+ return Math.ceil(value / boundary) * boundary;
127
+ }
128
+
129
+ /** Restrict a finite value to an inclusive range. */
130
+ function clamp(value: number, minimum: number, maximum: number): number {
131
+ if (!Number.isFinite(value)) return minimum;
132
+ return Math.min(maximum, Math.max(minimum, value));
133
+ }