@siuver/omp-debug-mode 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,140 @@
1
+ export const PROCEED_REMINDER = "Press Proceed/Mark as fixed when done.";
2
+
3
+ export const METHODOLOGY = `\
4
+ [DEBUG MODE METHODOLOGY — follow strictly]
5
+ This is OMP Debug Mode. Follow the steps in order. Do not skip them.
6
+
7
+ 1. Generate 3-5 precise hypotheses about WHY the bug occurs. Be detailed; prefer
8
+ more hypotheses over fewer. Mark each hypothesis pending until logs exist.
9
+
10
+ 2. Instrument code with runtime probes that test ALL remaining hypotheses in
11
+ parallel. Do not apply a product fix in this step. NEVER fix without runtime evidence first.
12
+ Always rely on runtime logs plus code — never code inspection alone. Unit tests are
13
+ optional and never replace a user reproduction.
14
+
15
+ Probe rules:
16
+ - Wrap EACH probe in a collapsible region (\`// #region agent log\` /
17
+ \`// #endregion\`, or the target language equivalent).
18
+ - Mark every probe with \`@omp-probe <id>\` so the ledger can track it.
19
+ - Every runtime probe MUST append exactly one compact JSON object plus a
20
+ newline to the exact absolute log file shown above.
21
+ - Schema: {"probe":"<id>","hypothesisId":"<A|B|C|...>","ts":<epoch-ms>,"location":"<file:line>","message":"<short>","data":<JSON-serializable-observation>}
22
+ - Include hypothesisId so each log line can confirm or reject one hypothesis.
23
+ - Append; never overwrite or truncate. Open, append, flush, and close promptly.
24
+ - Do not use HTTP, POST, localhost, sockets, or any network transport.
25
+ - Use the target environment's native file API. Console logging may supplement
26
+ the file but never replaces it. Never ask the user to copy console output.
27
+ - Aim for 2-6 probes; at least 1 is required; do not exceed 10.
28
+ - Never log secrets, tokens, passwords, API keys, or PII.
29
+ - The extension truncates the current log file at the start of each round.
30
+ Do not delete, rename, or overwrite that file yourself.
31
+
32
+ 3. Ask the user to reproduce. End your response with a
33
+ <reproduction_steps> numbered list (no header inside the tag) and this exact
34
+ sentence after the tag: "${PROCEED_REMINDER}"
35
+ Never say "click". Never ask the user to reply "done". Remind them to restart
36
+ the app or service if the instrumented code would otherwise be stale.
37
+ Then STOP. The user reproduces out-of-band.
38
+
39
+ 4. After Proceed: read logs with get_debug_logs (previous=true for the completed
40
+ run). Evaluate EACH hypothesis as CONFIRMED, REJECTED, or INCONCLUSIVE with
41
+ cited log-line evidence. Empty logs are themselves evidence (path not
42
+ executed, stale build, wrong path, or append failure).
43
+
44
+ 5. Fix only with 100% confidence and log proof. Do NOT remove instrumentation yet.
45
+ Keep probes active during the fix so the next reproduction can verify it.
46
+ A speculative fix without log proof is forbidden. If you are not 100%
47
+ confident, do not patch: update probes, add hypotheses if needed, and ask
48
+ for another reproduction.
49
+
50
+ 6. After a fix, ask the user to reproduce again. Compare before/after logs with
51
+ cited entries. Do not claim success without that log proof.
52
+
53
+ 7. If verification logs prove success and the user chooses Mark as fixed: remove
54
+ every probe, verify with list_debug_probes that the ledger is empty, then
55
+ summarize the root cause and the final fix in 1-2 lines.
56
+
57
+ If verification failed: FIRST remove any code changes from rejected hypotheses
58
+ (keep instrumentation and any proven fixes). THEN generate NEW hypotheses from
59
+ different subsystems, add more instrumentation, and reproduce again.
60
+
61
+ 8. After confirmed success: explain the problem and provide a concise summary
62
+ of the fix.`;
63
+
64
+ export function buildStartMessage(problem: string, logFile: string): string {
65
+ return (
66
+ `Starting debug mode. Problem report:\n\n${problem}\n\n` +
67
+ `Runtime log file (absolute): ${logFile}\n` +
68
+ "Every probe MUST append one JSON object per line to that exact file using the target environment's native file API. " +
69
+ "Console logging (including Unity Debug.Log) may supplement the file but never replaces it.\n\n" +
70
+ "Begin round 1: generate 3-5 precise hypotheses, instrument probes that test all of them in parallel, and do NOT apply a product fix yet. " +
71
+ `End with <reproduction_steps> and "${PROCEED_REMINDER}" then STOP.`
72
+ );
73
+ }
74
+
75
+ export function buildProceedMessage(args: {
76
+ run: string;
77
+ logCount: number;
78
+ reproductionDetails?: string;
79
+ hypotheses?: string;
80
+ }): string {
81
+ const userEvidence = args.reproductionDetails
82
+ ? `User added reproduction details after run ${args.run}:\n\n${args.reproductionDetails}\n\nTreat these details as evidence alongside the captured logs.\n`
83
+ : `User chose PROCEED after reproducing (run ${args.run} captured ${args.logCount} log entries).\n`;
84
+ const logNote =
85
+ args.logCount === 0
86
+ ? "No logs were captured: the instrumented code path may not have executed, the build may be stale, the path may be wrong, or the file append may have failed — treat that as a signal.\n"
87
+ : `Run ${args.run} captured ${args.logCount} log entries (by hypothesis: ${args.hypotheses ?? "unknown"}). A hypothesis with no entries was not exercised — that is not the same as being rejected.\n`;
88
+ return (
89
+ userEvidence +
90
+ logNote +
91
+ "Read the previous run with get_debug_logs (previous=true). Evaluate each hypothesis CONFIRMED/REJECTED/INCONCLUSIVE with cited log lines. " +
92
+ "Fix only if a hypothesis is confirmed with 100% confidence; keep all probes in place for a verification reproduce. " +
93
+ "If not confident, re-instrument without a speculative patch. " +
94
+ `If a previous fix failed, first revert code changes from rejected hypotheses. End with <reproduction_steps> and "${PROCEED_REMINDER}" then STOP.`
95
+ );
96
+ }
97
+
98
+ /**
99
+ * Cleanup turns get this instead of the full methodology: hypotheses,
100
+ * instrumentation and reproduction are all behind us, and restating them
101
+ * invites the agent to start another round instead of finishing.
102
+ */
103
+ export const CLEANUP_CONTRACT = `\
104
+ [DEBUG MODE — CLEANUP]
105
+ The user confirmed the fix. Only two things remain:
106
+ 1. Remove every debug probe listed in the ledger above, including its
107
+ \`#region agent log\` wrapper, then call list_debug_probes and confirm the
108
+ ledger is empty. Keep the proven fix; remove nothing else.
109
+ 2. Summarize in 1-2 lines: the root cause and the fix that is staying.
110
+ Do not add probes, form new hypotheses, or ask for another reproduction.`;
111
+
112
+ export function buildFixedMessage(probesJson: string): string {
113
+ return (
114
+ "User marked the problem FIXED.\n" +
115
+ "1. Remove every debug probe from the code (probe ledger below; verify with list_debug_probes after edits). Do not revert the proven fix.\n" +
116
+ "2. Then summarize in 1-2 lines: root cause, the fix applied, what remains in the working diff.\n" +
117
+ `Probe ledger: ${probesJson}`
118
+ );
119
+ }
120
+
121
+ export function extractAssistantText(content: unknown): string {
122
+ if (typeof content === "string") return content;
123
+ if (!Array.isArray(content)) return "";
124
+ const parts: string[] = [];
125
+ for (const block of content) {
126
+ if (!block || typeof block !== "object") continue;
127
+ const item = block as { type?: unknown; text?: unknown };
128
+ if (item.type === "text" && typeof item.text === "string") parts.push(item.text);
129
+ }
130
+ return parts.join("\n");
131
+ }
132
+
133
+ export function extractReproductionSteps(text: string): string[] {
134
+ const match = /<reproduction_steps>\s*([\s\S]*?)\s*<\/reproduction_steps>/i.exec(text);
135
+ if (!match) return [];
136
+ return match[1]
137
+ .split(/\r?\n/)
138
+ .map(line => line.trim())
139
+ .filter(line => line.length > 0);
140
+ }
package/src/probes.ts ADDED
@@ -0,0 +1,97 @@
1
+ import * as path from "node:path";
2
+ import type { Probe } from "./state";
3
+
4
+ const PROBE_MARK = /@omp-probe\s+([A-Za-z0-9_-]+)/g;
5
+
6
+ /**
7
+ * Edit-tool fields that describe the code being replaced. Scanning them would
8
+ * re-register the very probes an edit is removing, so the ledger ignores them.
9
+ */
10
+ const PRE_EDIT_KEYS = /^old(_?(string|str|text|content|source))?$/i;
11
+
12
+ export function probeIdsIn(text: unknown): string[] {
13
+ if (typeof text !== "string") return [];
14
+ const ids: string[] = [];
15
+ for (const m of text.matchAll(PROBE_MARK)) ids.push(m[1]);
16
+ return ids;
17
+ }
18
+
19
+ /** Absolute path of the file an edit/write tool call targets. */
20
+ export function probeFileFromInput(input: Record<string, unknown>, cwd: string): string {
21
+ const raw = typeof input.path === "string" ? input.path : typeof input.file_path === "string" ? input.file_path : null;
22
+ if (!raw) return "(unknown)";
23
+ return path.resolve(cwd, raw);
24
+ }
25
+
26
+ /** Register every `@omp-probe <id>` marker introduced by an edit/write tool call. */
27
+ export function recordProbes(probes: Probe[], round: number, input: Record<string, unknown>, cwd: string): void {
28
+ const file = probeFileFromInput(input, cwd);
29
+ for (const [key, value] of Object.entries(input)) {
30
+ if (PRE_EDIT_KEYS.test(key)) continue;
31
+ for (const id of probeIdsIn(value)) {
32
+ if (!probes.some(p => p.id === id)) probes.push({ id, file, round });
33
+ }
34
+ }
35
+ }
36
+
37
+ export interface LedgerScan {
38
+ /** Marker still present on disk. */
39
+ alive: Probe[];
40
+ /** File is gone or no longer contains the marker. */
41
+ gone: Probe[];
42
+ /** File exists but could not be read — never assume these were cleaned up. */
43
+ unknown: Probe[];
44
+ }
45
+
46
+ /** Ground truth: rescan every recorded file and classify each probe. */
47
+ export async function scanLedger(probes: readonly Probe[]): Promise<LedgerScan> {
48
+ const scan: LedgerScan = { alive: [], gone: [], unknown: [] };
49
+ const byFile = new Map<string, Probe[]>();
50
+ for (const p of probes) {
51
+ const list = byFile.get(p.file) ?? [];
52
+ list.push(p);
53
+ byFile.set(p.file, list);
54
+ }
55
+ for (const [file, filedProbes] of byFile) {
56
+ const handle = Bun.file(file);
57
+ let text: string | null = null;
58
+ let readable = true;
59
+ if (await handle.exists()) {
60
+ try {
61
+ text = await handle.text();
62
+ } catch {
63
+ readable = false;
64
+ }
65
+ }
66
+ for (const p of filedProbes) {
67
+ if (!readable) scan.unknown.push(p);
68
+ else if (text?.includes(`@omp-probe ${p.id}`)) scan.alive.push(p);
69
+ else scan.gone.push(p);
70
+ }
71
+ }
72
+ return scan;
73
+ }
74
+
75
+ /**
76
+ * Rescan and prune the ledger so it mirrors the code on disk. Unreadable files
77
+ * keep their probes so a transient read error cannot fake a clean teardown.
78
+ */
79
+ export async function syncLedger(state: { probes: Probe[] }): Promise<LedgerScan> {
80
+ const scan = await scanLedger(state.probes);
81
+ state.probes = [...scan.alive, ...scan.unknown];
82
+ return scan;
83
+ }
84
+
85
+ export function describeLedger(scan: LedgerScan): string {
86
+ if (scan.alive.length === 0 && scan.unknown.length === 0) return "Probe ledger is EMPTY — all probes removed.";
87
+ const lines: string[] = [];
88
+ if (scan.alive.length > 0) {
89
+ lines.push(`Alive probes (${scan.alive.length}):`);
90
+ for (const p of scan.alive) lines.push(`${p.id} — ${p.file}`);
91
+ }
92
+ if (scan.unknown.length > 0) {
93
+ lines.push(`Unverified probes (${scan.unknown.length}) — file could not be read, check manually:`);
94
+ for (const p of scan.unknown) lines.push(`${p.id} — ${p.file}`);
95
+ }
96
+ return lines.join("\n");
97
+ }
@@ -0,0 +1,22 @@
1
+ export const REVIEW_MARK_FIXED = "Mark as fixed";
2
+ export const REVIEW_PROCEED = "Proceed";
3
+ export const REVIEW_ADD_DETAILS = "Add reproduction details";
4
+ export const REVIEW_ABORT = "Abort debug mode";
5
+
6
+ export const REVIEW_OPTIONS = [
7
+ REVIEW_MARK_FIXED,
8
+ REVIEW_PROCEED,
9
+ REVIEW_ADD_DETAILS,
10
+ REVIEW_ABORT,
11
+ ] as const;
12
+
13
+ export const REVIEW_DESCRIPTIONS: Record<string, string> = {
14
+ [REVIEW_MARK_FIXED]: "Remove every probe and summarize the root cause",
15
+ [REVIEW_PROCEED]: "Read the captured logs, judge each hypothesis, continue",
16
+ [REVIEW_ADD_DETAILS]: "Describe what you observed before continuing",
17
+ [REVIEW_ABORT]: "Stop debugging and delete the logs; code changes stay",
18
+ };
19
+
20
+ export function reviewMenuOptions(): { label: string; description: string }[] {
21
+ return REVIEW_OPTIONS.map(label => ({ label, description: REVIEW_DESCRIPTIONS[label] ?? "" }));
22
+ }
package/src/state.ts ADDED
@@ -0,0 +1,147 @@
1
+ import { resolveRunLogFile } from "./log-files";
2
+
3
+ export const DEBUG_ENTRY = "com.omp.debug-mode.state";
4
+ /** Custom message that carries the blackboard + methodology into the model. */
5
+ export const DEBUG_CONTEXT_TYPE = "debug-mode-context";
6
+
7
+ export type Phase = "idle" | "round" | "waiting" | "cleanup";
8
+
9
+ export interface Probe {
10
+ id: string;
11
+ file: string;
12
+ round: number;
13
+ }
14
+
15
+ export interface DebugState {
16
+ active: boolean;
17
+ phase: Phase;
18
+ problem: string;
19
+ round: number;
20
+ runId: string | null;
21
+ /** Every run in creation order; the last entry is always the active run. */
22
+ runHistory: string[];
23
+ probes: Probe[];
24
+ debugDir: string | null;
25
+ logCounts: Record<string, number>;
26
+ hasRoundContent: boolean;
27
+ cleanupReady: boolean;
28
+ reproductionSteps: string[];
29
+ /** Times the current round was asked to produce its reproduction steps. */
30
+ gateNudges: number;
31
+ }
32
+
33
+ export function freshState(): DebugState {
34
+ return {
35
+ active: false,
36
+ phase: "idle",
37
+ problem: "",
38
+ round: 0,
39
+ runId: null,
40
+ runHistory: [],
41
+ probes: [],
42
+ debugDir: null,
43
+ logCounts: {},
44
+ hasRoundContent: false,
45
+ cleanupReady: false,
46
+ reproductionSteps: [],
47
+ gateNudges: 0,
48
+ };
49
+ }
50
+
51
+ /** Order run ids by round number, then by the base36 creation stamp. */
52
+ export function compareRunIds(a: string, b: string): number {
53
+ const parse = (id: string): [number, string] => {
54
+ const m = /^run(\d+)-(.*)$/.exec(id);
55
+ return m ? [Number(m[1]), m[2]] : [Number.POSITIVE_INFINITY, id];
56
+ };
57
+ const [roundA, stampA] = parse(a);
58
+ const [roundB, stampB] = parse(b);
59
+ if (roundA !== roundB) return roundA - roundB;
60
+ return stampA < stampB ? -1 : stampA > stampB ? 1 : 0;
61
+ }
62
+
63
+ export interface RunSelection {
64
+ run: string | null;
65
+ /** Set when the resolved run is not the one the caller literally asked for. */
66
+ note: string | null;
67
+ }
68
+
69
+ /**
70
+ * Pick which run `get_debug_logs` should read. The active run is truncated at
71
+ * the start of every round, so an empty current run falls back to the most
72
+ * recent run that actually captured something rather than reporting "no logs".
73
+ */
74
+ export function resolveRun(
75
+ params: { run?: string; previous?: boolean },
76
+ runHistory: readonly string[],
77
+ currentRun: string | null,
78
+ logCounts: Readonly<Record<string, number>>,
79
+ ): RunSelection {
80
+ if (params.run) return { run: params.run, note: null };
81
+
82
+ const currentIndex = currentRun ? runHistory.indexOf(currentRun) : -1;
83
+ const completed = currentIndex >= 0 ? runHistory.slice(0, currentIndex) : runHistory.filter(r => r !== currentRun);
84
+
85
+ if (params.previous) {
86
+ const previous = completed[completed.length - 1];
87
+ if (!previous) return { run: null, note: "no completed previous debug run is available" };
88
+ return { run: previous, note: null };
89
+ }
90
+
91
+ if (currentRun && (logCounts[currentRun] ?? 0) > 0) return { run: currentRun, note: null };
92
+
93
+ for (let i = completed.length - 1; i >= 0; i -= 1) {
94
+ const candidate = completed[i];
95
+ if ((logCounts[candidate] ?? 0) > 0) {
96
+ return {
97
+ run: candidate,
98
+ note: `the current run (${currentRun ?? "none"}) is empty; showing the last run with observations instead`,
99
+ };
100
+ }
101
+ }
102
+ return { run: currentRun, note: null };
103
+ }
104
+
105
+ export function logFileFor(s: DebugState, run = s.runId): string | null {
106
+ return resolveRunLogFile(s.debugDir, run, s.runId);
107
+ }
108
+
109
+ /**
110
+ * Keep only the newest copy of a custom-type injection. `before_agent_start`
111
+ * re-injects a fresh blackboard every turn; `context` runs afterwards on the
112
+ * combined history, so deleting every match would drop the copy that was just
113
+ * added and the model would never see it.
114
+ */
115
+ export function keepLatestCustomType<M extends { role?: string; customType?: string }>(
116
+ messages: readonly M[],
117
+ customType: string,
118
+ ): M[] {
119
+ let last = -1;
120
+ for (let i = 0; i < messages.length; i++) {
121
+ const message = messages[i];
122
+ if (message?.role === "custom" && message.customType === customType) last = i;
123
+ }
124
+ if (last < 0) return [...messages];
125
+ return messages.filter((message, index) => !(message.role === "custom" && message.customType === customType && index !== last));
126
+ }
127
+
128
+ export function blackboard(s: DebugState): string {
129
+ const probes = s.probes.map(p => `${p.id} (${p.file}, round ${p.round})`).join("\n ") || "(none)";
130
+ const counts = Object.entries(s.logCounts)
131
+ .map(([run, n]) => `${run}: ${n}`)
132
+ .join(", ") || "(none yet)";
133
+ return `\
134
+ [DEBUG MODE ACTIVE — round ${s.round}]
135
+
136
+ Problem under investigation:
137
+ ${s.problem}
138
+
139
+ Deployed probes (ground truth, maintained by the extension):
140
+ ${probes}
141
+
142
+ Current run log file (absolute path): ${logFileFor(s) ?? "(not initialized)"}
143
+ Runtime probes MUST append JSONL directly to that exact file using the target environment's native file APIs.
144
+ Console output such as Unity Debug.Log may supplement diagnostics but is never the runtime evidence for this workflow. Never ask the user to transcribe console output.
145
+ Logs by run: ${counts}
146
+ Current run id: ${s.runId ?? "(not started)"}`;
147
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,78 @@
1
+ import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
2
+ import { describeHypotheses, summarizeHypotheses } from "./log-files";
3
+ import { describeLedger, syncLedger } from "./probes";
4
+ import { type DebugState, logFileFor, resolveRun } from "./state";
5
+
6
+ export interface DebugToolDeps {
7
+ state: DebugState;
8
+ refreshLogCounts(): void;
9
+ readRunLines(run: string): string[];
10
+ }
11
+
12
+ export function registerDebugTools(pi: ExtensionAPI, deps: DebugToolDeps): void {
13
+ const z = pi.zod;
14
+ const { state, refreshLogCounts, readRunLines } = deps;
15
+
16
+ pi.registerTool({
17
+ name: "get_debug_logs",
18
+ label: "Get Debug Logs",
19
+ description:
20
+ "Read JSONL observations appended directly by debug-mode runtime probes. Each entry: {probe, hypothesisId, ts, location, message, data}. Defaults to the newest run that captured observations; pass previous=true to force the last completed reproduction run.",
21
+ parameters: z.object({
22
+ run: z.string().optional().describe("Run id filter (default: the newest run with observations)"),
23
+ probe: z.string().optional().describe("Probe id filter"),
24
+ previous: z.boolean().optional().describe("Use the previous (completed) run instead of the current one"),
25
+ }),
26
+ approval: "read",
27
+ async execute(_toolCallId, params) {
28
+ refreshLogCounts();
29
+ const selection = resolveRun(params, state.runHistory, state.runId, state.logCounts);
30
+ if (!selection.run) {
31
+ return {
32
+ content: [{ type: "text", text: `(${selection.note ?? "no debug run is available"})` }],
33
+ details: { run: null, file: null, count: 0 },
34
+ };
35
+ }
36
+
37
+ const run = selection.run;
38
+ let lines = readRunLines(run);
39
+ if (params.probe) {
40
+ lines = lines.filter(line => {
41
+ try {
42
+ const entry = JSON.parse(line) as { probe?: unknown };
43
+ return entry.probe === params.probe;
44
+ } catch {
45
+ return false;
46
+ }
47
+ });
48
+ }
49
+
50
+ const tallies = summarizeHypotheses(lines);
51
+ const scope = selection.note ? `run ${run} — ${selection.note}` : `run ${run}`;
52
+ const header = `(${scope}; by hypothesis: ${describeHypotheses(tallies)})\n`;
53
+ const body =
54
+ lines.join("\n") ||
55
+ "(no logs captured — the instrumented path may not have executed, the build may be stale, the path may be wrong, or the file append may have failed)";
56
+ return {
57
+ content: [{ type: "text", text: header + body }],
58
+ details: { run, file: logFileFor(state, run), count: lines.length, hypotheses: tallies },
59
+ };
60
+ },
61
+ });
62
+
63
+ pi.registerTool({
64
+ name: "list_debug_probes",
65
+ label: "List Debug Probes",
66
+ description:
67
+ "Ground-truth probe ledger for debug mode: rescans files for `@omp-probe <id>` markers and reports which probes are actually present in code, with their files. Use to verify cleanup is complete.",
68
+ parameters: z.object({}),
69
+ approval: "read",
70
+ async execute() {
71
+ const scan = await syncLedger(state);
72
+ return {
73
+ content: [{ type: "text", text: describeLedger(scan) }],
74
+ details: { alive: scan.alive, unknown: scan.unknown },
75
+ };
76
+ },
77
+ });
78
+ }
package/src/ui.ts ADDED
@@ -0,0 +1,78 @@
1
+ import type { ExtensionContext } from "@oh-my-pi/pi-coding-agent";
2
+ import { PROCEED_REMINDER } from "./methodology";
3
+ import type { DebugState } from "./state";
4
+
5
+ /** `setWidget` caps string-array widgets at 10 lines. */
6
+ export const WIDGET_MAX_LINES = 10;
7
+ const WIDGET_MAX_STEPS = 6;
8
+ const WIDGET_MAX_WIDTH = 90;
9
+
10
+ export type WidgetTone = "accent" | "dim";
11
+
12
+ export interface WidgetLine {
13
+ text: string;
14
+ tone: WidgetTone;
15
+ }
16
+
17
+ export function statusLabel(state: DebugState): string {
18
+ if (state.phase === "waiting") return "🐞 waiting-repro";
19
+ if (state.phase === "round") return `🐞 round ${state.round}`;
20
+ return "🐞 cleanup";
21
+ }
22
+
23
+ function clip(text: string): string {
24
+ return text.length > WIDGET_MAX_WIDTH ? `${text.slice(0, WIDGET_MAX_WIDTH - 1)}…` : text;
25
+ }
26
+
27
+ function plural(count: number, singular: string): string {
28
+ return `${count} ${singular}${count === 1 ? "" : "s"}`;
29
+ }
30
+
31
+ function logEntries(count: number): string {
32
+ return count === 1 ? "1 log entry" : `${count} log entries`;
33
+ }
34
+
35
+ /**
36
+ * Reproduction-gate widget: the call to action, an excerpt of the agent's
37
+ * reproduction steps, and the live evidence counter. Always within the host's
38
+ * line budget so nothing important is silently dropped.
39
+ */
40
+ export function waitingWidgetLines(state: DebugState, logCount: number): WidgetLine[] {
41
+ const lines: WidgetLine[] = [{ text: PROCEED_REMINDER, tone: "accent" }];
42
+ const shown = state.reproductionSteps.slice(0, WIDGET_MAX_STEPS);
43
+ for (const step of shown) lines.push({ text: clip(step), tone: "dim" });
44
+ const hidden = state.reproductionSteps.length - shown.length;
45
+ if (hidden > 0) lines.push({ text: `… +${plural(hidden, "more step")} in the transcript`, tone: "dim" });
46
+ lines.push({
47
+ text: `/debug-menu · run ${state.runId ?? "none"} — ${logEntries(logCount)}`,
48
+ tone: logCount > 0 ? "accent" : "dim",
49
+ });
50
+ return lines.slice(0, WIDGET_MAX_LINES);
51
+ }
52
+
53
+ export function reviewMenuTitle(round: number, logCount: number, probeCount: number): string {
54
+ return `Review debug round ${round} · ${logEntries(logCount)} · ${plural(probeCount, "probe")}`;
55
+ }
56
+
57
+ /**
58
+ * Render the status entry and the reproduction widget. `getLogCount` is only
59
+ * consulted at the reproduction gate so idle phases do not touch the log files.
60
+ */
61
+ export function applyUi(ctx: ExtensionContext | null, state: DebugState, getLogCount: () => number): void {
62
+ if (!ctx?.hasUI) return;
63
+ if (!state.active) {
64
+ ctx.ui.setStatus("debug-mode", undefined);
65
+ ctx.ui.setWidget("debug-mode", undefined);
66
+ return;
67
+ }
68
+ ctx.ui.setStatus("debug-mode", ctx.ui.theme.fg("warning", statusLabel(state)));
69
+ if (state.phase !== "waiting") {
70
+ ctx.ui.setWidget("debug-mode", undefined);
71
+ return;
72
+ }
73
+ const lines = waitingWidgetLines(state, getLogCount());
74
+ ctx.ui.setWidget(
75
+ "debug-mode",
76
+ lines.map(line => ctx.ui.theme.fg(line.tone, line.text)),
77
+ );
78
+ }
@@ -0,0 +1,79 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+
4
+ export const DEBUG_ROOT = path.join(".omp", "debug");
5
+ /** Line written to `.git/info/exclude` so probe logs stay out of `git status`. */
6
+ export const EXCLUDE_LINE = ".omp/debug/";
7
+
8
+ /**
9
+ * Directory name for one session's probe logs. Two omp sessions debugging the
10
+ * same repository must not share `current.jsonl`: each round truncates it and
11
+ * teardown deletes it, so a shared directory would let one session erase the
12
+ * other's evidence.
13
+ */
14
+ export function sessionDirName(sessionId: string | null | undefined): string {
15
+ const safe = (sessionId ?? "").replace(/[^A-Za-z0-9_-]/g, "");
16
+ return safe.length > 0 ? safe.slice(0, 16) : "session";
17
+ }
18
+
19
+ export function debugDirFor(cwd: string, sessionId: string | null | undefined): string {
20
+ return path.resolve(cwd, DEBUG_ROOT, sessionDirName(sessionId));
21
+ }
22
+
23
+ /** Walk up from `cwd` to the enclosing `.git` directory, if there is a plain one. */
24
+ export function findGitDir(cwd: string): string | null {
25
+ let dir = path.resolve(cwd);
26
+ for (;;) {
27
+ const candidate = path.join(dir, ".git");
28
+ try {
29
+ // A `.git` file means a worktree or submodule; leave those alone.
30
+ if (fs.statSync(candidate).isDirectory()) return candidate;
31
+ } catch {}
32
+ const parent = path.dirname(dir);
33
+ if (parent === dir) return null;
34
+ dir = parent;
35
+ }
36
+ }
37
+
38
+ export function needsExcludeLine(contents: string): boolean {
39
+ return !contents.split(/\r?\n/).some(line => line.trim() === EXCLUDE_LINE);
40
+ }
41
+
42
+ export function appendExcludeLine(contents: string): string {
43
+ if (!needsExcludeLine(contents)) return contents;
44
+ const separator = contents.length === 0 || contents.endsWith("\n") ? "" : "\n";
45
+ return `${contents}${separator}${EXCLUDE_LINE}\n`;
46
+ }
47
+
48
+ /**
49
+ * Keep probe logs out of the user's working diff via the repository-local
50
+ * exclude file, which is never committed. Best effort: a read-only or absent
51
+ * git directory is not a reason to fail debugging.
52
+ */
53
+ export function excludeDebugLogsFromGit(cwd: string): boolean {
54
+ const gitDir = findGitDir(cwd);
55
+ if (!gitDir) return false;
56
+ const excludeFile = path.join(gitDir, "info", "exclude");
57
+ try {
58
+ let contents = "";
59
+ try {
60
+ contents = fs.readFileSync(excludeFile, "utf8");
61
+ } catch {}
62
+ if (!needsExcludeLine(contents)) return false;
63
+ fs.mkdirSync(path.dirname(excludeFile), { recursive: true });
64
+ fs.writeFileSync(excludeFile, appendExcludeLine(contents));
65
+ return true;
66
+ } catch {
67
+ return false;
68
+ }
69
+ }
70
+
71
+ /** Remove the shared `.omp/debug` parent once the last session directory is gone. */
72
+ export function pruneDebugRoot(cwd: string): void {
73
+ try {
74
+ fs.rmdirSync(path.resolve(cwd, DEBUG_ROOT));
75
+ } catch {}
76
+ try {
77
+ fs.rmdirSync(path.resolve(cwd, ".omp"));
78
+ } catch {}
79
+ }