Commit Graph
45 Commits
Author SHA1 Message Date
Codeman maintainer f6a30d7335 fix(subagent-watcher): discover workflow-nested agents + harden meta→transcript upgrade
Two follow-ups to db93491 (the 2026-06 CC meta.json format change), after
reverse-engineering the new on-disk layout with a live current-CC subagent +
1Hz fs poller:

(1) Workflow recursion — the Workflow tool nests its agents at
    subagents/workflows/{wf}/agent-{id}.jsonl, one level below the flat
    subagents/ scan, so they were never tracked. Add watchWorkflowDirs()
    (driven from scanForSubagents) to descend and watch each workflow dir
    (idempotent; fs.watch recursive is unsupported on Linux, so the ~5s
    periodic scan re-drives it — same latency as new-session discovery).
    Require the `agent-` prefix in the flat readdir + watch callback so a
    workflow dir's sibling journal.jsonl can't register a bogus "journal" agent.
    E2E verified against real ~/.claude/projects: 32 workflow-nested agents
    discovered (wf_fa35c1d8-4a9), 0 bogus journal agents.

(2) Transcript timing — empirically the per-agent .jsonl IS written at the
    standard subagents/ path and grows incrementally (tailable); the
    /tmp/.../tasks/<id>.output the prior probe found is just a symlink back to
    it. meta.json lands at spawn, the .jsonl a beat later. Add a meta→transcript
    upgrade in registerAgentFile: when an agent registered meta-only gets its
    sibling .jsonl, re-point filePath, drop the stale sidecar context, start
    tailing, and emit subagent:updated (not a duplicate discovered). Corrects the
    now-inaccurate "no transcript to tail" doc comment on registerAgentMeta.

Tests: 2 new cases (workflow-nested discovery; journal.jsonl not registered).
All 56 pass; tsc/lint/format clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 01:43:15 +02:00
Codeman maintainer db93491dd1 fix(subagent-watcher): discover subagents via agent-*.meta.json (CC format change)
Claude Code changed its subagent on-disk format (~2026-06-14): TUI Task
subagents now write `agent-{id}.meta.json` ({agentType,description,toolUseId})
into the session's `subagents/` dir and no longer reliably write a per-agent
`agent-{id}.jsonl` transcript there. The watcher discovered agents ONLY by
`.jsonl`, so it tracked zero — subagent windows and the monitor's "N TRACKED"
showed nothing.

- Add `registerAgentMeta()`: discover from the meta sidecar (description from
  meta.description/agentType), prefer a sibling `.jsonl` transcript when present
  (richer), never tail a meta file.
- Initial scan + directory watcher now handle `.meta.json` alongside `.jsonl`.
- Tests: 2 new cases (meta-only discovery; prefer-.jsonl-when-present).
  Verified e2e against a real ~/.claude/projects fixture.

Known follow-ups (not in scope): meta-only agents have no per-agent transcript
to tail (no live tool-call feed, status stays 'active'); workflow agents under
`subagents/workflows/{wf}/agent-*.jsonl` are still missed by the flat scan.

Also adds the README screenshot tooling used to surface this:
- capture-real-overview.mjs: DSF=2 + ?nowebgl crisp path (DOM renderer avoids
  the WebGL glyph-doubling at deviceScaleFactor>1).
- capture-readme-real.mjs: real-instance desktop-scene capture (dashboard/
  monitor/subagent) for an isolated beta seeded from prod settings.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 01:24:30 +02:00
arkonandClaude Opus 4.7 02e2f3e8b5 refactor: remove dead code and narrow internal exports (knip sweep)
Knip-driven cleanup. All changes verified with tsc --noEmit, lint, and
build.

Removed (zero consumers):
- VERIFICATION_PROMPT constant + its barrel re-export
- createInitialOrchestratorPersistState factory
- transcriptWatcher singleton export
- createAnsiPatternFull / createAnsiPatternSimple factories
- TimerInfo interface + unused AiCheckResult/AiPlanCheckResult imports
  in respawn-controller.ts
