Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .agents/skills/helmor-debug-loop/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
name: helmor-debug-loop
description: Autonomous local-development debugging loop for Helmor bugs. Use when the user asks an agent to reproduce, diagnose, instrument, fix, or verify a Helmor local dev build issue using repeated local UI simulation, temporary logging, Tauri MCP/towery MCP, screenshots, DOM/accessibility snapshots, IPC traces, console/system logs, terminal/run-script logs, or multi-attempt verification. This skill coordinates with $helmor-debug-operate for operating the running desktop app.
---

# Helmor Debug Loop

Use this skill to drive a bounded reproduce -> instrument -> inspect -> fix -> verify loop for Helmor local-dev bugs. Always use `$helmor-debug-operate` for actual local app control through Tauri MCP; this skill owns the debugging strategy and evidence discipline.

## Core Loop

1. Define the suspected behavior, expected behavior, and success signal in one or two sentences.
2. Reproduce through `$helmor-debug-operate` with real UI actions when possible. Start with screenshots, DOM/accessibility snapshots, IPC monitor, console/system logs, and terminal buffers.
3. If evidence is insufficient, add the smallest temporary log or probe with a unique prefix such as `[debug-loop:<slug>]`, rerun the flow, then remove or justify the probe before finalizing.
4. Analyze the evidence before editing product code. Prefer a narrow fix that explains the observed signal.
5. Verify the fix with the same user path. For user-visible flows, require three consecutive successful runs unless the user explicitly lowers the bar.
6. Produce an evidence pack under `.agent-contexts/<task-slug>/` with repro attempts, logs, screenshots, IPC, fix summary, and remaining uncertainty.

## Fault Tolerance

- If you cannot reproduce after three distinct attempts, do not invent a failure. Mark the state as `not reproduced`, preserve evidence, inspect code paths that should have fired, and report the most likely missing precondition.
- If the bug is flaky, run at least three attempts and compare evidence. Treat intermittent pass/fail as a valid finding, not a failure of the loop.
- If Tauri MCP cannot connect, use `$helmor-debug-operate` recovery steps. If the bridge remains unavailable, fall back to static code analysis and terminal tests, and label UI verification as blocked.
- If a skill recipe fails three times, follow `$helmor-debug-operate` stale-skill rules: reason from fresh screenshots/DOM/code, record a candidate skill update, and ask before editing that skill unless the user explicitly requested it.
- If adding logs risks exposing secrets, log shape/count/state only. Never print access tokens, credentials, API keys, cookies, or private account details.
- If verification cannot be run safely because it would mutate durable user data, switch to a disposable workspace/session or stop and state the risk.

## Evidence Sources

Use the available signals in this order:

- Terminal buffers: use `$helmor-debug-operate`'s **Call App Commands** helper to run `debug_list_terminal_buffers`, then `debug_read_terminal_buffer` with the returned raw `scriptType`.
- UI state: screenshot plus accessibility or structure snapshot.
- IPC: start monitor, perform one action, capture filtered commands/events, then stop monitor.
- Logs: Tauri console/system logs, sidecar JSONL logs under the dev data dir when relevant.
- Code probes: temporary logs with unique prefixes, guarded by debug context when possible.

Read `references/debug-loop.md` when the task needs the full loop checklist or when reproduction fails. Use scripts in `scripts/` to summarize logs and build evidence packs instead of pasting raw dumps into the chat.
4 changes: 4 additions & 0 deletions .agents/skills/helmor-debug-loop/agents/openai.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
interface:
display_name: "Helmor Debug Loop"
short_description: "Autonomous Helmor local-dev bug loop."
default_prompt: "Use $helmor-debug-loop to reproduce, instrument, inspect, fix, and verify a Helmor local-dev bug."
95 changes: 95 additions & 0 deletions .agents/skills/helmor-debug-loop/references/debug-loop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Helmor Debug Loop Reference

Use this reference after loading `SKILL.md` when a bug needs iterative local verification.

## Attempt Structure

Each attempt should record:

- Attempt number and timestamp.
- Preconditions: workspace, session, selected model/mode, run action, feature flags, relevant settings.
- Exact user path driven through `$helmor-debug-operate`.
- Evidence collected: screenshot path, DOM/snapshot file, IPC capture, console/system logs, terminal buffer ids, and code probes.
- Result: `reproduced`, `not reproduced`, `flaky`, `fixed`, `blocked`, or `inconclusive`.

