marmonitor 0.1.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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -0
  3. package/bin/marmonitor.js +2 -0
  4. package/dist/banner/index.d.ts +7 -0
  5. package/dist/banner/index.js +212 -0
  6. package/dist/cli.d.ts +1 -0
  7. package/dist/cli.js +855 -0
  8. package/dist/config/index.d.ts +105 -0
  9. package/dist/config/index.js +218 -0
  10. package/dist/guard/index.d.ts +23 -0
  11. package/dist/guard/index.js +128 -0
  12. package/dist/output/index.d.ts +28 -0
  13. package/dist/output/index.js +457 -0
  14. package/dist/output/utils.d.ts +138 -0
  15. package/dist/output/utils.js +588 -0
  16. package/dist/process-safety.d.ts +2 -0
  17. package/dist/process-safety.js +7 -0
  18. package/dist/scanner/bounded-map.d.ts +10 -0
  19. package/dist/scanner/bounded-map.js +25 -0
  20. package/dist/scanner/cache.d.ts +88 -0
  21. package/dist/scanner/cache.js +32 -0
  22. package/dist/scanner/claude.d.ts +25 -0
  23. package/dist/scanner/claude.js +425 -0
  24. package/dist/scanner/codex.d.ts +14 -0
  25. package/dist/scanner/codex.js +195 -0
  26. package/dist/scanner/gemini.d.ts +21 -0
  27. package/dist/scanner/gemini.js +131 -0
  28. package/dist/scanner/group.d.ts +7 -0
  29. package/dist/scanner/group.js +54 -0
  30. package/dist/scanner/index.d.ts +16 -0
  31. package/dist/scanner/index.js +256 -0
  32. package/dist/scanner/process.d.ts +17 -0
  33. package/dist/scanner/process.js +91 -0
  34. package/dist/scanner/status.d.ts +8 -0
  35. package/dist/scanner/status.js +45 -0
  36. package/dist/scanner/types.d.ts +6 -0
  37. package/dist/scanner/types.js +4 -0
  38. package/dist/tmux/index.d.ts +34 -0
  39. package/dist/tmux/index.js +166 -0
  40. package/dist/types.d.ts +55 -0
  41. package/dist/types.js +1 -0
  42. package/dist/version.d.ts +1 -0
  43. package/dist/version.js +1 -0
  44. package/docs/banner-ansi.png +0 -0
  45. package/docs/marmot-small.png +0 -0
  46. package/package.json +70 -0
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Configuration loader for marmonitor.
3
+ * Loads settings from XDG-compliant paths with fallback.
4
+ *
5
+ * Priority:
6
+ * 1. $XDG_CONFIG_HOME/marmonitor/settings.json
7
+ * 2. ~/.config/marmonitor/settings.json
8
+ * 3. ~/.marmonitor.json (legacy fallback, read-only)
9
+ */
10
+ /** Full config shape with all fields required (after merge with defaults) */
11
+ export interface MarmonitorConfig {
12
+ status: {
13
+ activeCpuThreshold: number;
14
+ stalledAfterMin: number;
15
+ minMemoryMb: number;
16
+ phaseDecay: {
17
+ thinking: number;
18
+ tool: number;
19
+ permission: number;
20
+ done: number;
21
+ };
22
+ stdoutHeuristic: {
23
+ approvalPatterns: string[];
24
+ clearPatterns: string[];
25
+ };
26
+ };
27
+ display: {
28
+ showDead: boolean;
29
+ sortBy: "cwd" | "agent" | "status" | "pid";
30
+ attentionLimit: number;
31
+ statuslineAttentionLimit: number;
32
+ };
33
+ agents: Record<string, {
34
+ processNames: string[];
35
+ }>;
36
+ intervention: {
37
+ enabled: boolean;
38
+ mode: "alert" | "hold" | "block";
39
+ requireConfirmation: boolean;
40
+ defaultAction: "ignore" | "alert" | "hold" | "block";
41
+ rules: Array<{
42
+ id: string;
43
+ enabled: boolean;
44
+ trigger: string;
45
+ action?: "ignore" | "alert" | "hold" | "block";
46
+ agents?: Array<"claude" | "codex" | "gemini">;
47
+ runtimeSources?: Array<"cli" | "vscode" | "unknown">;
48
+ severity?: "low" | "medium" | "high" | "critical";
49
+ match?: {
50
+ commandRegex?: string;
51
+ cwdPrefix?: string;
52
+ toolNames?: string[];
53
+ };
54
+ note?: string;
55
+ }>;
56
+ };
57
+ integration: {
58
+ tmux: {
59
+ keys: {
60
+ attentionPopup: string;
61
+ jumpPopup: string;
62
+ dockToggle: string;
63
+ directJump: string[];
64
+ };
65
+ };
66
+ wezterm: {
67
+ enabled: boolean;
68
+ statusTtlSec: number;
69
+ };
70
+ banner: {
71
+ install: boolean;
72
+ runtime: boolean;
73
+ };
74
+ };
75
+ paths: {
76
+ claudeProjects: string[];
77
+ claudeSessions: string[];
78
+ codexSessions: string[];
79
+ extraRoots: string[];
80
+ };
81
+ performance: {
82
+ snapshotTtlMs: number;
83
+ statuslineTtlMs: number;
84
+ stdoutHeuristicTtlMs: number;
85
+ };
86
+ }
87
+ /** Get config search paths in priority order */
88
+ export declare function getConfigSearchPaths(): string[];
89
+ /** Load config, merging user overrides onto defaults */
90
+ export declare function loadConfig(customPath?: string): Promise<MarmonitorConfig>;
91
+ /** Get default config (no file I/O) */
92
+ export declare function getDefaults(): MarmonitorConfig;
93
+ /** Get the expected config directory path (for init/display) */
94
+ export declare function getConfigDir(): string;
95
+ /** Get the default writable settings path */
96
+ export declare function getDefaultConfigPath(): string;
97
+ /** Resolve the config path that would actually be used */
98
+ export declare function resolveConfigPath(customPath?: string): string | undefined;
99
+ export interface RuntimeDataPaths {
100
+ claudeProjects: string[];
101
+ claudeSessions: string[];
102
+ codexSessions: string[];
103
+ extraRoots: string[];
104
+ }
105
+ export declare function resolveRuntimeDataPaths(config: MarmonitorConfig): RuntimeDataPaths;
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Configuration loader for marmonitor.
3
+ * Loads settings from XDG-compliant paths with fallback.
4
+ *
5
+ * Priority:
6
+ * 1. $XDG_CONFIG_HOME/marmonitor/settings.json
7
+ * 2. ~/.config/marmonitor/settings.json
8
+ * 3. ~/.marmonitor.json (legacy fallback, read-only)
9
+ */
10
+ import { existsSync } from "node:fs";
11
+ import { readFile } from "node:fs/promises";
12
+ import { homedir } from "node:os";
13
+ import { delimiter, join } from "node:path";
14
+ const DEFAULTS = {
15
+ status: {
16
+ activeCpuThreshold: 0.5,
17
+ stalledAfterMin: 30,
18
+ minMemoryMb: 5,
19
+ phaseDecay: {
20
+ thinking: 20,
21
+ tool: 30,
22
+ permission: 0,
23
+ done: 5,
24
+ },
25
+ stdoutHeuristic: {
26
+ approvalPatterns: [
27
+ "would you like to",
28
+ "approve this",
29
+ "approve the following",
30
+ "confirm",
31
+ "confirmation required",
32
+ "action required",
33
+ "allow execution of:",
34
+ ],
35
+ clearPatterns: [
36
+ "reading files",
37
+ "applying patch",
38
+ "running tests",
39
+ "running command",
40
+ "edited",
41
+ "changes applied",
42
+ ],
43
+ },
44
+ },
45
+ display: {
46
+ showDead: false,
47
+ sortBy: "cwd",
48
+ attentionLimit: 10,
49
+ statuslineAttentionLimit: 5,
50
+ },
51
+ agents: {
52
+ "Claude Code": { processNames: ["claude"] },
53
+ Codex: { processNames: ["codex"] },
54
+ Gemini: { processNames: ["gemini"] },
55
+ },
56
+ intervention: {
57
+ enabled: false,
58
+ mode: "alert",
59
+ requireConfirmation: true,
60
+ defaultAction: "alert",
61
+ rules: [],
62
+ },
63
+ integration: {
64
+ tmux: {
65
+ keys: {
66
+ attentionPopup: "a",
67
+ jumpPopup: "j",
68
+ dockToggle: "m",
69
+ directJump: ["M-1", "M-2", "M-3", "M-4", "M-5"],
70
+ },
71
+ },
72
+ wezterm: {
73
+ enabled: false,
74
+ statusTtlSec: 15,
75
+ },
76
+ banner: {
77
+ install: true,
78
+ runtime: false,
79
+ },
80
+ },
81
+ paths: {
82
+ claudeProjects: [],
83
+ claudeSessions: [],
84
+ codexSessions: [],
85
+ extraRoots: [],
86
+ },
87
+ performance: {
88
+ snapshotTtlMs: 5000,
89
+ statuslineTtlMs: 5000,
90
+ stdoutHeuristicTtlMs: 5000,
91
+ },
92
+ };
93
+ function cloneDefaults() {
94
+ return JSON.parse(JSON.stringify(DEFAULTS));
95
+ }
96
+ /** Get config search paths in priority order */
97
+ export function getConfigSearchPaths() {
98
+ const home = homedir();
99
+ const xdgHome = process.env.XDG_CONFIG_HOME ?? join(home, ".config");
100
+ return [join(xdgHome, "marmonitor", "settings.json"), join(home, ".marmonitor.json")];
101
+ }
102
+ /** Find the config file path (first existing one wins) */
103
+ function findConfigPath() {
104
+ const candidates = getConfigSearchPaths();
105
+ for (const p of candidates) {
106
+ if (existsSync(p))
107
+ return p;
108
+ }
109
+ return undefined;
110
+ }
111
+ function isJsonObject(value) {
112
+ return value !== null && typeof value === "object" && !Array.isArray(value);
113
+ }
114
+ /** Deep merge user config onto defaults */
115
+ function deepMerge(defaults, overrides) {
116
+ const result = { ...defaults };
117
+ for (const key of Object.keys(overrides)) {
118
+ const val = overrides[key];
119
+ const defaultVal = defaults[key];
120
+ if (isJsonObject(val) && isJsonObject(defaultVal)) {
121
+ result[key] = deepMerge(defaultVal, val);
122
+ }
123
+ else {
124
+ result[key] = val;
125
+ }
126
+ }
127
+ return result;
128
+ }
129
+ /** Load config, merging user overrides onto defaults */
130
+ export async function loadConfig(customPath) {
131
+ const configPath = customPath ?? findConfigPath();
132
+ if (!configPath)
133
+ return cloneDefaults();
134
+ try {
135
+ const raw = await readFile(configPath, "utf-8");
136
+ const userConfig = JSON.parse(raw);
137
+ if (!isJsonObject(userConfig))
138
+ return cloneDefaults();
139
+ return deepMerge(cloneDefaults(), userConfig);
140
+ }
141
+ catch {
142
+ // Malformed or unreadable config — use defaults silently
143
+ return cloneDefaults();
144
+ }
145
+ }
146
+ /** Get default config (no file I/O) */
147
+ export function getDefaults() {
148
+ return cloneDefaults();
149
+ }
150
+ /** Get the expected config directory path (for init/display) */
151
+ export function getConfigDir() {
152
+ const xdgHome = process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
153
+ return join(xdgHome, "marmonitor");
154
+ }
155
+ /** Get the default writable settings path */
156
+ export function getDefaultConfigPath() {
157
+ return join(getConfigDir(), "settings.json");
158
+ }
159
+ /** Resolve the config path that would actually be used */
160
+ export function resolveConfigPath(customPath) {
161
+ return customPath ?? findConfigPath();
162
+ }
163
+ function expandUserPath(value) {
164
+ if (value === "~")
165
+ return homedir();
166
+ if (value.startsWith("~/"))
167
+ return join(homedir(), value.slice(2));
168
+ return value;
169
+ }
170
+ function parsePathList(value) {
171
+ if (!value)
172
+ return [];
173
+ return value
174
+ .split(delimiter)
175
+ .map((item) => item.trim())
176
+ .filter(Boolean)
177
+ .map(expandUserPath);
178
+ }
179
+ function uniquePaths(values) {
180
+ const seen = new Set();
181
+ const result = [];
182
+ for (const value of values.map(expandUserPath)) {
183
+ if (seen.has(value))
184
+ continue;
185
+ seen.add(value);
186
+ result.push(value);
187
+ }
188
+ return result;
189
+ }
190
+ export function resolveRuntimeDataPaths(config) {
191
+ const claudeHome = process.env.MARMONITOR_CLAUDE_HOME
192
+ ? expandUserPath(process.env.MARMONITOR_CLAUDE_HOME)
193
+ : undefined;
194
+ const codexHome = process.env.MARMONITOR_CODEX_HOME
195
+ ? expandUserPath(process.env.MARMONITOR_CODEX_HOME)
196
+ : undefined;
197
+ return {
198
+ claudeProjects: uniquePaths([
199
+ ...parsePathList(process.env.MARMONITOR_CLAUDE_PROJECTS),
200
+ ...config.paths.claudeProjects,
201
+ ...(claudeHome ? [join(claudeHome, "projects")] : []),
202
+ join(homedir(), ".claude", "projects"),
203
+ ]),
204
+ claudeSessions: uniquePaths([
205
+ ...parsePathList(process.env.MARMONITOR_CLAUDE_SESSIONS),
206
+ ...config.paths.claudeSessions,
207
+ ...(claudeHome ? [join(claudeHome, "sessions")] : []),
208
+ join(homedir(), ".claude", "sessions"),
209
+ ]),
210
+ codexSessions: uniquePaths([
211
+ ...parsePathList(process.env.MARMONITOR_CODEX_SESSIONS),
212
+ ...config.paths.codexSessions,
213
+ ...(codexHome ? [join(codexHome, "sessions")] : []),
214
+ join(homedir(), ".codex", "sessions"),
215
+ ]),
216
+ extraRoots: uniquePaths(config.paths.extraRoots),
217
+ };
218
+ }
@@ -0,0 +1,23 @@
1
+ import type { MarmonitorConfig } from "../config/index.js";
2
+ export type GuardAction = "ignore" | "alert" | "hold" | "block";
3
+ export type GuardTrigger = "dangerous_command" | "prod_path_access" | "secret_access" | "out_of_cwd_write";
4
+ export interface HookEvent {
5
+ agent: "claude";
6
+ toolName?: string;
7
+ cwd?: string;
8
+ command?: string;
9
+ filePath?: string;
10
+ raw: unknown;
11
+ }
12
+ export interface GuardDecision {
13
+ decision: "allow" | "block";
14
+ message?: string;
15
+ matchedRuleId?: string;
16
+ trigger?: GuardTrigger;
17
+ action?: GuardAction;
18
+ }
19
+ export declare function parseHookEvent(input: string): HookEvent | undefined;
20
+ export declare function detectGuardTriggers(event: HookEvent): GuardTrigger[];
21
+ export declare function evaluateGuard(config: MarmonitorConfig, event: HookEvent): GuardDecision;
22
+ export declare function readStdin(): Promise<string>;
23
+ export declare function formatGuardOutput(result: GuardDecision): string;
@@ -0,0 +1,128 @@
1
+ import { readFile } from "node:fs/promises";
2
+ const DANGEROUS_COMMAND_PATTERNS = [/\brm\s+-rf\s+\//, /\bmkfs\b/, /\bdd\s+if=.*\sof=\/dev\//];
3
+ const SECRET_PATH_PATTERNS = [/\.env\b/, /\/secrets?\b/, /\/\.ssh\b/, /id_rsa\b/];
4
+ const PROD_PATH_PATTERNS = [/\/prod\b/, /\/production\b/, /prod/i];
5
+ function normalizeAction(action) {
6
+ if (action === "block")
7
+ return "block";
8
+ return "allow";
9
+ }
10
+ export function parseHookEvent(input) {
11
+ try {
12
+ const raw = JSON.parse(input);
13
+ const toolName = typeof raw.tool_name === "string"
14
+ ? raw.tool_name
15
+ : typeof raw.toolName === "string"
16
+ ? raw.toolName
17
+ : undefined;
18
+ const toolInput = raw.tool_input && typeof raw.tool_input === "object"
19
+ ? raw.tool_input
20
+ : raw.toolInput && typeof raw.toolInput === "object"
21
+ ? raw.toolInput
22
+ : undefined;
23
+ return {
24
+ agent: "claude",
25
+ toolName,
26
+ cwd: typeof raw.cwd === "string" ? raw.cwd : undefined,
27
+ command: typeof toolInput?.command === "string" ? toolInput.command : undefined,
28
+ filePath: typeof toolInput?.file_path === "string"
29
+ ? toolInput.file_path
30
+ : typeof toolInput?.path === "string"
31
+ ? toolInput.path
32
+ : undefined,
33
+ raw,
34
+ };
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
40
+ export function detectGuardTriggers(event) {
41
+ const triggers = new Set();
42
+ const command = event.command ?? "";
43
+ const filePath = event.filePath ?? "";
44
+ const cwd = event.cwd ?? "";
45
+ if (DANGEROUS_COMMAND_PATTERNS.some((pattern) => pattern.test(command))) {
46
+ triggers.add("dangerous_command");
47
+ }
48
+ if (PROD_PATH_PATTERNS.some((pattern) => pattern.test(command) || pattern.test(filePath))) {
49
+ triggers.add("prod_path_access");
50
+ }
51
+ if (SECRET_PATH_PATTERNS.some((pattern) => pattern.test(command) || pattern.test(filePath))) {
52
+ triggers.add("secret_access");
53
+ }
54
+ if (filePath && cwd && !filePath.startsWith(cwd)) {
55
+ triggers.add("out_of_cwd_write");
56
+ }
57
+ return [...triggers];
58
+ }
59
+ function ruleMatches(rule, event, trigger) {
60
+ if (!rule.enabled)
61
+ return false;
62
+ if (rule.trigger !== trigger)
63
+ return false;
64
+ if (rule.agents && !rule.agents.includes(event.agent))
65
+ return false;
66
+ if (rule.match?.toolNames && event.toolName && !rule.match.toolNames.includes(event.toolName)) {
67
+ return false;
68
+ }
69
+ if (rule.match?.cwdPrefix && event.cwd && !event.cwd.startsWith(rule.match.cwdPrefix)) {
70
+ return false;
71
+ }
72
+ if (rule.match?.commandRegex) {
73
+ const command = event.command ?? "";
74
+ try {
75
+ if (!new RegExp(rule.match.commandRegex).test(command))
76
+ return false;
77
+ }
78
+ catch {
79
+ return false;
80
+ }
81
+ }
82
+ return true;
83
+ }
84
+ export function evaluateGuard(config, event) {
85
+ if (!config.intervention.enabled) {
86
+ return { decision: "allow" };
87
+ }
88
+ const triggers = detectGuardTriggers(event);
89
+ if (triggers.length === 0) {
90
+ return { decision: "allow" };
91
+ }
92
+ for (const trigger of triggers) {
93
+ const matchedRule = config.intervention.rules.find((rule) => ruleMatches(rule, event, trigger));
94
+ if (!matchedRule)
95
+ continue;
96
+ const action = matchedRule.action ?? config.intervention.defaultAction;
97
+ const decision = normalizeAction(action);
98
+ return {
99
+ decision,
100
+ matchedRuleId: matchedRule.id,
101
+ trigger,
102
+ action,
103
+ message: decision === "block"
104
+ ? `Blocked by marmonitor: ${trigger}${matchedRule.id ? ` (${matchedRule.id})` : ""}`
105
+ : undefined,
106
+ };
107
+ }
108
+ const action = config.intervention.defaultAction;
109
+ const decision = normalizeAction(action);
110
+ return {
111
+ decision,
112
+ trigger: triggers[0],
113
+ action,
114
+ message: decision === "block" ? `Blocked by marmonitor: ${triggers[0]}` : undefined,
115
+ };
116
+ }
117
+ export async function readStdin() {
118
+ return readFile("/dev/stdin", "utf8");
119
+ }
120
+ export function formatGuardOutput(result) {
121
+ if (result.decision === "block") {
122
+ return JSON.stringify({
123
+ decision: "block",
124
+ message: result.message ?? "Blocked by marmonitor",
125
+ });
126
+ }
127
+ return JSON.stringify({ decision: "allow" });
128
+ }
@@ -0,0 +1,28 @@
1
+ import type { TmuxJumpResult } from "../tmux/index.js";
2
+ import type { AgentSession, SystemInfo } from "../types.js";
3
+ import { type StatuslineFormat } from "./utils.js";
4
+ /** Collect system resource info */
5
+ export declare function getSystemInfo(): Promise<SystemInfo>;
6
+ /** Print agent status as formatted text */
7
+ export declare function printStatus(agents: AgentSession[]): Promise<void>;
8
+ /** Print agent status as JSON */
9
+ export declare function printStatusJson(agents: AgentSession[]): Promise<void>;
10
+ export declare function printCleanPlan(agents: AgentSession[], kill: boolean): void;
11
+ export declare function printCleanJson(agents: AgentSession[], executed: boolean, signal?: string): void;
12
+ export declare function printAttention(agents: AgentSession[], limit?: number): void;
13
+ export declare function printAttentionJson(agents: AgentSession[], limit?: number): void;
14
+ export declare function printAttentionChooser(agents: AgentSession[], limit?: number): void;
15
+ export declare function printJumpAttentionChooser(agents: AgentSession[], limit?: number): void;
16
+ export declare function printJumpResult(result: TmuxJumpResult): void;
17
+ export declare function printJumpJson(result: TmuxJumpResult): void;
18
+ /**
19
+ * Print compact dock view for tmux side/bottom pane.
20
+ * Prioritizes attention signals over completeness.
21
+ */
22
+ export declare function printDock(agents: AgentSession[], maxLines?: number): Promise<void>;
23
+ /** Print one-line summary for tmux/terminal status bar */
24
+ export declare function renderUnavailableStatusline(format?: StatuslineFormat): string;
25
+ /** Print one-line summary for tmux/terminal status bar */
26
+ export declare function renderStatusline(agents: AgentSession[], format?: StatuslineFormat, attentionLimit?: number, width?: number): Promise<string>;
27
+ /** Print one-line summary for tmux/terminal status bar */
28
+ export declare function printStatusline(agents: AgentSession[], format?: StatuslineFormat, attentionLimit?: number, width?: number): Promise<void>;