-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.sh
More file actions
executable file
·898 lines (740 loc) · 28 KB
/
Copy pathmonitor.sh
File metadata and controls
executable file
·898 lines (740 loc) · 28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
#!/usr/bin/env bash
# Monitor is the foreground CLI for the WSL desktop activity summarizer. It
# loads local settings, captures Windows desktop screenshots through the
# repository helper, asks Codex CLI to summarize each image and refresh the run
# summary, and writes sensitive run artifacts under a gitignored output directory.
set -euo pipefail
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)
REPO_ROOT=$(cd "$SCRIPT_DIR/.." && pwd -P)
DEFAULT_ANALYZER="codex"
DEFAULT_INTERVAL_SECONDS="60"
DEFAULT_OUTPUT_DIR=".monitor/runs"
DEFAULT_CAPTURE_COMMAND="$REPO_ROOT/scripts/win-screenshot"
DEFAULT_CODEX_COMMAND="codex"
DEFAULT_SLEEP_COMMAND="sleep"
usage() {
cat <<'USAGE'
Usage: bash src/monitor.sh [options]
Capture Windows desktop screenshots from WSL, summarize them with Codex CLI,
and write local text activity summaries.
Options:
--interval SECONDS Seconds between screenshots. Default: 60.
--count N Stop after N screenshots. Default: unlimited.
--output-dir DIR Directory that receives timestamped run folders.
Default: .monitor/runs.
--analyzer NAME Analyzer backend. Only "codex" is supported in v1.
--codex-model MODEL Optional Codex model override.
--once Capture and analyze one screenshot.
-h, --help Show this help.
Environment:
MONITOR_ANALYZER
MONITOR_INTERVAL_SECONDS
MONITOR_OUTPUT_DIR
MONITOR_CODEX_MODEL
Test hooks:
MONITOR_ENV_FILE
MONITOR_CAPTURE_COMMAND
MONITOR_CODEX_COMMAND
MONITOR_SLEEP_COMMAND
MONITOR_TEST_STOP_AFTER_ITERATIONS
USAGE
}
# Print a CLI error and stop before any further work happens.
die() {
printf 'monitor: %s\n' "$*" >&2
exit 1
}
# Return success when the supplied value is a nonzero positive integer.
is_positive_integer() {
[[ "${1:-}" =~ ^[1-9][0-9]*$ ]]
}
# Check either an executable path or a command name without printing anything.
command_available() {
local command_name=$1
if [[ "$command_name" == */* ]]; then
[[ -x "$command_name" ]]
else
command -v "$command_name" >/dev/null 2>&1
fi
}
# Stop with a named dependency error when a required command is unavailable.
require_command() {
local command_name=$1
local description=$2
if ! command_available "$command_name"; then
die "$description is required but was not found: $command_name"
fi
}
# Resolve repo-relative output paths so artifacts have stable absolute paths.
resolve_path() {
local path_value=$1
case "$path_value" in
/*) printf '%s\n' "$path_value" ;;
*) printf '%s\n' "$REPO_ROOT/$path_value" ;;
esac
}
# Remove a trailing Windows carriage return from .env lines read in WSL.
trim_cr() {
local value=$1
printf '%s\n' "${value%$'\r'}"
}
# Load simple KEY=VALUE settings from .env without overriding the shell.
load_env_file() {
local env_file=$1
local line key value
[[ -f "$env_file" ]] || return 0
while IFS= read -r line || [[ -n "$line" ]]; do
line=$(trim_cr "$line")
case "$line" in
''|'#'*) continue ;;
esac
if [[ "$line" != *=* ]]; then
die "invalid .env line without KEY=VALUE syntax in $env_file: $line"
fi
key=${line%%=*}
value=${line#*=}
if [[ ! "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then
die "invalid .env variable name in $env_file: $key"
fi
if [[ -z ${!key+x} ]]; then
printf -v "$key" '%s' "$value"
export "$key"
fi
done < "$env_file"
}
# Parse CLI flags after .env values have populated Monitor defaults.
parse_args() {
analyzer=${MONITOR_ANALYZER:-$DEFAULT_ANALYZER}
interval_seconds=${MONITOR_INTERVAL_SECONDS:-$DEFAULT_INTERVAL_SECONDS}
output_dir=${MONITOR_OUTPUT_DIR:-$DEFAULT_OUTPUT_DIR}
codex_model=${MONITOR_CODEX_MODEL:-}
test_stop_after_iterations=${MONITOR_TEST_STOP_AFTER_ITERATIONS:-}
count_limit=""
once="false"
while [[ $# -gt 0 ]]; do
case "$1" in
--interval)
[[ $# -ge 2 ]] || die "--interval requires SECONDS"
interval_seconds=$2
shift 2
;;
--count)
[[ $# -ge 2 ]] || die "--count requires N"
count_limit=$2
shift 2
;;
--output-dir)
[[ $# -ge 2 ]] || die "--output-dir requires DIR"
output_dir=$2
shift 2
;;
--analyzer)
[[ $# -ge 2 ]] || die "--analyzer requires NAME"
analyzer=$2
shift 2
;;
--codex-model)
[[ $# -ge 2 ]] || die "--codex-model requires MODEL"
codex_model=$2
shift 2
;;
--once)
once="true"
count_limit="1"
shift
;;
-h|--help)
usage
exit 0
;;
*)
die "unknown argument: $1"
;;
esac
done
}
# Validate user-provided runtime settings before creating run artifacts.
validate_config() {
if [[ "$analyzer" != "codex" ]]; then
die "unsupported analyzer '$analyzer'; v1 only supports 'codex'"
fi
is_positive_integer "$interval_seconds" || die "--interval must be a positive integer"
if [[ -n "$count_limit" ]]; then
is_positive_integer "$count_limit" || die "--count must be a positive integer"
fi
if [[ -n "$test_stop_after_iterations" ]]; then
is_positive_integer "$test_stop_after_iterations" || die "MONITOR_TEST_STOP_AFTER_ITERATIONS must be a positive integer"
fi
}
# Resolve and validate all external commands used by the selected configuration.
validate_commands() {
capture_command=${MONITOR_CAPTURE_COMMAND:-$DEFAULT_CAPTURE_COMMAND}
codex_command=${MONITOR_CODEX_COMMAND:-$DEFAULT_CODEX_COMMAND}
sleep_command=${MONITOR_SLEEP_COMMAND:-$DEFAULT_SLEEP_COMMAND}
require_command "date" "date"
require_command "mkdir" "mkdir"
require_command "mktemp" "mktemp"
require_command "mv" "mv"
require_command "cat" "cat"
require_command "$sleep_command" "sleep command"
require_command "$capture_command" "capture command"
require_command "$codex_command" "Codex analyzer command"
if [[ -z ${MONITOR_CAPTURE_COMMAND+x} ]]; then
require_command "powershell.exe" "powershell.exe for Windows desktop capture"
require_command "wslpath" "wslpath for Windows desktop capture"
fi
}
# Return a local datetime that is readable and safe in Windows-visible paths.
filename_datetime_stamp() {
date +%Y-%m-%d_%H-%M-%S
}
# Create a unique timestamped run directory with screenshot and summary folders.
create_run_dir() {
local output_root=$1
local stamp base candidate suffix
stamp=$(filename_datetime_stamp)
base="$output_root/$stamp"
candidate=$base
suffix=2
while [[ -e "$candidate" ]]; do
candidate="$base-$suffix"
suffix=$((suffix + 1))
done
mkdir -p "$candidate/screenshots" "$candidate/summaries"
printf '%s\n' "$candidate"
}
# Print the first few lines of a summary file for dashboard and rollup excerpts.
summary_excerpt() {
local summary_file=$1
local max_lines=${2:-8}
local line line_count
line_count=0
while IFS= read -r line && [[ $line_count -lt $max_lines ]]; do
printf '%s\n' "$line"
line_count=$((line_count + 1))
done < "$summary_file"
return 0
}
# Format a duration in seconds for compact terminal display.
format_duration() {
local total_seconds=$1
local hours minutes seconds
if [[ "$total_seconds" == "complete" || "$total_seconds" == "∞" ]]; then
printf '%s\n' "$total_seconds"
return 0
fi
hours=$((total_seconds / 3600))
minutes=$(((total_seconds % 3600) / 60))
seconds=$((total_seconds % 60))
if (( hours > 0 )); then
printf '%dh %02dm %02ds\n' "$hours" "$minutes" "$seconds"
elif (( minutes > 0 )); then
printf '%dm %02ds\n' "$minutes" "$seconds"
else
printf '%ds\n' "$seconds"
fi
}
# Return a numeric percent for bounded runs or infinity for unbounded runs.
progress_percent() {
local percent
if [[ -z "$count_limit" ]]; then
printf '%s\n' "∞"
return 0
fi
percent=$((screenshots_attempted * 100 / count_limit))
if (( percent > 100 )); then
percent=100
fi
printf '%s\n' "$percent"
}
# Render a fixed-width ASCII progress bar for bounded or unbounded runs.
progress_bar() {
local percent=$1
local width=24
local filled empty bar
if [[ "$percent" == "∞" ]]; then
printf '[########################] ∞\n'
return 0
fi
filled=$((percent * width / 100))
empty=$((width - filled))
bar=""
while (( filled > 0 )); do
bar+="#"
filled=$((filled - 1))
done
while (( empty > 0 )); do
bar+="-"
empty=$((empty - 1))
done
printf '[%s]\n' "$bar"
}
# Return the current attempted screenshot count against the run limit.
progress_count() {
if [[ -n "$count_limit" ]]; then
printf '%s/%s\n' "$screenshots_attempted" "$count_limit"
else
printf '%s/∞\n' "$screenshots_attempted"
fi
}
# Estimate completion from the current progress and next-capture countdown.
completion_eta_seconds() {
local next_seconds=$1
local remaining_shots
if [[ -z "$count_limit" ]]; then
printf '%s\n' "∞"
return 0
fi
remaining_shots=$((count_limit - screenshots_attempted))
if (( remaining_shots <= 0 )); then
printf '%s\n' "complete"
return 0
fi
if [[ "$next_seconds" =~ ^[0-9]+$ ]]; then
printf '%s\n' $((next_seconds + ((remaining_shots - 1) * interval_seconds)))
else
printf '%s\n' $((remaining_shots * interval_seconds))
fi
}
# Enable ANSI color and live screen refresh only when stdout supports them.
initialize_display() {
if [[ -t 1 && "${TERM:-}" != "dumb" && -z "${NO_COLOR:-}" ]]; then
live_dashboard="true"
color_blue=$'\033[34m'
color_green=$'\033[32m'
color_red=$'\033[31m'
color_yellow=$'\033[33m'
color_bold=$'\033[1m'
color_dim=$'\033[2m'
color_reset=$'\033[0m'
else
live_dashboard="false"
color_blue=""
color_green=""
color_red=""
color_yellow=""
color_bold=""
color_dim=""
color_reset=""
fi
}
# Pick a color for the latest phase or failure status.
status_color() {
local status=$1
case "$status" in
analysis_succeeded|summary_updated|complete) printf '%s\n' "$color_green" ;;
analysis_failed|capture_failed|summary_failed|error) printf '%s\n' "$color_red" ;;
waiting|capturing|analyzing|summarizing|starting) printf '%s\n' "$color_blue" ;;
*) printf '%s\n' "$color_yellow" ;;
esac
}
# Render the user-facing terminal dashboard or plain redirected-output block.
render_dashboard() {
local phase=$1
local latest_status=$2
local latest_screenshot_path=${3:-}
local latest_summary_path=${4:-}
local next_seconds=${5:-}
local current_summary_status=${6:-}
local percent count_display bar eta_value eta_display next_display phase_color
percent=$(progress_percent)
count_display=$(progress_count)
bar=$(progress_bar "$percent")
eta_value=$(completion_eta_seconds "${next_seconds:-}")
eta_display=$(format_duration "$eta_value")
phase_color=$(status_color "$latest_status")
if [[ "$next_seconds" == "complete" || "$phase" == "complete" ]]; then
next_display="complete"
elif [[ "$next_seconds" =~ ^[0-9]+$ ]]; then
next_display=$(format_duration "$next_seconds")
else
next_display="now"
fi
if [[ "$live_dashboard" == "true" ]]; then
printf '\033[2J\033[H'
else
printf '\n'
fi
printf '%b%s%b\n' "$color_bold" "Monitor" "$color_reset"
printf '%b%s%b %s\n' "$phase_color" "Phase:" "$color_reset" "$phase"
printf 'Progress: %s (%s%%) %s\n' "$count_display" "$percent" "$bar"
printf 'Interval: %ss\n' "$interval_seconds"
printf 'Next screenshot: %s\n' "$next_display"
printf 'Time to completion: %s\n' "$eta_display"
printf 'Analyzer: %s\n' "$analyzer"
printf 'Run directory: %s\n' "$run_dir"
printf 'Screenshots: %s attempted, %s analyzed, %s failed\n' "$screenshots_attempted" "$successful_summaries" "$failed_summaries"
printf 'Current summary: %s updates, %s failures' "$current_summary_updates" "$current_summary_failures"
if [[ -n "$current_summary_status" ]]; then
printf ' (%s)' "$current_summary_status"
fi
printf '\n'
if [[ -n "$latest_screenshot_path" ]]; then
printf 'Latest screenshot: %s\n' "$latest_screenshot_path"
fi
if [[ -n "$latest_summary_path" ]]; then
printf 'Latest analysis: %s\n' "$latest_summary_path"
fi
printf '\n%bLatest Analysis%b\n' "$color_bold" "$color_reset"
if [[ -n "$latest_summary_path" && -f "$latest_summary_path" ]]; then
summary_excerpt "$latest_summary_path" 6
else
printf '%s\n' "No screenshot analysis yet."
fi
printf '\n%bCurrent Summary%b\n' "$color_bold" "$color_reset"
if [[ -f "$current_summary_file" ]]; then
summary_excerpt "$current_summary_file" 8
else
printf '%s\n' "No current summary yet."
fi
}
# Print the complete final run narrative after a bounded invocation finishes.
print_final_detailed_summary() {
printf '\n%bFinal Detailed Summary%b\n' "$color_bold" "$color_reset"
printf 'Source: %s\n\n' "$current_summary_file"
if [[ -f "$current_summary_file" ]]; then
cat "$current_summary_file"
printf '\n'
else
printf '%s\n' "No current summary was written."
fi
}
# Extract a one-line analyzer failure message for summaries and index rows.
first_log_line() {
local log_file=$1
local line
if [[ -s "$log_file" ]]; then
IFS= read -r line < "$log_file" || line="analysis command failed"
printf '%s\n' "${line//$'\t'/ }"
else
printf '%s\n' "analysis command failed"
fi
}
# Append one tab-separated event row to the run index.
append_index_row() {
local timestamp=$1
local status=$2
local screenshot_path=$3
local summary_path=$4
local message=$5
message=${message//$'\t'/ }
message=${message//$'\n'/ }
printf '%s\t%s\t%s\t%s\t%s\n' "$timestamp" "$status" "$screenshot_path" "$summary_path" "$message" >> "$index_file"
}
# Write a Markdown per-screenshot summary when the analyzer fails.
write_failure_summary() {
local summary_path=$1
local screenshot_path=$2
local message=$3
cat > "$summary_path" <<FAILURE
# Screenshot Summary
Analysis failed for this screenshot.
# Visible Activity
No activity summary is available because the analyzer command failed.
# Notable Changes
No changes were inferred.
# Uncertainty
The screenshot was saved at \`$screenshot_path\`, but Codex CLI did not produce a successful summary.
Failure: $message
FAILURE
}
# Write a Markdown per-screenshot summary when capture fails before analysis.
write_capture_failure_summary() {
local summary_path=$1
local screenshot_path=$2
local message=$3
cat > "$summary_path" <<FAILURE
# Screenshot Summary
Screenshot capture failed before analysis, so no visible desktop activity could be summarized for this cycle.
# Visible Activity
No activity summary is available because Monitor could not save a usable screenshot.
# Notable Changes
No changes were inferred.
# Uncertainty
Monitor intended to save the screenshot at \`$screenshot_path\`, but the capture command did not produce a usable image.
Failure: $message
FAILURE
}
# Rewrite the deterministic run rollup from counters, excerpts, and index rows.
write_activity_summary() {
local latest_summary_path=$1
local latest_status=$2
local current_summary_status=$3
local line timestamp status screenshot_path summary_path message
{
printf '# Monitor Activity Summary\n\n'
printf '%s\n' "- Run started: $run_started_at"
printf '%s\n' "- Analyzer: $analyzer"
printf '%s\n' "- Interval: ${interval_seconds}s"
printf '%s\n' "- Screenshots attempted: $screenshots_attempted"
printf '%s\n' "- Successful summaries: $successful_summaries"
printf '%s\n' "- Failed summaries: $failed_summaries"
printf '%s\n' "- Current summary updates: $current_summary_updates"
printf '%s\n' "- Current summary failures: $current_summary_failures"
printf '%s\n\n' "- Latest status: $latest_status"
printf '%s\n\n' "- Current summary status: $current_summary_status"
printf '## Latest Summary Detail\n\n'
if [[ -f "$latest_summary_path" ]]; then
summary_excerpt "$latest_summary_path" 80
else
printf 'No summary file exists yet.\n'
fi
printf '\n## Current Summary Detail\n\n'
if [[ -f "$current_summary_file" ]]; then
summary_excerpt "$current_summary_file" 120
else
printf 'No current summary exists yet.\n'
fi
printf '\n## Timeline\n\n'
if [[ -f "$index_file" ]]; then
while IFS=$'\t' read -r timestamp status screenshot_path summary_path message; do
[[ "$timestamp" == "timestamp" ]] && continue
printf '%s\n' "- $timestamp [$status] $summary_path"
if [[ -n "${message:-}" ]]; then
printf ' %s\n' "$message"
fi
done < "$index_file"
fi
} > "$activity_summary_file"
}
# Build the screenshot-analysis prompt sent with an attached image.
codex_prompt() {
cat <<'PROMPT'
Summarize this desktop screenshot for a private local activity journal.
Write a detailed, evidence-dense Markdown record, not a terse caption. When the
image contains enough visible information, aim for roughly 600 to 1000 words.
Use exactly these top-level headings, in this order:
# Screenshot Summary
# Visible Activity
# Notable Changes
# Uncertainty
Under "# Screenshot Summary", explain the overall desktop state in several
paragraphs. Name visible applications, windows, documents, files, browser tabs,
terminal panes, editors, dialogs, notifications, and taskbar/system-tray state
when they can be read. Include enough concrete detail that a future reader can
reconstruct the situation without opening the screenshot.
Under "# Visible Activity", use specific bullets grouped by visible area or
application. Capture visible task context, active files, commands, errors,
URLs/domains, timestamps, selected controls, cursor/focus state, and meaningful
on-screen text. Quote only short visible snippets that are useful for context.
If credential-like, token-like, financial, medical, or other sensitive text is
visible, say that sensitive text appears without reproducing the secret value.
Under "# Notable Changes", describe state that would matter when comparing this
screenshot with the next one: new errors, progress indicators, selected items,
open work surfaces, pending dialogs, or apparent blockers. If there is no prior
screenshot available, say that direct comparison is unavailable and focus on
notable visible state.
Under "# Uncertainty", list anything ambiguous, cropped, too small to read,
hidden behind another window, or inferred only weakly from visible evidence.
Only describe visible evidence. Do not infer private intent, identity,
credentials, or facts that are not visible. Do not claim a task is complete
unless the screenshot shows that result. Return only the Markdown summary.
PROMPT
}
# Build the text-only prompt that updates the run-level current summary.
current_summary_prompt() {
local latest_summary_path=$1
local previous_summary latest_summary
previous_summary=$(cat "$current_summary_file")
latest_summary=$(cat "$latest_summary_path")
cat <<PROMPT
Update the running activity summary for a private local activity journal.
Write a detailed running narrative, not a terse recap. Preserve concrete details
from earlier screenshots while incorporating the latest screenshot analysis.
When there is enough evidence, aim for roughly 700 to 1200 words. Use exactly
these top-level headings, in this order:
# Current Summary
# Recent Activity
# Trend
# Uncertainty
Under "# Current Summary", describe the best current understanding of the work
session from visible evidence only. Keep important application names, active
files, visible commands, browser or document context, errors, progress
indicators, and unresolved blockers. Do not compress away specifics that would
help reconstruct the session later.
Under "# Recent Activity", summarize what the latest screenshot adds or changes.
Call out new visible work surfaces, changed terminal/editor/browser state, new
messages or errors, and whether the latest evidence confirms, contradicts, or
adds nuance to the previous summary.
Under "# Trend", describe the visible direction of the session across time:
repeated work areas, likely active project context, recurring blockers, progress
signals, and shifts between applications. Use cautious language when the trend
is weak.
Under "# Uncertainty", list details that remain ambiguous, unreadable, cropped,
or based on weak visual evidence. If sensitive text appears in the summaries,
avoid reproducing secret values.
Avoid inventing private intent, identity, credentials, or facts that are not
visible in the screenshot summaries. Return only the Markdown summary.
Previous current summary:
$previous_summary
Latest screenshot analysis:
$latest_summary
PROMPT
}
# Invoke Codex CLI for one screenshot and write the per-screenshot summary.
run_codex_analyzer() {
local screenshot_path=$1
local summary_path=$2
local -a command_args
command_args=("$codex_command" exec -c 'approval_policy="never"' --image "$screenshot_path" --sandbox read-only --ephemeral --cd "$REPO_ROOT" --output-last-message "$summary_path")
if [[ -n "$codex_model" ]]; then
command_args+=(--model "$codex_model")
fi
codex_prompt | "${command_args[@]}" -
}
# Invoke Codex CLI without image input to refresh current-summary.md.
run_codex_text_summary() {
local latest_summary_path=$1
local output_path=$2
local -a command_args
command_args=("$codex_command" exec -c 'approval_policy="never"' --sandbox read-only --ephemeral --cd "$REPO_ROOT" --output-last-message "$output_path")
if [[ -n "$codex_model" ]]; then
command_args+=(--model "$codex_model")
fi
current_summary_prompt "$latest_summary_path" | "${command_args[@]}" -
}
# Capture one host desktop screenshot through the configured command.
capture_screenshot() {
local screenshot_path=$1
"$capture_command" "$screenshot_path"
}
# Write the initial current-summary.md before any screenshot has been analyzed.
initialize_current_summary() {
cat > "$current_summary_file" <<'SUMMARY'
# Current Summary
No screenshots have been analyzed yet.
# Recent Activity
No activity has been recorded yet.
# Trend
No trend is available yet.
# Uncertainty
The run has not captured enough evidence to summarize.
SUMMARY
}
# Refresh current-summary.md while preserving the prior summary on failure.
update_current_summary() {
local latest_summary_path=$1
local candidate_path log_path failure_message
candidate_path="$run_dir/current-summary.next.md"
log_path="$run_dir/current-summary.analyzer.log"
if run_codex_text_summary "$latest_summary_path" "$candidate_path" > "$log_path" 2>&1 && [[ -s "$candidate_path" ]]; then
mv "$candidate_path" "$current_summary_file"
current_summary_updates=$((current_summary_updates + 1))
current_summary_status="summary_updated"
else
current_summary_failures=$((current_summary_failures + 1))
failure_message=$(first_log_line "$log_path")
current_summary_status="summary_failed: $failure_message"
fi
}
# Sleep between captures while keeping the live dashboard countdown updated.
wait_for_next_capture() {
local remaining=$1
if [[ "$live_dashboard" == "true" ]]; then
while (( remaining > 0 )); do
render_dashboard "waiting" "waiting" "$latest_screenshot_path" "$latest_summary_path" "$remaining" "$current_summary_status"
"$sleep_command" 1
remaining=$((remaining - 1))
done
else
render_dashboard "waiting" "waiting" "$latest_screenshot_path" "$latest_summary_path" "$remaining" "$current_summary_status"
"$sleep_command" "$remaining"
fi
}
# Run one capture, analysis, current-summary update, and file-rollup cycle.
run_iteration() {
local shot_id screenshot_path summary_path capture_log_path analyzer_log_path failure_message index_message
screenshots_attempted=$((screenshots_attempted + 1))
shot_id="$(filename_datetime_stamp)-$(printf '%04d' "$screenshots_attempted")"
screenshot_path="$run_dir/screenshots/$shot_id.png"
summary_path="$run_dir/summaries/$shot_id.md"
capture_log_path="$run_dir/screenshots/$shot_id.capture.log"
analyzer_log_path="$run_dir/summaries/$shot_id.analyzer.log"
latest_screenshot_path="$screenshot_path"
latest_summary_path="$summary_path"
render_dashboard "capturing screenshot" "capturing" "$screenshot_path" "" "" "$current_summary_status"
if capture_screenshot "$screenshot_path" > "$capture_log_path" 2>&1; then
if [[ ! -s "$screenshot_path" ]]; then
failed_summaries=$((failed_summaries + 1))
latest_status="capture_failed"
failure_message="capture command did not create a non-empty screenshot"
write_capture_failure_summary "$summary_path" "$screenshot_path" "$failure_message"
current_summary_status="skipped after capture failure"
append_index_row "$shot_id" "$latest_status" "$screenshot_path" "$summary_path" "$failure_message"
write_activity_summary "$summary_path" "$latest_status" "$current_summary_status"
render_dashboard "cycle complete" "$latest_status" "$screenshot_path" "$summary_path" "complete" "$current_summary_status"
return 0
fi
else
failed_summaries=$((failed_summaries + 1))
latest_status="capture_failed"
failure_message=$(first_log_line "$capture_log_path")
write_capture_failure_summary "$summary_path" "$screenshot_path" "$failure_message"
current_summary_status="skipped after capture failure"
append_index_row "$shot_id" "$latest_status" "$screenshot_path" "$summary_path" "$failure_message"
write_activity_summary "$summary_path" "$latest_status" "$current_summary_status"
render_dashboard "cycle complete" "$latest_status" "$screenshot_path" "$summary_path" "complete" "$current_summary_status"
return 0
fi
render_dashboard "analyzing screenshot" "analyzing" "$screenshot_path" "$summary_path" "" "$current_summary_status"
if run_codex_analyzer "$screenshot_path" "$summary_path" > "$analyzer_log_path" 2>&1 && [[ -s "$summary_path" ]]; then
successful_summaries=$((successful_summaries + 1))
latest_status="analysis_succeeded"
render_dashboard "updating current summary" "summarizing" "$screenshot_path" "$summary_path" "" "$current_summary_status"
update_current_summary "$summary_path"
index_message="summary written; current summary $current_summary_status"
else
failed_summaries=$((failed_summaries + 1))
latest_status="analysis_failed"
failure_message=$(first_log_line "$analyzer_log_path")
write_failure_summary "$summary_path" "$screenshot_path" "$failure_message"
current_summary_status="skipped after analysis failure"
index_message="$failure_message"
fi
append_index_row "$shot_id" "$latest_status" "$screenshot_path" "$summary_path" "$index_message"
write_activity_summary "$summary_path" "$latest_status" "$current_summary_status"
render_dashboard "cycle complete" "$latest_status" "$screenshot_path" "$summary_path" "complete" "$current_summary_status"
}
# Initialize configuration and artifacts, then run until the requested stop point.
main() {
local env_file output_root
env_file=${MONITOR_ENV_FILE:-$REPO_ROOT/.env}
load_env_file "$env_file"
parse_args "$@"
validate_config
validate_commands
output_root=$(resolve_path "$output_dir")
mkdir -p "$output_root"
run_dir=$(create_run_dir "$output_root")
run_started_at=$(date +%Y-%m-%dT%H:%M:%S%z)
index_file="$run_dir/index.tsv"
activity_summary_file="$run_dir/activity-summary.md"
current_summary_file="$run_dir/current-summary.md"
screenshots_attempted=0
successful_summaries=0
failed_summaries=0
current_summary_updates=0
current_summary_failures=0
latest_screenshot_path=""
latest_summary_path=""
latest_status="starting"
current_summary_status="not started"
initialize_display
initialize_current_summary
printf 'timestamp\tstatus\tscreenshot_path\tsummary_path\tmessage\n' > "$index_file"
write_activity_summary "" "$latest_status" "$current_summary_status"
render_dashboard "starting" "$latest_status" "" "" "" "$current_summary_status"
while :; do
run_iteration
if [[ -n "$count_limit" && "$screenshots_attempted" -ge "$count_limit" ]]; then
break
fi
if [[ -n "$test_stop_after_iterations" && "$screenshots_attempted" -ge "$test_stop_after_iterations" ]]; then
break
fi
wait_for_next_capture "$interval_seconds"
done
render_dashboard "complete" "complete" "$latest_screenshot_path" "$latest_summary_path" "complete" "$current_summary_status"
print_final_detailed_summary
}
main "$@"