Store attempt notes under `.agent-contexts/<task-slug>/attempts.md`.

## Terminal Buffer Commands

When the app has a debug build with the terminal buffer commands registered, use `$helmor-debug-operate`'s **Call App Commands** helper. Do not call the Tauri MCP `ipc_execute_command` tool for these app commands; the current bridge returns `Unsupported Tauri command`.

```json
{ "id": "list-buffers", "command": "debug_list_terminal_buffers", "payload": {} }
```

Pick the relevant item from the returned `repoId`, `workspaceId`, and `scriptType`, then read the tail:

```json
{
"id": "read-buffer",
"command": "debug_read_terminal_buffer",
"payload": {
"repoId": "REPO_ID",
"workspaceId": "WORKSPACE_ID_OR_NULL",
"scriptType": "RAW_SCRIPT_TYPE_FROM_LIST",
"maxBytes": 200000
}
}
```

If the helper result says the command is unavailable, fall back to visible xterm screenshots/DOM and mark terminal-buffer evidence as unavailable. Do not block the whole loop on this one signal.

## Reproduction Branches

### Reproduced

1. Freeze the smallest path that reproduces the bug.
2. Add temporary probes only where the next unknown remains.
3. Fix the code.
4. Repeat the same path three times.

### Not Reproduced

After three distinct attempts:

1. Record every precondition and attempt.
2. Inspect the code path that should have handled the user flow.
3. Identify missing preconditions, likely stale recipe, or environment drift.
4. If a low-risk static fix is obvious, make it and verify with available tests; otherwise report `not reproduced` with next recommended probe.

### Flaky

Treat flaky behavior as a valid bug. Preserve a run table with pass/fail state and compare:

- Logs immediately before divergence.
- DOM state before the click/keypress.
- IPC event ordering.
- Terminal/run-script timing.

Fix the race or state leak only after the divergence has a plausible mechanism.

### Blocked

Use `blocked` only when the loop cannot progress without user input or an external state change, such as missing credentials, no running debug build, destructive verification risk, or unavailable Tauri bridge after recovery attempts.

## Temporary Logging Rules

- Use a unique prefix: `[debug-loop:<short-slug>]`.
- Log the smallest state needed: ids, booleans, counts, branch names, command names, elapsed times.
- Avoid secrets and large objects.
- Prefer existing structured logging in Rust/backend and `console.debug` in frontend only when it is removed before final.
- Remove temporary logs before final unless they become intentional product diagnostics.

## Evidence Pack Checklist

Create `.agent-contexts/<task-slug>/evidence.md` with:

- User request and expected behavior.
- Reproduction attempts table.
- Evidence links and summaries.
- Root cause.
- Fix summary.
- Verification table with three pass rows or a clear exception.
- Residual risk and unverified paths.

Use `scripts/terminal_log_summary.py` for terminal text and `scripts/build_evidence_pack.py` to assemble a markdown pack.
85 changes: 85 additions & 0 deletions .agents/skills/helmor-debug-loop/scripts/build_evidence_pack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""Build a compact markdown evidence pack from local debugging artifacts."""

from __future__ import annotations

import argparse
from pathlib import Path


TEXT_EXTENSIONS = {
".txt",
".log",
".json",
".jsonl",
".md",
".html",
".xml",
".yaml",
".yml",
}


def tail_text(path: Path, max_lines: int) -> str:
text = path.read_text(errors="replace")
lines = text.splitlines()
return "\n".join(lines[-max_lines:])


def parse_artifact(value: str) -> tuple[str, Path]:
if "=" not in value:
path = Path(value)
return (path.stem or "artifact", path)
label, raw_path = value.split("=", 1)
return (label.strip() or "artifact", Path(raw_path))


def render_artifact(label: str, path: Path, max_lines: int) -> str:
exists = path.exists()
out = [f"## {label}", "", f"- Path: `{path}`", f"- Exists: `{str(exists).lower()}`"]
if not exists:
return "\n".join(out) + "\n"

if path.suffix.lower() in TEXT_EXTENSIONS:
out.extend(["", "```text", tail_text(path, max_lines), "```"])
else:
out.extend(["", f"![{label}]({path})"])
return "\n".join(out) + "\n"


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--out", required=True, help="Markdown output path.")
parser.add_argument("--title", default="Helmor Debug Evidence")
parser.add_argument("--status", default="inconclusive")
parser.add_argument("--summary", default="")
parser.add_argument(
"--artifact",
action="append",
default=[],
help="Artifact as label=path, repeatable. Text files are tailed; images are linked.",
)
parser.add_argument("--max-lines", type=int, default=200)
args = parser.parse_args()

parts = [
f"# {args.title}",
"",
f"- Status: `{args.status}`",
]
if args.summary:
parts.extend(["", args.summary])

for value in args.artifact:
label, path = parse_artifact(value)
parts.extend(["", render_artifact(label, path, max(0, args.max_lines)).rstrip()])

out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text("\n".join(parts).rstrip() + "\n")
print(out_path)
return 0


if __name__ == "__main__":
raise SystemExit(main())
110 changes: 110 additions & 0 deletions .agents/skills/helmor-debug-loop/scripts/terminal_log_summary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Summarize Helmor terminal/run-script logs for debugging evidence."""

