@mrclrchtr/supi-consulting 0.0.0-stage → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CLAUDE.md +23 -0
  2. package/CONTEXT.md +53 -0
  3. package/README.md +104 -2
  4. package/docs/adr/0001-use-an-isolated-antigravity-home.md +5 -0
  5. package/node_modules/@mrclrchtr/supi-core/README.md +137 -0
  6. package/node_modules/@mrclrchtr/supi-core/package.json +73 -0
  7. package/node_modules/@mrclrchtr/supi-core/src/api.ts +42 -0
  8. package/node_modules/@mrclrchtr/supi-core/src/config/config.ts +342 -0
  9. package/node_modules/@mrclrchtr/supi-core/src/config/prompt-surface.ts +363 -0
  10. package/node_modules/@mrclrchtr/supi-core/src/config.ts +17 -0
  11. package/node_modules/@mrclrchtr/supi-core/src/context/context-provider-registry.ts +36 -0
  12. package/node_modules/@mrclrchtr/supi-core/src/context/context-tag.ts +31 -0
  13. package/node_modules/@mrclrchtr/supi-core/src/context.ts +8 -0
  14. package/node_modules/@mrclrchtr/supi-core/src/debug-identity.ts +11 -0
  15. package/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +313 -0
  16. package/node_modules/@mrclrchtr/supi-core/src/debug-timing.ts +120 -0
  17. package/node_modules/@mrclrchtr/supi-core/src/debug.ts +14 -0
  18. package/node_modules/@mrclrchtr/supi-core/src/evidence-badge.ts +41 -0
  19. package/node_modules/@mrclrchtr/supi-core/src/footer-registry.ts +64 -0
  20. package/node_modules/@mrclrchtr/supi-core/src/index.ts +38 -0
  21. package/node_modules/@mrclrchtr/supi-core/src/llm.ts +356 -0
  22. package/node_modules/@mrclrchtr/supi-core/src/model-selection.ts +134 -0
  23. package/node_modules/@mrclrchtr/supi-core/src/path-utils.ts +44 -0
  24. package/node_modules/@mrclrchtr/supi-core/src/path.ts +2 -0
  25. package/node_modules/@mrclrchtr/supi-core/src/project-roots.ts +170 -0
  26. package/node_modules/@mrclrchtr/supi-core/src/project.ts +15 -0
  27. package/node_modules/@mrclrchtr/supi-core/src/prompt-surface.ts +4 -0
  28. package/node_modules/@mrclrchtr/supi-core/src/registry-utils.ts +93 -0
  29. package/node_modules/@mrclrchtr/supi-core/src/report.ts +121 -0
  30. package/node_modules/@mrclrchtr/supi-core/src/session-capabilities.ts +242 -0
  31. package/node_modules/@mrclrchtr/supi-core/src/session-capability-profiles.ts +240 -0
  32. package/node_modules/@mrclrchtr/supi-core/src/session-utils.ts +71 -0
  33. package/node_modules/@mrclrchtr/supi-core/src/session.ts +47 -0
  34. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +105 -0
  35. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-schema.ts +454 -0
  36. package/node_modules/@mrclrchtr/supi-core/src/settings.ts +36 -0
  37. package/node_modules/@mrclrchtr/supi-core/src/spinner-frames.ts +11 -0
  38. package/node_modules/@mrclrchtr/supi-core/src/status-spinner.ts +68 -0
  39. package/node_modules/@mrclrchtr/supi-core/src/terminal.ts +60 -0
  40. package/node_modules/@mrclrchtr/supi-core/src/tui.ts +141 -0
  41. package/package.json +73 -4
  42. package/scripts/live-probe.ts +139 -0
  43. package/src/agents/antigravity/activity.ts +22 -0
  44. package/src/agents/antigravity/adapter.ts +196 -0
  45. package/src/agents/antigravity/availability.ts +231 -0
  46. package/src/agents/antigravity/isolated-home.ts +346 -0
  47. package/src/agents/antigravity/models.ts +15 -0
  48. package/src/agents/antigravity/process/environment.ts +33 -0
  49. package/src/agents/antigravity/process/event-values.ts +273 -0
  50. package/src/agents/antigravity/process/events.ts +366 -0
  51. package/src/agents/antigravity/process/hooks.ts +219 -0
  52. package/src/agents/antigravity/process/ndjson.ts +120 -0
  53. package/src/agents/antigravity/process/protocol.ts +69 -0
  54. package/src/agents/antigravity/process/runner.ts +147 -0
  55. package/src/agents/antigravity/process/subprocess.ts +278 -0
  56. package/src/agents/antigravity/process/usage.ts +50 -0
  57. package/src/agents/antigravity/structured-output.ts +58 -0
  58. package/src/agents/antigravity/types.ts +17 -0
  59. package/src/agents/errors.ts +27 -0
  60. package/src/agents/types.ts +43 -0
  61. package/src/catalogue.ts +17 -0
  62. package/src/config.ts +26 -0
  63. package/src/conversation/handles.ts +187 -0
  64. package/src/evidence-hash.ts +6 -0
  65. package/src/extension.ts +26 -0
  66. package/src/footer-constants.ts +5 -0
  67. package/src/footer.ts +25 -0
  68. package/src/runtime.ts +244 -0
  69. package/src/settings.ts +38 -0
  70. package/src/tool/consulting_run/evidence.ts +169 -0
  71. package/src/tool/consulting_run/execute.ts +201 -0
  72. package/src/tool/consulting_run/guidance.ts +3 -0
  73. package/src/tool/consulting_run/input.ts +117 -0
  74. package/src/tool/consulting_run/register.ts +36 -0
  75. package/src/tool/consulting_run/render.ts +261 -0
  76. package/src/tool/consulting_run/result.ts +185 -0
  77. package/src/tool/consulting_run/spec.ts +20 -0
  78. package/src/types.ts +104 -0