- 35 unused Zod z.infer \`*Input\` types in schemas.ts
- Dead re-exports: SessionMode from session.ts, AuthSessionRecord from
  web/ports/index.ts, EnhancedPlanTask/CheckpointReview from
  ralph-tracker.ts, 7 unused entries in utils/index.ts
- 14 event/config interfaces that lived only as JSDoc hints (no TS type
  position usage): Session/Respawn/RalphLoop/RalphTracker/
  SessionManager/SessionAutoOps/Subagent/TaskQueue/TaskTracker/
  TranscriptWatcher/Image/OrchestratorLoop Events + RespawnPreset +
  SessionOutput

Narrowed to module scope (kept but no longer exported):
- buildPermissionArgs in session-cli-builder.ts
- 28 type/interface declarations used only within their own file:
  Ai{Idle,Plan}Check{Config,State}, BashToolParser{Events,Config},
  FileStream/CreateStream{Options,Result}, PlanSubagentEvent,
  SubagentCallback, RalphLoopConfig, RalphLoop{Events,Options},
  ActiveTimerInfo, DetectionStatus, ActionLogEntry, AutoOpsCallbacks,
  TunnelStatus, Timer/LRUMap/StaleExpirationMap Options, AuthState,
  SessionListenerDeps, SseStreamManagerDeps, and 8 more

Docs: CLAUDE.md advice for global-regex `lastIndex` now points to the
remaining `execPattern()` helper instead of the deleted factories.

Knip delta: unused files 42→0, unused exports 161→16, unused types 92→0.
The 16 remaining exports are a mobile-test helper toolkit intentionally
kept for upcoming tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 11:57:00 +02:00
arkonandClaude Opus 4.6 28537de39d refactor: pass 3 — extract helpers, split long functions, deduplicate patterns
Backend:
- subagent-watcher: split 176L processEntry() into 5 focused methods; extract
  _resolveDescription() deduplicating 3 call sites for description acquisition
- bash-tool-parser: split 152L processCleanLine() into 4 handlers; extract
  _createActiveTool() factory and _scheduleAutoRemove() helper
- session: extract _setupOrAttachMuxSession() deduplicating ~80L between
  startInteractive/startShell; extract _handleTerminalOutput()
- respawn-controller: split 180L handleTerminalData() into 3 detection layers;
  data-driven validation loop replacing 9 individual calls
- plan-orchestrator: extract _extractJsonFromResponse(), _emitAgentFailure(),
  _formatResearchSection() helpers
- orchestrator-loop: extract _finalizeTask() unifying task completion/failure;
  _clearTimer() utility for correct clearInterval/clearTimeout dispatch
- ralph-status-parser: config-driven FIELD_PARSERS[] replacing 8 near-identical
  field-matching blocks; split updateCircuitBreaker() into focused handlers
- state-store: extract _mergeWithInitialState() and _resetCircuitBreaker()

Frontend:
- app.js: add _notifySession() helper used by 18 call sites across 5 modules
- panels-ui.js: extract _addActivityEntry() replacing 4 duplicate blocks
- settings-ui.js: extract _updateTunnelUrlRow() deduplicating 2 blocks
- ralph-panel.js, respawn-ui.js: convert to _notifySession()

Routes:
- route-helpers: add toggleService() helper
- system-routes: use toggleService() for watcher toggles; extract collectActiveTokens()
- orchestrator-routes: data-driven EVENT_MAP replacing 10 identical listeners

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-26 22:50:25 +01:00
arkonandClaude Opus 4.6 3145eac6d9 refactor: extract helper methods to reduce duplication and improve readability
DRY up repeated patterns across 7 core files:
- state-store: extract serializeState() and split assembleStateJson() into 3 focused methods
- session: extract _resetBuffers(), _clearAllTimers(), _handleJsonMessage()
- ralph-tracker: extract completeAllTodos() (was 4x duplicated), emitValidationWarning(), similarity constants
- subagent-watcher: extract markSubagentAsCompleted(), extractFirstTextContent(), emitToolResult(), findOldestInactiveAgent()
- respawn-controller: extract recoveryResetToWatching(), canAutoAccept(), formatRemainingSeconds(), validatePositiveTimeout()
- tmux-manager: replace 15 path.includes() checks with single UNSAFE_PATH_CHARS regex
- session-auto-ops: extract executeWhenIdle() shared retry helper for checkAutoCompact/checkAutoClear

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-25 23:21:38 +01:00
arkonandClaude Opus 4.6 98fa55b7b2 chore: codebase cleanup — remove dead code, consolidate imports, extract constants
- Remove 3 unused exported constants (TRIM_MESSAGES_TO, MAX_TERMINAL_COLS, MAX_TERMINAL_ROWS)
- Consolidate 8 direct util imports into barrel imports (./utils/index.js)
- Extract magic number 8191 to FILE_PEEK_BYTES constant in buffer-limits.ts
- Add explanatory comments to 9 undocumented .catch(() => {}) handlers

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 15:50:40 +01:00
arkonandClaude Opus 4.6 0717cfbfec refactor: codebase cleanup — dead code, regex helper, centralized constants, tests
- Remove unused validateTokenCounts/validateTokensAndCost exports and PlanPhase type alias
- Add execPattern() helper to eliminate 8 repetitive .lastIndex=0 + exec() loops
- Centralize 11 magic number constants into config/ai-defaults.ts and config/server-timing.ts
- Remove stale src/tui from tsconfig.json exclude
- Fix CLAUDE.md inaccuracies (session helpers, app.js line count, module count)
- Add 316 new tests: LRUMap (38), StaleExpirationMap (42), BufferAccumulator (33),
  respawn helpers (142), system-routes expansion (11→61)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 07:33:44 +01:00
Ark0NandClaude Opus 4.6 2ee9ad72e8 refactor: SSE event handlers, LLM context optimization, @fileoverview docs (#29)
* refactor: extract SSE event handlers into named class methods

Replace ~80 inline addListener closures in connectSSE() with a
declarative _SSE_HANDLER_MAP array that drives registration in a
single loop. Each handler is now a named _on* method on CodemanApp,
making them individually addressable for LLM navigation.

Add SSE_EVENTS constant object in constants.js to eliminate magic
event-type strings scattered across the frontend.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: fix inaccuracies in CLAUDE.md

- Fix types barrel path: src/types.ts → src/types/index.ts
- Update app.js line count: ~12K → ~11.5K
- Correct route handler counts (113 → 111, per-group fixes)
- Add code style, ESM gotcha, env vars, route test, lifecycle log docs
- Add Node 22 CI note, test teardown timeout, port range

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: add mobile screenshots and QR auth security writeup to README

Add 3 mobile screenshots (landing, idle, active) and expand the
mobile section with QR auth security design details and a
touch-optimized interface subsection.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: bundle xterm-zerolag-input as vendor IIFE and add pre-commit hook

Build and postinstall now bundle the local xterm-zerolag-input package
as an IIFE at vendor/xterm-zerolag-input.js with global LocalEchoOverlay
shim. Add git pre-commit hook that runs prettier --check on staged .ts
files to catch format issues before CI.

Also bump constants.js and app.js cache-bust versions to 0.3.0 and add
tunnel upload URL display row in settings.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add cloudflared install support and interactive launch menu

- Add optional cloudflared dependency detection and installation
  across 6 distro families (macOS, Debian, Fedora, Arch, Alpine, SUSE)
- Add tunnel systemd service setup helper
- Replace post-install instructions with interactive launch menu
  (run now / systemd service / skip)
- Uninstall now cleans up both codeman-web and codeman-tunnel services

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: gitignore readme-preview.mjs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: WIP — SSE event constants, @fileoverview docs, CLAUDE.md compression

- Migrate broadcast() string literals → SseEvent.* typed constants
- Add @fileoverview with cross-domain references to all 13 type domain files
- Add @fileoverview to frontend JS modules (constants, mobile, voice, etc.)
- Add section dividers to route files for LLM scanability
- Compress CLAUDE.md: flat file list → domain table, fix counts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: optimize codebase for LLM context window efficiency

CLAUDE.md: 456 → 309 lines (32% reduction)
- Merge Commands into compact table, remove redundant bash block
- Convert Security section to dense table format
- Merge Performance + Resource Limits, Debugging + Troubleshooting
- Compress Tunnel, Memory Leak, Scripts, Screenshots sections
- Remove Key Patterns that duplicate @fileoverview in source files

Backend @fileoverview enhancements (10 priority files):
- session.ts: key methods, events, cross-domain refs
- respawn-controller.ts: state machine, idle detection layers
- ralph-tracker.ts: exports, circuit breaker, events
- ralph-loop.ts: lifecycle, persistence, events
- subagent-watcher.ts: watched patterns, teammate detection
- server.ts: coordination list, port interfaces
- state-store.ts: dual-file persistence, migration
- session-manager.ts: lifecycle methods, mutex guard
- hooks-config.ts: hook events list, categories
- sse-events.ts: category breakdown (~90 events, 17 categories)

Frontend app.js: add 6 section dividers, update @fileoverview line refs

Fix: escape glob `*/` in JSDoc that broke ESLint parser

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: address PR #29 review bugs

- server.ts: replace hardcoded 'session:needsRefresh' with SseEvent constant
- install.sh: fix Alpine cloudflared install for non-root (download to tmpfile first)
- install.sh: replace Arch pacman (AUR-only) with direct binary download
- index.html: bump all 8 remaining cache-bust versions from v0.2.9 to v0.3.0
- mobile-handlers.js: fix @dependency annotation (keyboard-accessory.js, not constants.js)
- types/push.ts: fix layer number (4, not 5)
- subagent-watcher.ts: fix watched pattern path to include {session} segment
- constants.js: fix SSE_EVENTS count in @fileoverview (~73, not ~65)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 22:40:18 +01:00
arkonandClaude Opus 4.6 97ca13916a refactor: consolidate ~70 scattered constants into 6 new config files (phase 6)
Create 6 domain-focused config files in src/config/ to centralize operational
tuning knobs that were scattered across 15+ source files:

- server-timing.ts: SSE batching, state debounce, scheduled runs, error recovery
- auth-config.ts: session TTL, rate limits, hook timeout
- tunnel-config.ts: QR token rotation, tunnel process lifecycle
- terminal-limits.ts: input length, terminal cols/rows, session name
- ai-defaults.ts: AI model string, idle/plan context limits
- team-config.ts: poll interval, cache sizes

Eliminates all cross-file duplicates:
- AI model string: 5 occurrences → 1 (config only)
- STATS_COLLECTION_INTERVAL_MS: 2 → 1
- timeout: 10000 in hooks-config: 6 → 0 (now HOOK_TIMEOUT_MS)
- MAX_TRACKED_AGENTS shadow: removed, imports from map-limits

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 13:19:16 +01:00
arkonandClaude Opus 4.6 e0a2774d37 perf: implement phase 1-3 performance optimizations
Add implementation plans and code structure analysis for a 3-phase
performance optimization effort. Refactor core modules to reduce
timer overhead, consolidate regex usage, extract exec timeout config,
add debouncer utility, and streamline server/schema validation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 17:39:44 +01:00
arkonandClaude Opus 4.6 db8ee8458c chore: version packages
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 14:45:39 +01:00
480584de63 chore: project setup and tooling cleanup (#26)
* add project setup

* add tools to eslint

* remove contributing.md

* update claude md

* chore: simplify CI to single Node.js version (22)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* use node 20

* adjust formatting

* fix linting

* format

* fix layout

* fix: align CI node version to .nvmrc (22), remove redundant gotcha

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: arkon <arkon.85@hotmail.com>
2026-02-27 13:16:23 +01:00
arkonandClaude Opus 4.6 3795c45cc1 chore: rename Claudeman to Codeman
Full product rename across 109 files (~834 occurrences):
- Env vars: CLAUDEMAN_* → CODEMAN_*
- Data dirs: ~/.claudeman/ → ~/.codeman/, ~/claudeman-cases/ → ~/codeman-cases/
- tmux prefix: claudeman- → codeman-
- localStorage: claudeman-* → codeman-*
- Package/CLI: claudeman → codeman
- GitHub repo: Ark0N/Claudeman → Ark0N/Codeman
- systemd service: claudeman-web → codeman-web
- Class: ClaudemanApp → CodemanApp

Migration infrastructure for seamless transition:
- state-store.ts: auto-migrates data directories on startup
- tmux-manager.ts: dual-prefix detection (legacy claudeman- sessions)
- app.js: localStorage key migration (preserves old keys)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 16:44:34 +01:00
arkonandClaude Opus 4.6 85ee601b5b chore: bump version to 0.1584
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 16:26:11 +01:00
arkonandClaude Opus 4.6 2de3c46f66 chore: bump version to 0.1583
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 16:18:43 +01:00
arkon 5b882c448e chore: bump version to 0.1570 2026-02-20 06:09:28 +01:00
arkonandClaude Opus 4.6 c8a055d564 chore: bump version to 0.1565
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-19 23:21:28 +01:00
arkonandClaude Opus 4.6 31d3e7bc70 chore: bump version to 0.1528
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 07:06:34 +01:00
arkonandClaude Opus 4.6 9ab62adfa8 fix: medium severity audit fixes — races, leaks, perf, warnings
- Clear teams/teamTasks maps in handleInit() on SSE reconnect
- Fix saveNowAsync() race condition with in-flight promise guard
- Add setMaxListeners() on Session, WebServer, SubagentWatcher,
  ImageWatcher, TmuxManager to prevent MaxListenersExceeded warnings
- Debounce persistSessionState() per-session (100ms) to reduce
  redundant toState() serialization across 25+ call sites
- Cache getLightSessionsState() with 1s TTL to avoid re-serializing
  all sessions on every SSE connect and /api/sessions request

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 05:33:34 +01:00
arkonandClaude Opus 4.6 f223501164 fix: async I/O, map iteration bug, unified cleanup, Zod validation, error handling
- Convert sync readFileSync/statSync to async in subagent-watcher.ts to
  unblock event loop on hot paths (transcript reads, liveness checks)
- Fix Map mutation during iteration in closeSessionLogViewerWindows and
  closeSessionImagePopups (collect IDs first, then iterate to close)
- Unify session cleanup into shared _cleanupSessionData() method called
  from both closeSession() and session:deleted handler to prevent leaks
- Add Zod validation schemas for 20+ API routes that used raw type casts
- Add consecutive error tracking (5 errors/60s triggers exit for systemd
  restart) and SIGHUP handler for SSH disconnect safety

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 05:26:29 +01:00
arkon 3a77fe48e3 chore: bump version to 0.1496 2026-02-13 07:42:50 +01:00
arkonandClaude Opus 4.6 7d2519cacb fix: subagent windows not opening — two cascading bugs
1. handleInit crash: commit cdc822d removed Map initializations for
   teammateTerminals, teammatePanesByName, teams, teamTasks, teammateMap
   from the constructor but left cleanup code that iterates them.
   cleanupAllFloatingWindows() crashed on "not iterable", preventing
   ALL frontend data (sessions, subagents) from loading.

2. claudeSessionId null on recovered sessions: only set inside
   startInteractive(), never in constructor or persisted. After server
   restart, recovered sessions had null claudeSessionId, so the
   hasMatchingTab check always failed → no subagent windows.

Fixes:
- Re-add all 5 missing Map initializations in app.js constructor
- Set _claudeSessionId = this.id in Session constructor (Claudeman
  always passes --session-id to Claude, so they always match)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 05:07:51 +01:00
arkonandClaude Opus 4.6 0314de7789 fix: bulletproof test safety — IS_TEST_MODE guards prevent tests from killing real tmux sessions
Added IS_TEST_MODE (process.env.VITEST) guards to every method in TmuxManager and
ScreenManager that touches real tmux/screen sessions. Tests can never create, kill,
discover, or send input to real sessions. Removed broken E2E test suite entirely.
Rewrote test/setup.ts from 459 lines to minimal cleanup. Rewrote tmux-related tests
to verify test-mode safety behavior.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 18:26:16 +01:00
arkon e44f827473 chore: bump version to 0.1488 2026-02-12 14:41:27 +01:00
arkonandClaude Opus 4.5 8f0bbf33d6 chore: bump version to 0.1477
Location: Ko Samui

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 07:24:32 +01:00
arkonandClaude Opus 4.5 eb7c005363 fix: memory leaks and performance optimizations
- WebServer: Store session listener refs for explicit cleanup on delete
- RespawnController: Fix clearInterval bug (was using clearTimeout)
- RespawnController: Add try/catch to interval callbacks
- PlanOrchestrator: Guarantee progressInterval cleanup with try/finally
- SubagentWatcher: Guard idle timer against deleted agents
- Session: Add threshold validation for auto-clear/compact (1k-500k)
- Session: Add token sum overflow check in restoreTokens
- Session: Use LRUMap for _recentTaskDescriptions auto-eviction

Commit from flight QR118 in an Airbus A350-1000, stable connection thanks to Starlink!

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-31 23:48:59 +01:00
arkonandClaude Opus 4.5 fd30040289 feat: mobile keyboard input visibility - scroll inputs into view when keyboard opens
- Add KeyboardHandler module using visualViewport API for keyboard detection
- Set --keyboard-height CSS variable and toggle .keyboard-visible class
- Auto-scroll focused inputs into view after keyboard appears (350ms delay)
- Update viewport meta with interactive-widget=resizes-content for Android
- Add scroll-margin on inputs for tablet/phone breakpoints
- Resize modal-content and modal-body when keyboard visible on mobile

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-31 07:51:29 +01:00
arkonandClaude Opus 4.5 20283019f4 feat: comprehensive codebase improvements (cleanup, logic, performance)
Code Cleanups:
- Consolidated PlanTaskStatus and TddPhase types to types.ts
- Standardized node: prefix for Node.js builtin imports
- Fixed timer type to NodeJS.Timeout in respawn-controller

Logic Improvements:
- Fixed AI check race condition with UUID tracking in respawn-controller
- Added comprehensive _isStopped guards in session timer callbacks
- Made RalphTracker reset events non-reentrant via process.nextTick()
- Improved SessionManager mutex pattern reliability

Performance Optimizations:
- Fixed pendingToolCalls memory leak with TTL cleanup in subagent-watcher
- Improved LRUMap.newest() from O(n) to O(1) with _newestKey tracking

Documentation:
- Enhanced README antiflicker section with 6-layer technical details

Version: 0.1441

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-30 19:05:46 +01:00
arkon f4612278ef chore: bump version to 0.1437 2026-01-30 14:14:45 +01:00
arkon 7dfd97df58 chore: bump version to 0.1434 2026-01-30 11:30:51 +01:00
arkonandClaude Opus 4.5 c659b7769e feat: enhance /api/debug/memory endpoint with comprehensive metrics
- Add getStats() method to SubagentWatcher for internal resource tracking
- Return detailed Map sizes for all server and subagent Maps
- Track file watchers, directory watchers, and transcript watchers separately
- Track all timer types (respawn, idle, pending starts)
- Add totals for quick overview of resource usage
- Useful for debugging memory leaks and resource exhaustion

The enhanced endpoint now returns:
- Memory usage (heap, external, array buffers)
- Map sizes by component (server, subagent watcher)
- Watcher counts (file, directory, transcript)
- Timer counts by type
- Spawn agent statistics

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 04:44:29 +01:00
arkon 59b22337a5 chore: bump version to 0.1390 2026-01-27 00:41:00 +01:00
arkonandClaude Opus 4.5 428556e831 refactor: extract magic numbers to named constants
Low severity code quality improvements:
- session.ts: Add timing constants (SCREEN_STARTUP_DELAY_MS, etc.)
- screen-manager.ts: Add EXEC_TIMEOUT_MS, CR_MAX_ATTEMPTS, etc.
- subagent-watcher.ts: Add display length constants
- server.ts: Add STATS_COLLECTION_INTERVAL_MS, SESSION_LIMIT_WAIT_MS, etc.
- spawn-orchestrator.ts: Add budget ratio constants
- respawn-controller.ts: Use pre-compiled ANSI_ESCAPE_PATTERN
- state-store.ts: Use ES6 import for unlinkSync instead of dynamic require
- app.js: Add notification timing constants

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 14:27:21 +01:00
arkonandClaude Opus 4.5 3c2e89f427 fix: address medium severity issues from code review
- Fix inconsistent null handling in state-store (use ?? instead of ||)
- Add JSON.stringify error handling with specific messages
- Add error handling for SSE init event in app.js
- Fix spawn orchestrator silent failures (add logging)
- Fix statSync race condition in subagent-watcher
- Fix unbounded _taskNumberToContent Map in ralph-tracker
- Fix YAML pattern case sensitivity in ralph-config

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 13:58:34 +01:00
arkonandClaude Opus 4.5 e81dc4665a fix: high severity memory leaks and bugs
- Add warningTimer to AgentContext and clean it up in cleanupAgent
- Clear all state in subagent-watcher stop() for clean restart
- Add cleanupStaleAgents() to remove completed agents older than 24h
- Delete pendingToolCalls entries after lookup to prevent memory leak
- Add FSWatcher error handlers to prevent unhandled exceptions
- Bump version to 0.1382

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 12:50:39 +01:00
arkonandClaude Opus 4.5 fe334c2ea6 fix: improve stability with memory leak fixes and atomic writes
Session Manager:
- Store event handlers for proper cleanup on session stop
- Add resetSessionManager() for test isolation

State Store:
- Use atomic write pattern (temp file + rename) to prevent corruption
- Add tokenStats to AppState interface

Subagent Watcher:
- Clean up pendingToolCalls on agent completion
- Add cleanupStaleAgents() for 24h+ old agents
- Clear all state maps on stop() for clean restart

Web Server:
- Remove listeners from transcript watcher before stopping
- Clean up respawn timers when session is deleted
- Use cleanupSession() in spawn orchestrator for proper resource cleanup

Frontend:
- Close existing EventSource before reconnecting to prevent duplicates
- Close failed connection before scheduling reconnect

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 12:35:00 +01:00
arkonandClaude Opus 4.5 32e0d6126c fix: read subagent descriptions directly from parent transcript
Instead of timing-based correlation between terminal output and subagent
files, now reads the Task tool's description parameter directly from the
parent session's transcript. This provides 100% reliable mapping between
agent IDs and their short descriptions, fixing issues where multiple
agents spawned in quick succession would get the same window title.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 11:06:35 +01:00
arkonandClaude Opus 4.5 fc940e153b fix: correct Task tool description extraction for subagent window titles
- Add parseTaskDescriptionsFromTerminalData() to parse raw terminal data in
  interactive sessions (not just one-shot mode)
- Strip ANSI codes before regex matching since terminal output has embedded
  codes like [1mExplore[0m
- Fix getTaskDescriptionForSubagent() to check ALL sessions with matching
  project hash (not just the first one found) since multiple sessions can
  share the same working directory
- Add tool_result event forwarding for subagent SSE broadcasts

The pattern Explore(Description) in terminal output is now correctly parsed
and used as the subagent window title instead of extracting from the prompt.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 10:42:04 +01:00
arkonandClaude Opus 4.5 f06240f4ef feat: use Task tool description for subagent window titles + auto-minimize completed
- Extract short description from TaskTracker (params.description) for subagent windows
- Correlate subagents with sessions by working directory and timing
- Auto-minimize subagent windows when agents complete
- Persist minimized/open window states to server for cross-browser sync
- Restore window states on reconnection/page reload
- New API: GET/PUT /api/subagent-window-states
- State file: ~/.claudeman/subagent-window-states.json

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-26 09:06:49 +01:00
arkonandClaude Opus 4.5 c6b16bf815 fix: subagent title extraction race condition
- Add 100ms debounce for new file detection to allow content to be written
- Add subagent:updated event for retroactive description updates
- Extract description in processEntry when first user message is processed
- Add extractDescriptionFromFile helper with retry in file change handler
- Update SubagentTranscriptEntry.content type to support string | array
- Add test coverage for subagent:updated event

Fixes 43% failure rate where subagents displayed raw IDs instead of descriptions
due to race condition when files were discovered before first line was written.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 19:49:58 +01:00
arkonandClaude Opus 4.5 0d22d19645 docs: improve CLAUDE.md structure and discoverability
- Move COM shorthand to prominent position after safety warning
- Add version sync note (must match package.json)
- Consolidate Key Files into 4 logical categories
- Clarify next available test port (3128)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 18:09:25 +01:00
arkonandClaude Opus 4.5 8094a756c6 feat: smart title extraction for subagent descriptions
- Condenses long prompts to ~45 chars while preserving meaning
- Removes filler words (the, a, please, I need you to, etc.)
- Cuts at natural boundaries (colons, dashes, commas)
- Falls back to word-boundary truncation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 17:56:31 +01:00
arkonandClaude Opus 4.5 953d9845ca fix: subagent description extraction for JSONL format
The JSONL files have message.content as a direct string, not an array
of content blocks. Now handles both formats correctly.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 17:51:59 +01:00
arkonandClaude Opus 4.5 cec9608b66 ui: improve subagent window titles and readability
- Extract better titles from task description (first line/sentence)
- Make subagent window text white for better readability
- Expand monitor panel to 700px when subagents tab is active
- Add smooth width transition when switching tabs

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 17:40:28 +01:00
arkonandClaude Opus 4.5 ad24020cdc feat: add real-time subagent visibility - monitor Claude Code background agents
- Add SubagentWatcher service that discovers and tails Claude Code's subagent
  transcript files (~/.claude/projects/.../subagents/agent-*.jsonl)
- Track tool calls, progress events, and messages in real-time via file watching
- Add SSE events for subagent:discovered, subagent:tool_call, subagent:progress,
  subagent:message, subagent:completed
- Add REST API endpoints: GET /api/subagents, /api/subagents/:id,
  /api/subagents/:id/transcript
- Add subagent panel in Monitor section showing active agents and their activity
- Add floating draggable windows that auto-open for each active agent
- Add standalone CLI tool: scripts/watch-subagents.ts for terminal monitoring

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-25 14:33:12 +01:00