from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path

ANSI_RE = re.compile(r"\x1b(?:\[[0-9;?=<>]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1b\\)|[@-Z\\-_])")
URL_RE = re.compile(r"https?://(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|::1|[^\s'\"<>]+)[^\s'\"<>]*")
ERROR_RE = re.compile(
r"\b(error|exception|panic|failed|failure|traceback|unhandled|cannot|could not|enoent|eaddrinuse)\b",
re.IGNORECASE,
)
WARNING_RE = re.compile(r"\b(warn|warning|deprecated)\b", re.IGNORECASE)


def read_text(path: str | None) -> str:
if path:
return Path(path).read_text(errors="replace")
return sys.stdin.read()


def strip_ansi(text: str) -> str:
return ANSI_RE.sub("", text)


def unique(values: list[str]) -> list[str]:
seen: set[str] = set()
out: list[str] = []
for value in values:
if value in seen:
continue
seen.add(value)
out.append(value)
return out


def summarize(text: str, tail_lines: int) -> dict[str, object]:
clean = strip_ansi(text).replace("\r\n", "\n").replace("\r", "\n")
lines = clean.splitlines()
error_lines = [line for line in lines if ERROR_RE.search(line)]
warning_lines = [line for line in lines if WARNING_RE.search(line)]
urls = unique(URL_RE.findall(clean))
return {
"bytes": len(text.encode()),
"cleanBytes": len(clean.encode()),
"lineCount": len(lines),
"urls": urls[:20],
"errorCount": len(error_lines),
"warningCount": len(warning_lines),
"errors": error_lines[-20:],
"warnings": warning_lines[-20:],
"tail": lines[-tail_lines:],
}


def print_markdown(summary: dict[str, object]) -> None:
print("# Terminal Log Summary\n")
print(f"- Bytes: {summary['bytes']}")
print(f"- Clean bytes: {summary['cleanBytes']}")
print(f"- Lines: {summary['lineCount']}")
print(f"- Errors: {summary['errorCount']}")
print(f"- Warnings: {summary['warningCount']}")

urls = summary["urls"]
if urls:
print("\n## URLs")
for url in urls:
print(f"- `{url}`")

errors = summary["errors"]
if errors:
print("\n## Recent Error Lines")
for line in errors:
print(f"- `{line[:500]}`")

warnings = summary["warnings"]
if warnings:
print("\n## Recent Warning Lines")
for line in warnings:
print(f"- `{line[:500]}`")

print("\n## Tail")
print("```text")
for line in summary["tail"]:
print(line)
print("```")


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("path", nargs="?", help="Log file path. Reads stdin when omitted.")
parser.add_argument("--tail-lines", type=int, default=120)
parser.add_argument("--json", action="store_true", help="Emit JSON instead of markdown.")
args = parser.parse_args()

summary = summarize(read_text(args.path), max(0, args.tail_lines))
if args.json:
print(json.dumps(summary, ensure_ascii=False, indent=2))
else:
print_markdown(summary)
return 0


if __name__ == "__main__":
raise SystemExit(main())
Loading