@@ -0,0 +1,17 @@
1
+ // supi-core config domain — config loading.
2
+ export type {
3
+ AutomaticExclusionOptions,
4
+ SupiConfigLocation,
5
+ SupiConfigOptions,
6
+ } from "./config/config.ts";
7
+ export {
8
+ getSupiConfigPath,
9
+ loadAutomaticExclusionPatterns,
10
+ loadSupiConfig,
11
+ loadSupiConfigForScope,
12
+ loadSupiConfigSectionForScope,
13
+ readJsonFile,
14
+ removeSupiConfigKey,
15
+ replaceSupiConfigSection,
16
+ writeSupiConfig,
17
+ } from "./config/config.ts";
@@ -0,0 +1,36 @@
1
+ // Context provider registry for SuPi extensions.
2
+ //
3
+ // Extensions declare context data providers via `registerContextProvider()` during their
4
+ // factory function. The `/supi-context` command reads them via `getRegisteredContextProviders()`.
5
+
6
+ import { createRegistry } from "../registry-utils.ts";
7
+
8
+ export interface ContextProvider {
9
+ /** Unique identifier — e.g. "lsp" */
10
+ id: string;
11
+ /** Human-readable label shown in the report */
12
+ label: string;
13
+ /** Return structured data for display, or null when unavailable. */
14
+ getData: () => Record<string, string | number> | null;
15
+ }
16
+
17
+ const registry = createRegistry<ContextProvider>("context-provider-registry");
18
+
19
+ /**
20
+ * Register a context data provider for an extension.
21
+ * Call during the extension factory function (not async handlers).
22
+ * Duplicate ids replace the previous registration.
23
+ */
24
+ export function registerContextProvider(provider: ContextProvider): void {
25
+ registry.register(provider.id, provider);
26
+ }
27
+
28
+ /** Get all registered context providers in registration order. */
29
+ export function getRegisteredContextProviders(): ContextProvider[] {
30
+ return registry.getAll();
31
+ }
32
+
33
+ /** Clear the registry — used by tests. */
34
+ export function clearRegisteredContextProviders(): void {
35
+ registry.clear();
36
+ }
@@ -0,0 +1,31 @@
1
+ // XML context tag wrapping for SuPi extensions.
2
+ //
3
+ // Produces machine-parseable <extension-context> blocks that:
4
+ // - Are LLM-friendly (structured XML)
5
+ // - Carry metadata via attributes (source, file, turn, etc.)
6
+ // - Can be reconstructed from session history via regex
7
+
8
+ /**
9
+ * Wrap content in an `<extension-context>` XML tag.
10
+ *
11
+ * @param source - Extension identifier (e.g. "supi-claude-md", "supi-lsp")
12
+ * @param content - The text content to wrap
13
+ * @param attrs - Optional additional attributes (rendered as key="value")
14
+ * @returns Formatted XML string
15
+ */
16
+ export function wrapExtensionContext(
17
+ source: string,
18
+ content: string,
19
+ attrs?: Record<string, string | number>,
20
+ ): string {
21
+ const attrParts = [`source="${source}"`];
22
+
23
+ if (attrs) {
24
+ for (const [key, value] of Object.entries(attrs)) {
25
+ attrParts.push(`${key}="${String(value)}"`);
26
+ }
27
+ }
28
+
29
+ const openTag = `<extension-context ${attrParts.join(" ")}>`;
30
+ return `${openTag}\n${content}\n</extension-context>`;
31
+ }
@@ -0,0 +1,8 @@
1
+ // supi-core context domain — context providers and XML tags.
2
+ export type { ContextProvider } from "./context/context-provider-registry.ts";
3
+ export {
4
+ clearRegisteredContextProviders,
5
+ getRegisteredContextProviders,
6
+ registerContextProvider,
7
+ } from "./context/context-provider-registry.ts";
8
+ export { wrapExtensionContext } from "./context/context-tag.ts";
@@ -0,0 +1,11 @@
1
+ /** Maximum UTF-16 code-unit length of one debug identity string. */
2
+ export const MAX_DEBUG_IDENTITY_STRING = 512;
3
+
4
+ /** Marker appended to a truncated debug identity string. */
5
+ export const DEBUG_IDENTITY_TRUNCATION_MARKER = "…";
6
+
7
+ /** Bound one debug identity string, including its truncation marker. */
8
+ export function truncateDebugIdentity(value: string): string {
9
+ if (value.length <= MAX_DEBUG_IDENTITY_STRING) return value;
10
+ return `${value.slice(0, MAX_DEBUG_IDENTITY_STRING - 1)}${DEBUG_IDENTITY_TRUNCATION_MARKER}`;
11
+ }
@@ -0,0 +1,313 @@
1
+ // Shared debug event registry for SuPi extensions.
2
+ //
3
+ // Extensions record session-local diagnostic events here. The user-facing
4
+ // supi-debug extension owns policy/configuration and exposes events through a
5
+ // command/tool while this module stays dependency-free for producers.
6
+
7
+ export type DebugLevel = "debug" | "info" | "warning" | "error";
8
+ export type DebugAgentAccess = "off" | "sanitized" | "raw";
9
+
10
+ /** Custom session-entry type used to persist sanitized debug events. */
11
+ export const DEBUG_EVENT_ENTRY_TYPE = "supi-debug-event";
12
+ export interface DebugRegistryConfig {
13
+ /** Whether producers should retain debug events. */
14
+ enabled: boolean;
15
+ /** What the agent-callable debug tool may return. */
16
+ agentAccess: DebugAgentAccess;
17
+ /** Maximum number of session-local events to keep in memory. */
18
+ maxEvents: number;
19
+ }
20
+
21
+ export const DEBUG_REGISTRY_DEFAULTS: DebugRegistryConfig = {
22
+ enabled: false,
23
+ agentAccess: "sanitized",
24
+ maxEvents: 100,
25
+ };
26
+
27
+ export interface DebugEventInput {
28
+ /** Opaque identity for events directly owned by one public Tool call. */
29
+ operationId?: string;
30
+ source: string;
31
+ level: DebugLevel;
32
+ category: string;
33
+ message: string;
34
+ cwd?: string;
35
+ data?: unknown;
36
+ rawData?: unknown;
37
+ }
38
+
39
+ export interface DebugEvent extends DebugEventInput {
40
+ id: number;
41
+ timestamp: number;
42
+ data?: unknown;
43
+ rawData?: unknown;
44
+ }
45
+
46
+ export interface DebugEventQuery {
47
+ /** Match one exact Debug Operation ID. */
48
+ operationId?: string;
49
+ source?: string;
50
+ level?: DebugLevel;
51
+ category?: string;
52
+ limit?: number;
53
+ includeRaw?: boolean;
54
+ allowRaw?: boolean;
55
+ }
56
+
57
+ export interface DebugEventView {
58
+ id: number;
59
+ timestamp: number;
60
+ operationId?: string;
61
+ source: string;
62
+ level: DebugLevel;
63
+ category: string;
64
+ message: string;
65
+ cwd?: string;
66
+ data?: unknown;
67
+ rawData?: unknown;
68
+ }
69
+
70
+ export interface DebugEventQueryResult {
71
+ events: DebugEventView[];
72
+ rawAccessDenied: boolean;
73
+ }
74
+
75
+ /** Receives a sanitized event whenever the registry records one. */
76
+ export type DebugEventListener = (event: DebugEventView) => void;
77
+
78
+ export interface DebugSummary {
79
+ total: number;
80
+ byLevel: Partial<Record<DebugLevel, number>>;
81
+ bySource: Record<string, number>;
82
+ }
83
+
84
+ interface DebugRegistryState {
85
+ config: DebugRegistryConfig;
86
+ events: DebugEvent[];
87
+ listeners: Set<DebugEventListener>;
88
+ nextId: number;
89
+ }
90
+
91
+ const REGISTRY_KEY = Symbol.for("@mrclrchtr/supi-core/debug-registry");
92
+ const DEBUG_OPERATION_ID_RE = /^op-[A-Za-z0-9_-]{21}[AQgw]$/;
93
+ const SECRET_KEY_RE = /(?:token|password|passwd|secret|api[_-]?key|authorization|credential)/i;
94
+ const ENV_SECRET_RE =
95
+ /\b([A-Za-z0-9_]*(?:token|password|passwd|secret|api[_-]?key|authorization|credential)[A-Za-z0-9_]*)=(?:'[^']*'|"[^"]*"|\S+)/gi;
96
+ const AUTH_HEADER_RE = /\b(authorization\s*[:=]\s*)(?:bearer\s+)?[^\s;&|]+/gi;
97
+ const URL_SECRET_RE =
98
+ /([?&](?:token|password|passwd|secret|api[_-]?key|authorization|credential)=)[^&\s]+/gi;
99
+ const REDACTED = "[REDACTED]";
100
+
101
+ function cloneConfig(config: DebugRegistryConfig): DebugRegistryConfig {
102
+ return { ...config };
103
+ }
104
+
105
+ function getState(): DebugRegistryState {
106
+ let state = (globalThis as Record<symbol, unknown>)[REGISTRY_KEY] as
107
+ | DebugRegistryState
108
+ | undefined;
109
+ if (!state) {
110
+ state = {
111
+ config: cloneConfig(DEBUG_REGISTRY_DEFAULTS),
112
+ events: [],
113
+ listeners: new Set(),
114
+ nextId: 1,
115
+ };
116
+ (globalThis as Record<symbol, unknown>)[REGISTRY_KEY] = state;
117
+ }
118
+ // Keep the shared registry compatible with extension reloads that reuse an
119
+ // instance created before listeners existed.
120
+ if (!state.listeners) state.listeners = new Set();
121
+ return state;
122
+ }
123
+
124
+ function normalizeMaxEvents(value: number): number {
125
+ if (!Number.isFinite(value) || value <= 0) {
126
+ return DEBUG_REGISTRY_DEFAULTS.maxEvents;
127
+ }
128
+ return Math.floor(value);
129
+ }
130
+
131
+ function trimToMaxEvents(state: DebugRegistryState): void {
132
+ const maxEvents = normalizeMaxEvents(state.config.maxEvents);
133
+ if (state.events.length <= maxEvents) {
134
+ return;
135
+ }
136
+ state.events.splice(0, state.events.length - maxEvents);
137
+ }
138
+
139
+ /** Return whether a debug level is recognized by the registry. */
140
+ export function isDebugLevel(value: unknown): value is DebugLevel {
141
+ return value === "debug" || value === "info" || value === "warning" || value === "error";
142
+ }
143
+
144
+ /** Return whether a value has the exact 16-byte base64url Debug Operation ID form. */
145
+ export function isDebugOperationId(value: unknown): value is string {
146
+ return typeof value === "string" && DEBUG_OPERATION_ID_RE.test(value);
147
+ }
148
+
149
+ /** Match a debug event against the supported exact filters. */
150
+ export function matchesDebugEventQuery(
151
+ event: Pick<DebugEventView, "operationId" | "source" | "level" | "category">,
152
+ query: Pick<DebugEventQuery, "operationId" | "source" | "level" | "category">,
153
+ ): boolean {
154
+ if (query.operationId && event.operationId !== query.operationId) return false;
155
+ if (query.source && event.source !== query.source) return false;
156
+ if (query.level && event.level !== query.level) return false;
157
+ if (query.category && event.category !== query.category) return false;
158
+ return true;
159
+ }
160
+
161
+ function sanitizeString(value: string): string {
162
+ return value
163
+ .replace(ENV_SECRET_RE, (_match, key: string) => `${key}=${REDACTED}`)
164
+ .replace(AUTH_HEADER_RE, (_match, prefix: string) => `${prefix}${REDACTED}`)
165
+ .replace(URL_SECRET_RE, (_match, prefix: string) => `${prefix}${REDACTED}`);
166
+ }
167
+
168
+ function redactValue(value: unknown, depth: number): unknown {
169
+ if (depth <= 0) return "[MaxDepth]";
170
+ if (typeof value === "string") return sanitizeString(value);
171
+ if (typeof value !== "object" || value === null) return value;
172
+ if (Array.isArray(value)) return value.map((item) => redactValue(item, depth - 1));
173
+
174
+ const redacted: Record<string, unknown> = {};
175
+ for (const [key, item] of Object.entries(value)) {
176
+ redacted[key] = SECRET_KEY_RE.test(key) ? REDACTED : redactValue(item, depth - 1);
177
+ }
178
+ return redacted;
179
+ }
180
+
181
+ /** Configure the shared debug registry. Existing events are trimmed to the new max size. */
182
+ export function configureDebugRegistry(config: Partial<DebugRegistryConfig>): DebugRegistryConfig {
183
+ const state = getState();
184
+ state.config = {
185
+ ...state.config,
186
+ ...config,
187
+ maxEvents: normalizeMaxEvents(config.maxEvents ?? state.config.maxEvents),
188
+ };
189
+ trimToMaxEvents(state);
190
+ return getDebugRegistryConfig();
191
+ }
192
+
193
+ /** Return the active debug registry configuration. */
194
+ export function getDebugRegistryConfig(): DebugRegistryConfig {
195
+ return cloneConfig(getState().config);
196
+ }
197
+
198
+ /** Return whether the Debug Registry currently retains producer events. */
199
+ export function isDebugRegistryEnabled(): boolean {
200
+ return getState().config.enabled;
201
+ }
202
+
203
+ /** Best-effort redaction helper for data exposed through sanitized debug views. */
204
+ export function redactDebugData<T>(value: T): T {
205
+ return redactValue(value, 8) as T;
206
+ }
207
+
208
+ function toSanitizedView(event: DebugEvent): DebugEventView {
209
+ return {
210
+ id: event.id,
211
+ timestamp: event.timestamp,
212
+ operationId: event.operationId,
213
+ source: event.source,
214
+ level: event.level,
215
+ category: event.category,
216
+ message: event.message,
217
+ cwd: event.cwd,
218
+ data: event.data === undefined ? undefined : redactDebugData(event.data),
219
+ };
220
+ }
221
+
222
+ /** Subscribe to sanitized events. Listeners are isolated so diagnostics cannot disrupt producers. */
223
+ export function subscribeDebugEvents(listener: DebugEventListener): () => void {
224
+ const state = getState();
225
+ state.listeners.add(listener);
226
+ return () => state.listeners.delete(listener);
227
+ }
228
+
229
+ /** Record a session-local debug event if debugging is enabled. */
230
+ export function recordDebugEvent(input: DebugEventInput): DebugEvent | null {
231
+ const state = getState();
232
+ if (input.operationId !== undefined && !isDebugOperationId(input.operationId)) {
233
+ return null;
234
+ }
235
+ if (!state.config.enabled) {
236
+ return null;
237
+ }
238
+
239
+ const event: DebugEvent = {
240
+ ...input,
241
+ id: state.nextId++,
242
+ timestamp: Date.now(),
243
+ data: input.data === undefined ? undefined : redactDebugData(input.data),
244
+ };
245
+ state.events.push(event);
246
+ trimToMaxEvents(state);
247
+ for (const listener of state.listeners) {
248
+ try {
249
+ listener(toSanitizedView(event));
250
+ } catch {
251
+ // Debug-event consumers must not alter producer behavior.
252
+ }
253
+ }
254
+ return {
255
+ ...event,
256
+ data: event.data === undefined ? undefined : redactDebugData(event.data),
257
+ };
258
+ }
259
+
260
+ /** Query retained debug events newest-first. Results are sanitized unless raw access is requested and allowed. */
261
+ export function getDebugEvents(query: DebugEventQuery = {}): DebugEventQueryResult {
262
+ const state = getState();
263
+ const allowRaw = Boolean(
264
+ query.includeRaw && query.allowRaw && state.config.agentAccess === "raw",
265
+ );
266
+ const rawAccessDenied = Boolean(query.includeRaw && !allowRaw);
267
+ const limit = query.limit && query.limit > 0 ? Math.floor(query.limit) : state.config.maxEvents;
268
+
269
+ const events = state.events
270
+ .filter((event) => matchesDebugEventQuery(event, query))
271
+ .slice()
272
+ .reverse()
273
+ .slice(0, limit)
274
+ .map((event): DebugEventView => {
275
+ const view = toSanitizedView(event);
276
+ if (allowRaw && event.rawData !== undefined) {
277
+ view.rawData = event.rawData;
278
+ }
279
+ return view;
280
+ });
281
+
282
+ return { events, rawAccessDenied };
283
+ }
284
+
285
+ /** Return aggregate debug counts suitable for summary displays. */
286
+ export function getDebugSummary(): DebugSummary | null {
287
+ const events = getState().events;
288
+ if (events.length === 0) {
289
+ return null;
290
+ }
291
+
292
+ const summary: DebugSummary = { total: events.length, byLevel: {}, bySource: {} };
293
+ for (const event of events) {
294
+ summary.byLevel[event.level] = (summary.byLevel[event.level] ?? 0) + 1;
295
+ summary.bySource[event.source] = (summary.bySource[event.source] ?? 0) + 1;
296
+ }
297
+ return summary;
298
+ }
299
+
300
+ /** Clear retained events while preserving configuration. */
301
+ export function clearDebugEvents(): void {
302
+ const state = getState();
303
+ state.events = [];
304
+ }
305
+
306
+ /** Reset the debug registry to defaults; intended for tests. */
307
+ export function resetDebugRegistry(): void {
308
+ const state = getState();
309
+ state.config = cloneConfig(DEBUG_REGISTRY_DEFAULTS);
310
+ state.events = [];
311
+ state.listeners.clear();
312
+ state.nextId = 1;
313
+ }
@@ -0,0 +1,120 @@
1
+ import { performance } from "node:perf_hooks";
2
+ import {
3
+ type DebugEvent,
4
+ type DebugEventInput,
5
+ isDebugRegistryEnabled,
6
+ recordDebugEvent,
7
+ } from "./debug-registry.ts";
8
+
9
+ /** Monotonic duration data added to a timed debug event. */
10
+ export interface DebugTiming {
11
+ readonly durationMs: number;
12
+ readonly phasesMs: Readonly<Record<string, number>>;
13
+ }
14
+
15
+ /** Debug event input whose data can receive the reserved `timing` field. */
16
+ export interface TimedDebugEventInput extends Omit<DebugEventInput, "data"> {
17
+ readonly data?: Readonly<Record<string, unknown>>;
18
+ }
19
+
20
+ /** Test seam for the monotonic clock used by a debug timer. */
21
+ export interface DebugTimerOptions {
22
+ readonly now?: () => number;
23
+ }
24
+
25
+ /** Lazy timed-event input that is not evaluated when Debug is disabled. */
26
+ export type TimedDebugEventFactory = () => TimedDebugEventInput;
27
+
28
+ /** One-shot debug timer with optional sequential phase measurements. */
29
+ export interface DebugTimer {
30
+ /** Whether this timer sampled Debug as enabled when it started. */
31
+ readonly enabled: boolean;
32
+ /** Finish the current phase and start the next unnamed interval. */
33
+ mark(phase: string): void;
34
+ /** Record one event. A second call returns `null` without recording another event. */
35
+ finish(
36
+ input: TimedDebugEventInput | TimedDebugEventFactory,
37
+ finalPhase?: string,
38
+ ): DebugEvent | null;
39
+ }
40
+
41
+ /**
42
+ * Start a monotonic timer for one debug event.
43
+ *
44
+ * Each `mark(name)` stores the interval since the previous mark. `finish()`
45
+ * stores the total duration and can name the final interval. Repeated phase
46
+ * names are accumulated. Event data reserves the `timing` field. When Debug is
47
+ * disabled at start, this returns a no-op timer and does not read the clock.
48
+ * Pass a factory to `finish()` to avoid event-data construction when disabled.
49
+ * Clock, event-construction, and registry failures are isolated from the
50
+ * measured operation and make the timer a no-op.
51
+ */
52
+ export function startDebugTimer(options: DebugTimerOptions = {}): DebugTimer {
53
+ if (!isDebugRegistryEnabled()) return DISABLED_DEBUG_TIMER;
54
+ const now = options.now ?? performance.now.bind(performance);
55
+ let startedAt: number;
56
+ try {
57
+ startedAt = now();
58
+ } catch {
59
+ return DISABLED_DEBUG_TIMER;
60
+ }
61
+ let previousAt = startedAt;
62
+ let finished = false;
63
+ let failed = false;
64
+ const phases = new Map<string, number>();
65
+
66
+ const markAt = (phase: string, current: number): void => {
67
+ const name = phase.trim();
68
+ if (!name) return;
69
+ phases.set(name, (phases.get(name) ?? 0) + Math.max(0, current - previousAt));
70
+ previousAt = current;
71
+ };
72
+
73
+ return {
74
+ enabled: true,
75
+ mark(phase) {
76
+ if (finished || failed) return;
77
+ try {
78
+ markAt(phase, now());
79
+ } catch {
80
+ failed = true;
81
+ }
82
+ },
83
+ finish(input, finalPhase) {
84
+ if (finished || failed) return null;
85
+ finished = true;
86
+ try {
87
+ if (!isDebugRegistryEnabled()) return null;
88
+ const completedAt = now();
89
+ if (finalPhase) markAt(finalPhase, completedAt);
90
+ const phasesMs = Object.fromEntries(
91
+ [...phases.entries()].map(([name, value]) => [name, duration(value)]),
92
+ );
93
+ const timing: DebugTiming = {
94
+ durationMs: duration(completedAt - startedAt),
95
+ phasesMs,
96
+ };
97
+ const eventInput = typeof input === "function" ? input() : input;
98
+ return recordDebugEvent({
99
+ ...eventInput,
100
+ data: { ...eventInput.data, timing },
101
+ });
102
+ } catch {
103
+ return null;
104
+ }
105
+ },
106
+ };
107
+ }
108
+
109
+ const DISABLED_DEBUG_TIMER: DebugTimer = Object.freeze({
110
+ enabled: false,
111
+ mark() {},
112
+ finish() {
113
+ return null;
114
+ },
115
+ });
116
+
117
+ function duration(value: number): number {
118
+ if (!Number.isFinite(value)) return 0;
119
+ return Math.round(Math.max(0, value) * 10) / 10;
120
+ }
@@ -0,0 +1,14 @@
1
+ // Debug domain entry for `@mrclrchtr/supi-core/debug`.
2
+ //
3
+ // Kept separate from debug-registry.ts so debug-timing.ts can import the
4
+ // registry without creating an import cycle through the barrel re-export.
5
+
6
+ export {
7
+ DEBUG_IDENTITY_TRUNCATION_MARKER,
8
+ MAX_DEBUG_IDENTITY_STRING,
9
+ truncateDebugIdentity,
10
+ } from "./debug-identity.ts";
11
+ // biome-ignore lint/performance/noReExportAll: preserve the stable debug domain entry point
12
+ export * from "./debug-registry.ts";
13
+ // biome-ignore lint/performance/noReExportAll: preserve the stable debug domain entry point
14
+ export * from "./debug-timing.ts";
@@ -0,0 +1,41 @@
1
+ /**
2
+ * TUI-facing evidence badge string formatter.
3
+ *
4
+ * Pure string formatting — no pi-tui dependency. Consumes evidence
5
+ * completeness metadata and produces compact human-readable badges.
6
+ */
7
+
8
+ /** Metadata describing how many evidence atoms were shown vs exist. */
9
+ export interface EvidenceBadgeInput {
10
+ shownCount: number;
11
+ totalCount: number | null;
12
+ omittedCount: number | null;
13
+ partialReason: string | null;
14
+ /** Human-readable label for the badge, e.g. "references", "symbols". */
15
+ label: string;
16
+ }
17
+
18
+ /**
19
+ * Format a compact evidence completeness badge.
20
+ *
21
+ * | Input | Output |
22
+ * |------------------------------------------------------|---------------------------------------|
23
+ * | shown=12, total=12, omitted=0, label="references" | `12 references` |
24
+ * | shown=8, total=20, omitted=12, label="symbols" | `8 of 20 symbols (12 omitted)` |
25
+ * | shown=5, total=null, omitted=2, reason="timeout" | `5 matches (2 collected omitted; more may exist — timeout)` |
26
+ */
27
+ export function formatEvidenceBadge(input: EvidenceBadgeInput): string {
28
+ const { shownCount, totalCount, omittedCount, partialReason, label } = input;
29
+
30
+ if (totalCount === null) {
31
+ const reasonSuffix = partialReason ? ` — ${partialReason}` : "";
32
+ const omittedPrefix = (omittedCount ?? 0) > 0 ? `${omittedCount} collected omitted; ` : "";
33
+ return `${shownCount} ${label} (${omittedPrefix}more may exist${reasonSuffix})`;
34
+ }
35
+
36
+ if (omittedCount !== null && omittedCount > 0) {
37
+ return `${shownCount} of ${totalCount} ${label} (${omittedCount} omitted)`;
38
+ }
39
+
40
+ return `${shownCount} ${label}`;
41
+ }
@@ -0,0 +1,64 @@
1
+ // Shared footer contribution registry for SuPi extensions.
2
+ //
3
+ // Extensions register pre-styled text chunks with a placement hint
4
+ // ("stats" for the metrics line, "status" for the extension status line).
5
+ // The custom footer in supi-extras reads these contributions and renders them
6
+ // alongside the built-in metrics. Extensions can use PI's status API as a
7
+ // fallback when the custom footer is not installed.
8
+
9
+ import { createRegistry } from "./registry-utils.ts";
10
+
11
+ /** Event emitted when a dynamic footer contribution needs a new render. */
12
+ export const FOOTER_INVALIDATE_EVENT = "supi:footer:invalidate";
13
+
14
+ /** Where the contribution should appear in the footer. */
15
+ export type FooterPlacement = "stats" | "stats-end" | "status";
16
+
17
+ /** A single footer contribution registered by an extension. */
18
+ export interface FooterContribution {
19
+ /**
20
+ * Unique key for this contribution. Re-registering with the same key replaces it.
21
+ * A same-key Pi status is treated as this contribution's built-in-footer fallback.
22
+ */
23
+ key: string;
24
+ /** Which footer line this belongs on. */
25
+ placement: FooterPlacement;
26
+ /**
27
+ * Sort order within the placement (lower values render further left). Default: 100.
28
+ * Priority 0 is reserved for the turn cache-hit part so it stays adjacent to CH.
29
+ */
30
+ priority?: number;
31
+ /** Return the pre-styled text for this contribution. Called on every render. */
32
+ render: () => string;
33
+ }
34
+
35
+ const registry = createRegistry<FooterContribution>("footer-contributions");
36
+
37
+ function sortByPriority(a: FooterContribution, b: FooterContribution): number {
38
+ return (a.priority ?? 100) - (b.priority ?? 100);
39
+ }
40
+
41
+ export const footerContributions = {
42
+ /** Register or replace a footer contribution. */
43
+ register(contribution: FooterContribution): void {
44
+ registry.register(contribution.key, contribution);
45
+ },
46
+
47
+ /** Remove a contribution (e.g. on session_shutdown or when disabled). */
48
+ unregister(key: string): void {
49
+ registry.unregister(key);
50
+ },
51
+
52
+ /** Get contributions for a specific placement, sorted by priority. */
53
+ getByPlacement(placement: FooterPlacement): FooterContribution[] {
54
+ return registry
55
+ .getAll()
56
+ .filter((c) => c.placement === placement)
57
+ .sort(sortByPriority);
58
+ },
59
+
60
+ /** Remove all contributions (primarily for tests). */
61
+ clear(): void {
62
+ registry.clear();
63
+ },
64
+ };