@misterhuydo/sentinel 1.0.4 → 1.0.6

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.
package/lib/generate.js CHANGED
@@ -73,7 +73,7 @@ if echo "$AUTH_OUT" | grep -Eqi "not logged in|/login"; then
73
73
  exit 1
74
74
  fi
75
75
 
76
- mkdir -p "$DIR/logs" "$DIR/workspace/fetched" "$DIR/workspace/patches"
76
+ mkdir -p "$DIR/logs" "$DIR/workspace/fetched" "$DIR/workspace/patches" "$DIR/issues"
77
77
  cd "$DIR"
78
78
  PYTHONPATH="${codeDir}" "${pythonBin}" -m sentinel.main --config ./config \\
79
79
  >> "$DIR/logs/sentinel.log" 2>&1 &
@@ -109,17 +109,36 @@ rm -f "$PID_FILE"
109
109
  function generateWorkspaceScripts(workspace) {
110
110
  // startAll.sh
111
111
  fs.writeFileSync(path.join(workspace, 'startAll.sh'), `#!/usr/bin/env bash
112
- # Start all Sentinel project instances
112
+ # Start all valid Sentinel project instances.
113
+ # A valid project must have config/repo-configs/*.properties with a GitHub REPO_URL.
113
114
  WORKSPACE="$(cd "$(dirname "$0")" && pwd)"
114
115
  started=0
116
+ skipped=0
115
117
  for project_dir in "$WORKSPACE"/*/; do
116
118
  name=$(basename "$project_dir")
117
119
  [[ "$name" == "code" ]] && continue
118
120
  [[ -f "$project_dir/start.sh" ]] || continue
121
+
122
+ # Must have at least one repo-config with a valid GitHub REPO_URL
123
+ valid_repo=false
124
+ for props in "$project_dir/config/repo-configs/"*.properties 2>/dev/null; do
125
+ [[ -f "$props" ]] || continue
126
+ if grep -qE "^REPO_URL[[:space:]]*=[[:space:]]*(git@github\.com:|https://github\.com/)" "$props"; then
127
+ valid_repo=true
128
+ break
129
+ fi
130
+ done
131
+
132
+ if [[ "$valid_repo" == "false" ]]; then
133
+ echo "[sentinel] Skipping $name — no valid REPO_URL found in config/repo-configs/"
134
+ skipped=$((skipped + 1))
135
+ continue
136
+ fi
137
+
119
138
  bash "$project_dir/start.sh"
120
139
  started=$((started + 1))
121
140
  done
122
- echo "[sentinel] $started project(s) started"
141
+ echo "[sentinel] $started project(s) started, $skipped skipped"
123
142
  `, { mode: 0o755 });
124
143
 
125
144
  // stopAll.sh
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@misterhuydo/sentinel",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "Sentinel — Autonomous DevOps Agent installer and manager",
5
5
  "bin": {
6
6
  "sentinel": "./bin/sentinel.js"
@@ -41,8 +41,9 @@ class SentinelConfig:
41
41
  smtp_port: int = 587
42
42
  smtp_user: str = ""
43
43
  smtp_password: str = ""
44
- report_recipients: list[str] = field(default_factory=list)
44
+ mails: list[str] = field(default_factory=list)
45
45
  report_interval_hours: int = 6
46
+ send_health: bool = False
46
47
  state_db: str = "./sentinel.db"
47
48
  workspace_dir: str = "./workspace"
48
49
  claude_code_bin: str = "claude"
@@ -114,8 +115,9 @@ class ConfigLoader:
114
115
  c.smtp_port = int(d.get("SMTP_PORT", 587))
115
116
  c.smtp_user = d.get("SMTP_USER", "")
116
117
  c.smtp_password = d.get("SMTP_PASSWORD", "")
117
- c.report_recipients = _csv(d.get("REPORT_RECIPIENTS", ""))
118
+ c.mails = _csv(d.get("MAILS", ""))
118
119
  c.report_interval_hours = int(d.get("REPORT_INTERVAL_HOURS", 6))
120
+ c.send_health = d.get("SEND_HEALTH", "disabled").lower() == "enabled"
119
121
  c.state_db = d.get("STATE_DB", "./sentinel.db")
120
122
  c.workspace_dir = d.get("WORKSPACE_DIR", "./workspace")
121
123
  c.claude_code_bin = d.get("CLAUDE_CODE_BIN", "claude")
@@ -26,36 +26,39 @@ _DIFF_BLOCK = re.compile(r"```(?:diff|patch)?\n(.*?)```", re.DOTALL)
26
26
  _DIFF_HEADER = re.compile(r"^diff --git|^---\s+\S+|^\+\+\+\s+\S+", re.MULTILINE)
27
27
 
28
28
 
29
- def _build_prompt(event: ErrorEvent, repo: RepoConfig, log_file: Path) -> str:
30
- return textwrap.dedent(f"""\
31
- You are fixing a production bug in the repository at {repo.local_path}.
32
- Repository: {repo.repo_name}
33
-
34
- LOG FILE: {log_file}
35
- Read this file first. It contains the last 48h of logs from {event.source} —
36
- use it to understand the frequency, surrounding context, and any warnings
37
- that preceded this error.
38
-
39
- ERROR fingerprint to fix (from {event.source}):
40
- {event.full_text()}
41
-
42
- Task:
43
- 1. Read the log file above to understand what led up to this error.
44
- 2. Use your available tools to explore the codebase and identify the root cause.
45
- 3. Output ONLY a unified diff patch (git diff format) fixing the issue.
46
- 4. Do not explain. Output only the patch.
47
- 5. If you cannot determine a safe fix, output: SKIP: <reason>
48
- """)
49
-
50
-
51
- def _extract_patch(output: str) -> str | None:
52
- m = _DIFF_BLOCK.search(output)
53
- if m:
54
- return m.group(1).strip()
55
- if _DIFF_HEADER.search(output):
56
- return output.strip()
57
- return None
58
-
29
+ def _build_prompt(event, repo: RepoConfig, log_file) -> str:
30
+ if log_file and log_file.exists():
31
+ ctx = (
32
+ "LOG FILE: " + str(log_file) + "\n"
33
+ "Read this file first -- it contains the last 48h of logs from "
34
+ + event.source + ".\n"
35
+ "Use it to understand frequency, context, and preceding warnings."
36
+ )
37
+ step1 = "Read the log file above to understand what led up to this error."
38
+ else:
39
+ ctx = (
40
+ "SOURCE: " + event.source + "\n"
41
+ "No rolling log file available. The full issue description is below."
42
+ )
43
+ step1 = "Use the issue description above as your primary context."
44
+
45
+ lines_out = [
46
+ f"You are fixing a production bug in the repository at {repo.local_path}.",
47
+ f"Repository: {repo.repo_name}",
48
+ "",
49
+ ctx,
50
+ "",
51
+ f"ISSUE TO FIX (from {event.source}):",
52
+ event.full_text(),
53
+ "",
54
+ "Task:",
55
+ f"1. {step1}",
56
+ "2. Use your available tools to explore the codebase and identify the root cause.",
57
+ "3. Output ONLY a unified diff patch (git diff format) fixing the issue.",
58
+ "4. Do not explain. Output only the patch.",
59
+ "5. If you cannot determine a safe fix, output: SKIP: <reason>",
60
+ ]
61
+ return "\n".join(lines_out)
59
62
 
60
63
  def _validate_patch(patch: str) -> tuple[bool, str]:
61
64
  files_changed = len(re.findall(r"^diff --git", patch, re.MULTILINE))
@@ -83,7 +86,10 @@ def generate_fix(
83
86
  (status, patch_path)
84
87
  status: "patch" | "skip" | "error"
85
88
  """
89
+ # Issues have source like "issues/filename" — no rolling log file exists
86
90
  log_file = Path(cfg.workspace_dir) / "fetched" / f"{event.source}.log"
91
+ if not log_file.exists():
92
+ log_file = None
87
93
  prompt = _build_prompt(event, repo, log_file)
88
94
 
89
95
  logger.info("Invoking Claude Code for %s (fp=%s)", event.source, event.fingerprint)
@@ -0,0 +1,131 @@
1
+ """
2
+ issue_watcher.py — Scan the issues/ directory for manually-submitted bug reports.
3
+
4
+ Admins drop plain-text or markdown files into <project>/issues/.
5
+ Each file is treated as a fix request. Processed files are archived to issues/.done/.
6
+
7
+ File format (TARGET_REPO header is optional):
8
+
9
+ TARGET_REPO: my-repo-name
10
+
11
+ Short summary of the problem (becomes the email subject line)
12
+
13
+ Any details: customer feedback, stack traces, screenshots text, etc.
14
+ If TARGET_REPO is omitted and only one repo is configured, it is used automatically.
15
+ """
16
+
17
+ import hashlib
18
+ import logging
19
+ import time
20
+ from dataclasses import dataclass, field
21
+ from datetime import datetime, timezone
22
+ from pathlib import Path
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ _TARGET_REPO_PREFIX = "TARGET_REPO:"
27
+
28
+
29
+ @dataclass
30
+ class IssueEvent:
31
+ """
32
+ A fix request sourced from the issues/ directory.
33
+ Implements the same interface as ErrorEvent so it can flow through
34
+ the same fix pipeline (_handle_error / generate_fix / git_manager).
35
+ """
36
+ source: str # "issues/<filename>" — shown in emails and logs
37
+ issue_file: Path # full path, used for archiving after processing
38
+ message: str # first non-blank body line — used as subject summary
39
+ body: str # full file content (the issue description)
40
+ target_repo: str # explicit TARGET_REPO value, or "" for auto-select
41
+ fingerprint: str = ""
42
+ severity: str = "ERROR"
43
+ timestamp: str = ""
44
+
45
+ # Compatibility fields matching ErrorEvent interface
46
+ level: str = "ERROR"
47
+ thread: str = ""
48
+ logger_name: str = ""
49
+ stack_trace: list[str] = field(default_factory=list)
50
+ log_file: str = ""
51
+
52
+ def __post_init__(self):
53
+ if not self.fingerprint:
54
+ raw = f"issue:{self.source}:{self.message[:200]}"
55
+ self.fingerprint = hashlib.sha1(raw.encode()).hexdigest()[:16]
56
+ if not self.timestamp:
57
+ self.timestamp = datetime.now(timezone.utc).isoformat()
58
+ if not self.stack_trace:
59
+ self.stack_trace = self.body.splitlines()
60
+
61
+ @property
62
+ def is_infra_issue(self) -> bool:
63
+ return False
64
+
65
+ def short_summary(self) -> str:
66
+ return self.message[:120]
67
+
68
+ def full_text(self) -> str:
69
+ return self.body
70
+
71
+
72
+ def scan_issues(project_dir: Path) -> list[IssueEvent]:
73
+ """
74
+ Return all pending issue files from <project_dir>/issues/.
75
+ Files starting with '.' and files inside .done/ are skipped.
76
+ """
77
+ issues_dir = project_dir / "issues"
78
+ if not issues_dir.exists():
79
+ return []
80
+
81
+ events = []
82
+ for f in sorted(issues_dir.iterdir()):
83
+ if not f.is_file() or f.name.startswith("."):
84
+ continue
85
+
86
+ try:
87
+ content = f.read_text(encoding="utf-8", errors="replace").strip()
88
+ except OSError as e:
89
+ logger.error("Cannot read issue file %s: %s", f, e)
90
+ continue
91
+
92
+ if not content:
93
+ continue
94
+
95
+ lines = content.splitlines()
96
+ target_repo = ""
97
+ body_start = 0
98
+
99
+ # Parse optional TARGET_REPO: header (must be the first non-blank line)
100
+ for i, line in enumerate(lines):
101
+ stripped = line.strip()
102
+ if stripped.upper().startswith(_TARGET_REPO_PREFIX):
103
+ target_repo = stripped[len(_TARGET_REPO_PREFIX):].strip()
104
+ body_start = i + 1
105
+ elif stripped:
106
+ break
107
+
108
+ body = "\n".join(lines[body_start:]).strip() or content
109
+ message = next((l.strip() for l in lines[body_start:] if l.strip()), f.name)
110
+
111
+ events.append(IssueEvent(
112
+ source=f"issues/{f.name}",
113
+ issue_file=f,
114
+ message=message,
115
+ body=body,
116
+ target_repo=target_repo,
117
+ ))
118
+ logger.info("Found issue: %s (target_repo=%r)", f.name, target_repo or "auto")
119
+
120
+ return events
121
+
122
+
123
+ def mark_done(issue_file: Path) -> None:
124
+ """Archive a processed issue to issues/.done/ regardless of outcome."""
125
+ done_dir = issue_file.parent / ".done"
126
+ done_dir.mkdir(exist_ok=True)
127
+ dest = done_dir / issue_file.name
128
+ if dest.exists():
129
+ dest = done_dir / f"{issue_file.stem}-{int(time.time())}{issue_file.suffix}"
130
+ issue_file.rename(dest)
131
+ logger.info("Issue archived: %s -> .done/%s", issue_file.name, dest.name)