-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathupgrade.sh
More file actions
executable file
·1411 lines (1253 loc) · 57.2 KB
/
Copy pathupgrade.sh
File metadata and controls
executable file
·1411 lines (1253 loc) · 57.2 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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
#
# wp-coding-agents upgrade script
# Safely upgrade a live wp-coding-agents install without touching user state.
#
# Phases:
# 1. Detect environment (auto-detects local vs VPS, runtime, chat bridge —
# supports kimaki, cc-connect, telegram).
# 2. Update setup-installed Data Machine plugins to latest tagged releases,
# sync carried provider plugins, and sync WP Codebox (subtree-packaged)
# to its latest tag when installed.
# 3. Sync chat-bridge config (dispatches per bridge)
# kimaki:
# VPS: /opt/kimaki-config (plugins + post-upgrade.sh + skill allowlist)
# Local: $KIMAKI_DATA_DIR/kimaki-config/ for plugins,
# post-upgrade.sh + skill allowlist, and runs post-upgrade.sh inline (no launchd
# ExecStartPre hook).
# cc-connect: no per-install artifacts; reports binary version and
# reminds user to `npm update -g cc-connect`.
# telegram: no per-install artifacts; reports binary versions and
# reminds user to `npm update -g @grinev/opencode-telegram-bot`.
# 4. Sync the wp-coding-agents upgrade skill
# 5. Regenerate AGENTS.md via Data Machine compose
# 6. Smart systemd update (VPS only; dispatches per bridge)
# kimaki → kimaki.service
# cc-connect → cc-connect.service
# telegram → opencode-serve.service + opencode-telegram.service
# Each unit's existing Environment= lines are preserved (host custom
# values, secrets) while structural lines are refreshed from the same
# template the install path uses (bridges/<name>.sh::bridge_render_*).
# 7. Remove legacy opencode-claude-auth bash wrapper, if any (#117)
# 8. Summary — prints the right restart + verify commands per bridge × env.
#
# Usage:
# ./upgrade.sh # run all phases (auto-detects environment)
# ./upgrade.sh --dry-run # preview without changes
# ./upgrade.sh --kimaki-only # only sync kimaki config + plugins
# ./upgrade.sh --plugins-only # only update Data Machine plugins
# ./upgrade.sh --skills-only # only sync the wp-coding-agents upgrade skill
# ./upgrade.sh --agents-md-only # only regenerate AGENTS.md
# ./upgrade.sh --local --wp-path <path> # local install (auto on macOS)
#
# Safety: NEVER touches WordPress DB, nginx, SSL, ~/.kimaki/ auth state,
# the DM workspace cloned repos, agent memory files, or the running
# chat-bridge service.
#
# opencode.json is touched by default in additive mode: managed plugin
# entries the user is missing get added (dm-context-filter.ts and
# dm-agent-sync.ts on Kimaki bridges), and legacy
# `agent.build.prompt`/`agent.plan.prompt` keys get migrated to a top-level
# `instructions` array (fixes Anthropic Claude Max OAuth, see
# wp-coding-agents#60). User-added plugin entries are left alone.
#
# --repair-opencode-json upgrades the repair to full reconciliation:
# the `plugin` array is replaced with exactly what setup would produce
# today, removing any unexpected entries in addition to the additive
# behaviour above. Use this when you've intentionally pruned plugins
# the user added by hand.
#
# A .backup.<ts> is written alongside in both modes.
#
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
# Source shared modules (common, detect needed for environment resolution;
# wordpress is needed for wp_cmd helper used by compose and plugin updates).
for lib in common detect source-policy service-migration wordpress data-machine carried-plugins wp-codebox homeboy ai-gateway skills cli-transport cli-channel runtime-signature runtime-guard agents-md-guidance agents-md-backups; do
source "$SCRIPT_DIR/lib/${lib}.sh"
done
# Bridge dispatcher — auto-discovers bridges/*.sh. Each bridge owns its own
# render templates, sync, systemd/launchd update, and summary blocks.
# shellcheck disable=SC1091
source "$SCRIPT_DIR/bridges/_dispatch.sh"
# Guidance dispatcher — auto-discovers guidance/*.sh AGENTS.md section units.
# Adding a section is "drop a file in guidance/" — no edit here.
# shellcheck disable=SC1091
source "$SCRIPT_DIR/guidance/_dispatch.sh"
source "$SCRIPT_DIR/services/datamachine-worker.sh"
# Discover available runtimes
AVAILABLE_RUNTIMES=()
for runtime_file in "$SCRIPT_DIR"/runtimes/*.sh; do
[ -f "$runtime_file" ] || continue
AVAILABLE_RUNTIMES+=("$(basename "$runtime_file" .sh)")
done
# ============================================================================
# Parse arguments
# ============================================================================
DRY_RUN=false
KIMAKI_ONLY=false
PLUGINS_ONLY=false
SKILLS_ONLY=false
AGENTS_MD_ONLY=false
REPAIR_OPENCODE_JSON=false
SKIP_PLUGINS=false
WITH_AI_GATEWAY=false
WITH_CLAUDE_CODE_AUTH=true
ROTATE_AI_GATEWAY_TOKEN=false
SHOW_HELP=false
SOURCE_MODE=""
SOURCE_MODE_EXPLICIT=false
OWNED_SOURCES=""
OWNED_SOURCES_EXPLICIT=false
OWNED_WRITABLE=""
OWNED_WRITABLE_EXPLICIT=false
SOURCE_LOG_PATHS=""
SOURCE_LOG_PATHS_EXPLICIT=false
# Defaults setup.sh expects (detect.sh reads these)
LOCAL_MODE=false
SKIP_DEPS=true
SKIP_SSL=true
INSTALL_DATA_MACHINE=true
INSTALL_CHAT=true
INSTALL_SKILLS=true
RUN_AS_ROOT=true
REQUIRE_ROOT_DURING_DETECT=false
MULTISITE=false
MULTISITE_TYPE="subdirectory"
MODE="existing"
RUNTIME=""
DETECTED_RUNTIMES=()
IS_STUDIO=false
CHAT_BRIDGE=""
HOMEBOY_MODE="${HOMEBOY_MODE:-auto}"
WITH_HOMEBOY="${WITH_HOMEBOY:-false}"
# True when the operator forced the identity via --root / --non-root.
# Suppresses adopt_service_identity_from_units (existing-unit adoption).
SERVICE_USER_FORCED=false
# Set by --migrate-non-root: move an already-installed root agent onto a
# dedicated non-root service user, carrying its state across. See #93.
MIGRATE_NON_ROOT=false
MIGRATE_TARGET_USER="$SERVICE_MIGRATION_DEFAULT_USER"
initialize_kimaki_overrides
while [[ $# -gt 0 ]]; do
case $1 in
--dry-run) DRY_RUN=true; shift ;;
--kimaki-only) KIMAKI_ONLY=true; shift ;;
--plugins-only) PLUGINS_ONLY=true; shift ;;
--skills-only) SKILLS_ONLY=true; shift ;;
--agents-md-only) AGENTS_MD_ONLY=true; shift ;;
--repair-opencode-json) REPAIR_OPENCODE_JSON=true; shift ;;
--skip-plugins) SKIP_PLUGINS=true; shift ;;
--with-ai-gateway) WITH_AI_GATEWAY=true; shift ;;
--with-claude-code-auth) WITH_CLAUDE_CODE_AUTH=true; shift ;;
--no-claude-code-auth) WITH_CLAUDE_CODE_AUTH=false; shift ;;
--ai-gateway-provider) AI_GATEWAY_ROUTE_PROVIDER="$2"; shift 2 ;;
--ai-gateway-model) AI_GATEWAY_ROUTE_MODEL="$2"; shift 2 ;;
--ai-gateway-opencode-model) AI_GATEWAY_MODEL_ID="$2"; shift 2 ;;
--rotate-ai-gateway-token) ROTATE_AI_GATEWAY_TOKEN=true; shift ;;
--source-mode|--posture) SOURCE_MODE="$2"; SOURCE_MODE_EXPLICIT=true; shift 2 ;;
--owned-source|--managed-source) OWNED_SOURCES="${OWNED_SOURCES}${OWNED_SOURCES:+ }$2"; OWNED_SOURCES_EXPLICIT=true; shift 2 ;;
--owned-writable|--managed-writable) OWNED_WRITABLE="${OWNED_WRITABLE}${OWNED_WRITABLE:+ }$2"; OWNED_WRITABLE_EXPLICIT=true; shift 2 ;;
--log-path) SOURCE_LOG_PATHS="${SOURCE_LOG_PATHS}${SOURCE_LOG_PATHS:+ }$2"; SOURCE_LOG_PATHS_EXPLICIT=true; shift 2 ;;
--runtime) RUNTIME="$2"; shift 2 ;;
--wp-path) EXISTING_WP="$2"; shift 2 ;;
--agent-slug) AGENT_SLUG="$2"; AGENT_SLUG_EXPLICIT=true; shift 2 ;;
--kimaki-unit) KIMAKI_UNIT="$2"; KIMAKI_UNIT_EXPLICIT=true; shift 2 ;;
--kimaki-data-dir) KIMAKI_DATA_DIR="$2"; KIMAKI_DATA_DIR_EXPLICIT=true; shift 2 ;;
--kimaki-lock-port) KIMAKI_LOCK_PORT="$2"; KIMAKI_LOCK_PORT_EXPLICIT=true; shift 2 ;;
--local) LOCAL_MODE=true; RUN_AS_ROOT=false; shift ;;
--root) RUN_AS_ROOT=true; SERVICE_USER_FORCED=true; shift ;;
--non-root) RUN_AS_ROOT=false; SERVICE_USER_FORCED=true; shift ;;
--migrate-non-root) MIGRATE_NON_ROOT=true; RUN_AS_ROOT=false; SERVICE_USER_FORCED=true; shift ;;
--migrate-user) MIGRATE_TARGET_USER="$2"; shift 2 ;;
--migrate-extra) service_migration_add_extra_path "$2"; shift 2 ;;
--help|-h) SHOW_HELP=true; shift ;;
*) shift ;;
esac
done
if [ "$SHOW_HELP" = true ]; then
cat << HELP
wp-coding-agents upgrade script
Safely upgrade a live install without touching user state.
USAGE:
./upgrade.sh Run all phases (auto-detects local vs VPS)
./upgrade.sh --dry-run Preview what would change
./upgrade.sh --kimaki-only Only sync chat-bridge config (kept name for
backwards compat — also handles cc-connect
and telegram when they are the detected bridge)
./upgrade.sh --plugins-only Only update setup-installed Data Machine plugins
./upgrade.sh --skills-only Only sync the wp-coding-agents upgrade skill
./upgrade.sh --agents-md-only Only regenerate AGENTS.md
./upgrade.sh --skip-plugins Skip Data Machine plugin updates during full run
./upgrade.sh --repair-opencode-json
Full reconciliation of opencode.json:
- plugin array → match current setup exactly
(adds missing + removes unexpected)
- agent.build.prompt → instructions array
(fixes Anthropic Claude Max OAuth, #60)
Writes a .backup.<ts> alongside.
Default upgrade behaviour is additive repair:
only adds missing managed entries, never
removes user-added plugins.
./upgrade.sh --runtime <name> Force runtime (auto-detected otherwise)
./upgrade.sh --source-mode <name>
Where code changes land: workspace | owned
(default: the mode recorded at setup time).
Two shapes, not two levels. --posture is
accepted as a deprecated alias.
./upgrade.sh --owned-source <path>
wp-content path this site owns and may edit under
--source-mode owned. Repeatable. Replaces the
recorded set when supplied.
./upgrade.sh --wp-path <path> Override detected WordPress path
./upgrade.sh --agent-slug <s> Override Data Machine agent slug
./upgrade.sh --kimaki-unit <u> Target Kimaki systemd unit
./upgrade.sh --kimaki-data-dir <path>
Override the selected Kimaki state directory
./upgrade.sh --kimaki-lock-port <port>
Override the selected Kimaki lock port
./upgrade.sh --local Local mode (no systemd; auto-on on macOS)
./upgrade.sh --root Force root service identity (skips adoption
of the existing unit's User=)
./upgrade.sh --non-root Force non-root service identity (User=opencode)
./upgrade.sh --with-ai-gateway
Opt in to additive WP AI Gateway integration
for OpenCode: install/activate gateway stack,
configure route, reuse existing token env, and
merge a wp-ai-gateway OpenAI-compatible provider
into opencode.json.
./upgrade.sh --with-ai-gateway --rotate-ai-gateway-token
Explicitly mint a replacement gateway token.
./upgrade.sh --with-ai-gateway --ai-gateway-provider openai --ai-gateway-model gpt-4o-mini
Configure the WordPress gateway backend route.
./upgrade.sh --no-claude-code-auth
Skip direct OpenCode Claude Pro/Max auth.
The managed auth plugin is installed by default
for OpenCode runtimes.
SERVICE IDENTITY:
By default the upgrade adopts the service user from the EXISTING
installed systemd unit (its User= line) rather than assuming root.
The upgrade never changes the service identity implicitly; use
--root / --non-root to change it deliberately.
./upgrade.sh --migrate-non-root
Move an install that currently runs as root
onto a dedicated non-root service user,
carrying the agent's state across. Use this
rather than --non-root, which only re-renders
the unit and would strand the agent's state
in /root.
./upgrade.sh --migrate-user <name>
Target user for --migrate-non-root
(default: $SERVICE_MIGRATION_DEFAULT_USER).
./upgrade.sh --migrate-extra <path>
Carry an additional service-home-relative path
across. Repeatable. For install-specific state
the shipped inventory cannot know about.
Credential-shaped paths are refused.
What migrates is an explicit, mode-aware allowlist: runtime state
under every mode, plus the dev toolchain and forge credentials under
workspace mode only. SSH keys, secret stores, and shell history are
never migrated — they stay behind in root-owned /root, out of the agent's
reach. That is the point of the migration, not a side effect.
SUPPORTED CHAT BRIDGES:
kimaki, cc-connect, telegram (auto-detected per environment)
KIMAKI PLUGIN INSTALL TARGETS:
VPS: /opt/kimaki-config/plugins
Local: \$KIMAKI_DATA_DIR/kimaki-config/plugins
NEVER TOUCHED:
- CLAUDE.md runtime config
- WordPress database, nginx, SSL certs
- ~/.kimaki/ auth state and OAuth tokens
- DM workspace cloned repos
- Agent memory files (SOUL.md, MEMORY.md, USER.md, etc.)
- Running chat-bridge service (never restarted automatically)
DEFAULT TOUCHES:
- data-machine and data-machine-code — updates setup-installed git
checkouts to their latest version tags. Non-git plugin directories are
skipped. Carried provider plugins are synced from this repo when their
runtime is present. Use --skip-plugins to skip this phase.
- opencode.json — additive repair. Adds managed plugin entries the
user is missing (dm-context-filter.ts and dm-agent-sync.ts on Kimaki
bridges) and migrates "agent.build.prompt" to top-level "instructions"
(fixes Anthropic Claude Max OAuth). Never removes user-added plugins.
Preserves all other keys. Writes a .backup.<ts> alongside.
- AGENTS.md.backup.* — prunes old generated backups after successful
AGENTS.md regeneration. Defaults: keep latest 5 and remove older extras
after 30 days. Override with AGENTS_MD_BACKUP_KEEP and
AGENTS_MD_BACKUP_MAX_AGE_DAYS.
OPT-IN TOUCHES:
- opencode.json (--repair-opencode-json) — full reconcile. In addition
to the additive behaviour above, removes unexpected plugin entries
so the array matches exactly what setup would produce today.
- WP AI Gateway (--with-ai-gateway) — installs/updates wp-ai-gateway and
ai-provider-for-openai, configures the gateway route, writes/reuses
.opencode/wp-ai-gateway.env, and additively merges provider.wp-ai-gateway
into opencode.json. Existing gateway tokens are reused unless
--rotate-ai-gateway-token is also passed.
- OpenCode Claude Code auth — installs a managed OpenCode plugin under
.opencode/plugins and adds it to opencode.json so direct OpenCode can
authenticate with Claude Pro/Max OAuth. Use --no-claude-code-auth to skip.
HELP
exit 0
fi
if [ "$PLUGINS_ONLY" = true ] && [ "$SKIP_PLUGINS" = true ]; then
error "Cannot combine --plugins-only and --skip-plugins"
fi
# ============================================================================
# Phase 1: Detect environment
# ============================================================================
log "Phase 1: Detecting environment..."
# Auto-detect EXISTING_WP if not provided.
# Priority: env var → scan /var/www for wp-config.php → fail.
if [ -z "$EXISTING_WP" ]; then
if [ "$LOCAL_MODE" = true ]; then
error "Local mode requires --wp-path <path> or EXISTING_WP env var"
fi
# A host may serve several sites. Selecting the first glob result is unsafe.
wp_candidates=()
for candidate in /var/www/*/; do
if [ -f "$candidate/wp-config.php" ]; then
wp_candidates+=("${candidate%/}")
fi
done
if [ ${#wp_candidates[@]} -eq 1 ]; then
EXISTING_WP="${wp_candidates[0]}"
log "Auto-detected WordPress at: $EXISTING_WP"
elif [ ${#wp_candidates[@]} -gt 1 ]; then
error "Multiple WordPress installs found under /var/www. Pass --wp-path <path>: ${wp_candidates[*]}"
fi
if [ -z "$EXISTING_WP" ]; then
error "Could not auto-detect WordPress path. Pass --wp-path <path> or set EXISTING_WP."
fi
fi
# Auto-detect runtime(s). Same model as setup.sh: DETECTED_RUNTIMES is the
# full list (drives multi-runtime skills install); RUNTIME is the primary
# (first-match cascade: claude-code > opencode > codex). Explicit --runtime
# narrows to a single runtime.
if [ -n "$RUNTIME" ]; then
DETECTED_RUNTIMES=("$RUNTIME")
else
if command -v claude &>/dev/null; then
DETECTED_RUNTIMES+=("claude-code")
fi
if command -v opencode &>/dev/null; then
DETECTED_RUNTIMES+=("opencode")
fi
if command -v codex &>/dev/null; then
DETECTED_RUNTIMES+=("codex")
fi
if [ ${#DETECTED_RUNTIMES[@]} -eq 0 ]; then
warn "No runtime binary found — defaulting to opencode"
DETECTED_RUNTIMES=("opencode")
fi
RUNTIME="${DETECTED_RUNTIMES[0]}"
fi
RUNTIME_FILE="$SCRIPT_DIR/runtimes/${RUNTIME}.sh"
if [ ! -f "$RUNTIME_FILE" ]; then
error "Unknown runtime: $RUNTIME. Available: ${AVAILABLE_RUNTIMES[*]}"
fi
source "$RUNTIME_FILE"
# Run detect_environment first — it auto-sets LOCAL_MODE=true on macOS,
# which the chat bridge detection below depends on to pick the right branch.
detect_environment
# The source mode drives the plugin set, every runtime permission surface, and the
# AGENTS.md guidance. Resolve it from the value recorded at setup time so an
# upgrade converges a managed install instead of silently reverting it to
# engineering; --posture overrides and re-records.
source_policy_resolve_mode
source_policy_resolve_owned_sources
source_policy_resolve_writable_paths
source_policy_resolve_log_paths
source_policy_assert_runtime_supports_mode
source_policy_record_mode
source_policy_record_owned_sources
source_policy_record_writable_paths
source_policy_record_log_paths
# Detect chat bridge from installed services / installed binaries via the
# bridges/_dispatch.sh registry walk. See bridge_detect_local /
# bridge_detect_vps for the full probe order (launchd plists + command -v
# on local; systemd unit files on VPS). Priority order is set by
# BRIDGE_DETECTION_ORDER in _dispatch.sh: kimaki > cc-connect > telegram.
#
# Codex has no managed bridge in wp-coding-agents today. An explicit
# `--runtime codex` upgrade should sync Codex-owned files only, not pick up an
# unrelated local Kimaki/cc-connect install and rewrite its config.
if [ "$RUNTIME" = "codex" ]; then
CHAT_BRIDGE=""
elif [ "$LOCAL_MODE" = true ]; then
CHAT_BRIDGE=$(bridge_detect_local)
else
CHAT_BRIDGE=$(bridge_detect_vps)
fi
# Load the active bridge's hooks (render, sync, update, summary) into this
# shell so the rest of upgrade.sh can call bridge_sync_config /
# bridge_update_systemd / bridge_render_systemd directly. No-op when
# detection found nothing — phase functions guard on $CHAT_BRIDGE.
if [ -n "$CHAT_BRIDGE" ] && bridge_file "$CHAT_BRIDGE" >/dev/null 2>&1; then
bridge_load "$CHAT_BRIDGE"
fi
if [ "$CHAT_BRIDGE" = "kimaki" ] && [ "$LOCAL_MODE" = false ]; then
_kimaki_resolve_instance
fi
# On upgrade, the installed unit's User= is the source of truth for the
# service identity. upgrade.sh defaults RUN_AS_ROOT=true, which on a
# non-root install (User=opencode) made Phase 5 silently rewrite the unit
# to User=root — root-owned state files, broken next non-root start, and
# the root-homed-path dispatch trap (#198/#93) all over again. See #204.
# --root / --non-root force an explicit identity and skip adoption.
adopt_service_identity_from_units
if [ "$DRY_RUN" = false ] && [ "$LOCAL_MODE" = false ] && [ "$RUN_AS_ROOT" = true ] && [ "$EUID" -ne 0 ]; then
error "Please run as root (sudo ./upgrade.sh), or use --non-root for installs whose service and WordPress files are writable by the current user."
fi
# Service identity, as the units on disk actually have it. --non-root and
# --migrate-non-root both set SERVICE_USER_FORCED=true, which suppresses
# adoption above, so this is the only thing that still knows what the install is
# running as TODAY — which both branches below need. Read-only.
INSTALLED_SERVICE_USER="$(service_migration_installed_user)"
# --non-root alone only forces the identity the units are RENDERED with. On an
# install already running as root that is a footgun (#93): the service user may
# not exist, and KIMAKI_DATA_DIR is derived from the service home, so the agent
# gets repointed at an empty home while its session database, runtime auth, and
# toolchains stay behind in /root. Refuse early, before any mutation, and name
# the flag that does it properly rather than render a broken unit.
if [ "$MIGRATE_NON_ROOT" = false ] && [ "$LOCAL_MODE" = false ] && \
[ "$RUN_AS_ROOT" = false ] && [ "$INSTALLED_SERVICE_USER" = "root" ]; then
error "This install currently runs as root. --non-root only re-renders the unit; it would not create the service user or carry the agent's state across, leaving the service pointed at an empty home. Use --migrate-non-root to move it properly."
fi
log "Runtime: $RUNTIME"
log "Chat bridge: ${CHAT_BRIDGE:-none detected}"
log "Site path: $SITE_PATH"
log "Service: $SERVICE_USER"
if [ "$CHAT_BRIDGE" = "kimaki" ]; then
log "Kimaki unit: $KIMAKI_UNIT"
log "Kimaki data: $KIMAKI_DATA_DIR"
[ -z "$KIMAKI_LOCK_PORT" ] || log "Kimaki lock: $KIMAKI_LOCK_PORT"
fi
if [ "$DRY_RUN" = true ]; then
log "Dry-run mode: no changes will be made"
fi
echo ""
# Track what was touched for the summary
UPDATED_ITEMS=()
# Service identity migration (#93). Runs before any phase that renders a unit or
# writes into the service home, so everything downstream sees the new identity.
# Deliberately after UPDATED_ITEMS is declared — it reports into the summary.
if [ "$MIGRATE_NON_ROOT" = true ]; then
if [ -z "$INSTALLED_SERVICE_USER" ]; then
error "--migrate-non-root found no installed systemd unit to migrate. Use ./setup.sh --non-root for a fresh install."
elif [ "$INSTALLED_SERVICE_USER" != "root" ]; then
log "Install already runs as '$INSTALLED_SERVICE_USER' — nothing to migrate."
MIGRATE_NON_ROOT=false
else
service_migration_preflight "$MIGRATE_TARGET_USER" "/root" "$SOURCE_MODE"
service_migration_run "$MIGRATE_TARGET_USER" "/root" "$SOURCE_MODE"
UPDATED_ITEMS+=("Service identity migrated: root -> $SERVICE_USER")
fi
elif [ "$LOCAL_MODE" = false ] && [ "$SOURCE_MODE" = "owned" ] && \
[ "$INSTALLED_SERVICE_USER" = "root" ]; then
# Owned mode now defaults to non-root on fresh installs (#327), but an
# existing install is NEVER flipped implicitly — that is the #204 rule, and
# here it would additionally strand the agent's state in /root. Recommend the
# migration and let the operator choose when to take the service down.
warn "This owned-mode install runs as root. Fresh owned installs now default to"
warn "a non-root service user: the edit denies are a guardrail, not containment,"
warn "and a root service can reach every denied path through bash or wp eval."
warn "Migrate when convenient: sudo ./upgrade.sh --migrate-non-root"
fi
# Set true when opencode.json is found to have plugin-array drift and the
# --repair-opencode-json flag was NOT passed. Shown loudly in print_summary.
OPENCODE_JSON_DRIFT=false
# Set by the Kimaki bridge when a non-root upgrade cannot prove or repair the
# root-owned dispatch wrapper, target, and sudoers installation.
KIMAKI_DISPATCH_ROOT_REPAIR_REQUIRED=false
KIMAKI_DISPATCH_ROOT_REPAIR_COMMAND=""
# ============================================================================
# Helpers
# ============================================================================
_run_filter_active() {
# Returns 0 if the given phase should run given the *-only flags.
# Usage: _run_filter_active <flag_name> (e.g. KIMAKI_ONLY)
local phase="$1"
# If any --*-only flag is set, only that one runs
if [ "$KIMAKI_ONLY" = true ] || [ "$PLUGINS_ONLY" = true ] || [ "$SKILLS_ONLY" = true ] || [ "$AGENTS_MD_ONLY" = true ]; then
case "$phase" in
kimaki) [ "$KIMAKI_ONLY" = true ]; return $? ;;
opencode-json) [ "$KIMAKI_ONLY" = true ]; return $? ;;
plugins) [ "$PLUGINS_ONLY" = true ]; return $? ;;
skills) [ "$SKILLS_ONLY" = true ]; return $? ;;
agents-md) [ "$AGENTS_MD_ONLY" = true ]; return $? ;;
transport|systemd|patch) return 1 ;; # infrastructure phases skipped in *-only modes
*) return 1 ;;
esac
fi
if [ "$phase" = plugins ] && [ "$SKIP_PLUGINS" = true ]; then
return 1
fi
return 0
}
# ============================================================================
# Phase 2: Update Data Machine plugins
# ============================================================================
update_data_machine_plugins() {
_run_filter_active plugins || return 0
upgrade_data_machine_plugins
sync_carried_plugins
update_wp_codebox_plugin_subtree
}
configure_homeboy_dmc_worktree_provider_phase() {
_run_filter_active plugins || return 0
configure_homeboy_dmc_worktree_provider
}
sync_cli_transport_runtime() {
_run_filter_active transport || return 0
log "Phase 2b: Syncing CLI dispatch transport..."
cli_transport_install
runtime_guard_sync
}
update_ai_gateway() {
_run_filter_active plugins || return 0
upgrade_ai_gateway
}
# ============================================================================
# Phase 3: Sync chat-bridge config
# kimaki → plugins + post-upgrade.sh + skills-enable-list (see below).
# cc-connect → no per-install artifacts beyond the npm package; config.toml
# is user-owned. Report version and remind user to
# `npm update -g cc-connect` for upstream updates.
# telegram → no per-install artifacts beyond the npm package; .env files
# contain user secrets and are not touched. Report versions
# and remind user to `npm update -g @grinev/opencode-telegram-bot`.
# ============================================================================
sync_chat_bridge_config() {
_run_filter_active kimaki || return 0
if [ -z "$CHAT_BRIDGE" ]; then
log "Phase 3: Skipping (no chat bridge detected)"
return
fi
if ! bridge_has_hook sync_config; then
warn "Phase 3: $CHAT_BRIDGE does not implement bridge_sync_config — skipping"
return
fi
bridge_sync_config
}
# ============================================================================
# Phase 3b: Detect + optionally repair opencode.json drift
#
# opencode.json is user-owned. Additive repair preserves user entries while
# synchronizing wp-coding-agents-owned plugins, instructions, migrations, and
# protected WordPress edit rules; full repair additionally removes unexpected
# managed-array entries.
#
# Drift vectors checked:
# 1. `plugin` array — matches expected plugins for the detected runtime
# and chat bridge. Only applies when runtime is opencode.
# 2. `agent.build.prompt` / `agent.plan.prompt` — legacy format that
# breaks Anthropic Claude Max OAuth (see wp-coding-agents#60). Migrated
# to a top-level `instructions` array. This check runs for ALL runtimes
# because opencode.json can exist even when the primary runtime is
# claude-code (e.g. kimaki spawns opencode sessions).
# 3. Data Machine instruction paths.
# 4. OpenCode edit denies for installed WordPress source.
#
# With --repair-opencode-json, all drift vectors are repaired surgically.
# All other keys are preserved. A .backup.<ts> is written alongside.
# ============================================================================
upgrade_opencode_claude_code_auth_plugin_path() {
printf '%s/.opencode/plugins/claude-code-auth.ts' "$SITE_PATH"
}
upgrade_install_opencode_claude_code_auth_plugin() {
[ "${WITH_CLAUDE_CODE_AUTH:-false}" = true ] || return 0
local plugin_path plugins_dir source_path
plugin_path="$(upgrade_opencode_claude_code_auth_plugin_path)"
plugins_dir="$(dirname "$plugin_path")"
source_path="$SCRIPT_DIR/runtimes/opencode/plugins/claude-code-auth.ts"
if [ ! -f "$source_path" ]; then
warn "Phase 3b: $source_path not found — skipping Claude Code auth OpenCode plugin sync"
return 0
fi
if [ "$DRY_RUN" = true ]; then
echo -e "${BLUE}[dry-run]${NC} Would install Claude Code auth OpenCode plugin at $plugin_path"
return 0
fi
mkdir -p "$plugins_dir"
if [ -f "$plugin_path" ] && cmp -s "$source_path" "$plugin_path"; then
return 0
fi
cp "$source_path" "$plugin_path"
service_file_normalize_perms "$plugin_path"
UPDATED_ITEMS+=("OpenCode Claude Code auth plugin ($plugin_path)")
}
check_opencode_json_drift() {
_run_filter_active opencode-json || return 0
# Runs whenever opencode.json exists on disk. Default behaviour is
# additive repair: managed plugin entries the user is missing get added
# (dm-context-filter.ts and dm-agent-sync.ts on Kimaki bridges), and
# legacy agent.build.prompt / agent.plan.prompt get migrated to a
# top-level `instructions` array (fixes Anthropic Claude Max OAuth,
# wp-coding-agents#60).
#
# User-added plugin entries are left alone in additive mode. If any are
# present after the repair the user is told to re-run with
# --repair-opencode-json for the full reconciliation, which removes
# unexpected entries too.
#
# Why additive is the default: dm-context-filter.ts is a security policy
# plugin (it strips cross-channel routing discovery from Kimaki system
# prompts). Installs that predate the filter, or were bootstrapped before
# kimaki was the chat bridge, must not be left without it just because
# the user never knew to pass an opt-in flag. See wp-coding-agents#67.
local OPENCODE_JSON_FILE="$SITE_PATH/opencode.json"
if [ ! -f "$OPENCODE_JSON_FILE" ]; then
return 0
fi
local HELPER="$SCRIPT_DIR/lib/repair-opencode-json.py"
# Owned-source allow rules the reconciler must (re)write. Empty under
# engineering, so the argument list is unchanged there.
local _owned_source_args=()
local _owned_path
while IFS= read -r _owned_path; do
[ -n "$_owned_path" ] || continue
_owned_source_args+=(--owned-source "$_owned_path")
done < <(source_policy_owned_sources)
while IFS= read -r _owned_path; do
[ -n "$_owned_path" ] || continue
_owned_source_args+=(--owned-writable "$_owned_path")
done < <(source_policy_writable_paths)
while IFS= read -r _owned_path; do
[ -n "$_owned_path" ] || continue
_owned_source_args+=(--log-path "$_owned_path")
done < <(source_policy_log_paths)
if source_policy_workspace_enabled; then
_owned_source_args+=(--workspace-dir "$DM_WORKSPACE_DIR")
fi
if [ ! -f "$HELPER" ]; then
warn "Phase 3b: $HELPER not found — skipping drift check"
return 0
fi
local BRIDGE_ARG="${CHAT_BRIDGE:-none}"
# Kimaki plugins dir — match what bridges/kimaki.sh::bridge_sync_config resolved.
local PLUGINS_DIR="${RESOLVED_KIMAKI_PLUGINS_DIR:-/opt/kimaki-config/plugins}"
upgrade_install_opencode_claude_code_auth_plugin
local CLAUDE_CODE_AUTH_PLUGIN=""
local claude_code_auth_args=()
if [ "${WITH_CLAUDE_CODE_AUTH:-false}" = true ]; then
CLAUDE_CODE_AUTH_PLUGIN="$(upgrade_opencode_claude_code_auth_plugin_path)"
claude_code_auth_args=(--claude-code-auth-plugin "$CLAUDE_CODE_AUTH_PLUGIN")
fi
# Runtime arg for repair-opencode-json.py: always `opencode` when the file
# exists. The primary RUNTIME may be `claude-code`, but the presence of
# opencode.json on disk means opencode IS in use — otherwise the file wouldn't
# be there. expected_plugins() skips plugin-array drift entirely for
# non-opencode runtimes, which would silently mask real drift here.
local RUNTIME_ARG="opencode"
local MANAGED_INSTRUCTIONS_FILE=""
local AGENT_FOR_INSTRUCTIONS=""
AGENT_FOR_INSTRUCTIONS=$(python3 - "$OPENCODE_JSON_FILE" <<'PY' 2>/dev/null || true
import json
import re
import sys
with open(sys.argv[1], encoding="utf-8") as handle:
data = json.load(handle)
for item in data.get("instructions", []):
if not isinstance(item, str):
continue
match = re.search(r"(?:^|/)agents/([^/]+)/", item)
if match:
print(match.group(1))
break
PY
)
if [ -n "$AGENT_FOR_INSTRUCTIONS" ]; then
local injectable_raw injectable_json
injectable_raw=$($WP_CMD datamachine memory injectable-files --format=json --agent="$AGENT_FOR_INSTRUCTIONS" --path="$SITE_PATH" $WP_ROOT_FLAG 2>/dev/null || echo "")
injectable_json=$(echo "$injectable_raw" | sed -n '/^\[/,/^\]/p')
if [ -n "$injectable_json" ]; then
MANAGED_INSTRUCTIONS_FILE=$(mktemp)
echo "$injectable_json" | python3 -c "
import sys, json
data = json.load(sys.stdin)
for item in data:
path = item.get('path')
if path:
print(path)
" > "$MANAGED_INSTRUCTIONS_FILE"
fi
fi
# Mode: --apply (full reconcile, opt-in) or --additive (default).
local MODE_FLAG="--additive"
local MODE_LABEL="additive repair"
if [ "$REPAIR_OPENCODE_JSON" = true ]; then
MODE_FLAG="--apply"
MODE_LABEL="full repair"
fi
log "Phase 3b: opencode.json $MODE_LABEL..."
if [ "$DRY_RUN" = true ]; then
local owned_arg_display=""
if [ -n "$MANAGED_INSTRUCTIONS_FILE" ]; then
owned_arg_display=" --managed-instructions-file $MANAGED_INSTRUCTIONS_FILE"
fi
local claude_auth_arg_display=""
if [ -n "$CLAUDE_CODE_AUTH_PLUGIN" ]; then
claude_auth_arg_display=" --claude-code-auth-plugin $CLAUDE_CODE_AUTH_PLUGIN"
fi
echo -e "${BLUE}[dry-run]${NC} Would run: python3 $HELPER --file $OPENCODE_JSON_FILE --runtime $RUNTIME_ARG --chat-bridge $BRIDGE_ARG --source-mode ${SOURCE_MODE:-workspace} --kimaki-plugins-dir $PLUGINS_DIR$claude_auth_arg_display$owned_arg_display $MODE_FLAG"
local dry_out
local managed_args=()
if [ -n "$MANAGED_INSTRUCTIONS_FILE" ]; then
managed_args=(--managed-instructions-file "$MANAGED_INSTRUCTIONS_FILE")
fi
dry_out=$(python3 "$HELPER" \
--file "$OPENCODE_JSON_FILE" \
--runtime "$RUNTIME_ARG" \
--chat-bridge "$BRIDGE_ARG" \
--source-mode "${SOURCE_MODE:-workspace}" \
"${_owned_source_args[@]}" \
--kimaki-plugins-dir "$PLUGINS_DIR" \
"${claude_code_auth_args[@]}" \
"${managed_args[@]}" 2>&1 || true)
echo "$dry_out" | sed 's/^/ /'
[ -z "$MANAGED_INSTRUCTIONS_FILE" ] || rm -f "$MANAGED_INSTRUCTIONS_FILE"
return 0
fi
local repair_out repair_rc
local managed_args=()
if [ -n "$MANAGED_INSTRUCTIONS_FILE" ]; then
managed_args=(--managed-instructions-file "$MANAGED_INSTRUCTIONS_FILE")
fi
repair_out=$(python3 "$HELPER" \
--file "$OPENCODE_JSON_FILE" \
--runtime "$RUNTIME_ARG" \
--chat-bridge "$BRIDGE_ARG" \
--source-mode "${SOURCE_MODE:-workspace}" \
"${_owned_source_args[@]}" \
--kimaki-plugins-dir "$PLUGINS_DIR" \
"${claude_code_auth_args[@]}" \
"${managed_args[@]}" \
"$MODE_FLAG" \
--backup-suffix "$TIMESTAMP" 2>&1) && repair_rc=0 || repair_rc=$?
[ -z "$MANAGED_INSTRUCTIONS_FILE" ] || rm -f "$MANAGED_INSTRUCTIONS_FILE"
# repair-opencode-json.py writes both the target file and its own backup
# via plain Python open() — inherits the caller's umask/identity same as
# every other service-file writer in this repo. Normalize both.
service_file_normalize_perms "$OPENCODE_JSON_FILE"
service_file_normalize_perms "${OPENCODE_JSON_FILE}.backup.$TIMESTAMP"
local repair_status prompt_migration instruction_sync
repair_status=$(echo "$repair_out" | python3 -c "import json,sys; print(json.loads(sys.stdin.read()).get('status','?'))" 2>/dev/null || echo "parse-error")
prompt_migration=$(echo "$repair_out" | python3 -c "import json,sys; print(json.loads(sys.stdin.read()).get('prompt_migration','?'))" 2>/dev/null || echo "?")
instruction_sync=$(echo "$repair_out" | python3 -c "import json,sys; print(json.loads(sys.stdin.read()).get('instruction_sync','?'))" 2>/dev/null || echo "?")
case "$repair_status" in
ok)
log " opencode.json already correct"
;;
additive_repaired)
log " opencode.json repaired additively (backup: ${OPENCODE_JSON_FILE}.backup.$TIMESTAMP)"
log " $repair_out"
if [ "$prompt_migration" = "migrated" ]; then
UPDATED_ITEMS+=("opencode.json prompt → instructions migration")
fi
if [ "$instruction_sync" = "synced" ]; then
UPDATED_ITEMS+=("opencode.json Data Machine instructions")
fi
if echo "$repair_out" | grep -q '"added": \["'; then
UPDATED_ITEMS+=("opencode.json plugin array (added missing managed entries)")
fi
;;
needs_full_repair)
warn " opencode.json additively repaired, but unexpected plugin entries remain"
warn " Run './upgrade.sh --repair-opencode-json' to remove them (backup: ${OPENCODE_JSON_FILE}.backup.$TIMESTAMP)"
warn " $repair_out"
if [ "$prompt_migration" = "migrated" ]; then
UPDATED_ITEMS+=("opencode.json prompt → instructions migration")
fi
if [ "$instruction_sync" = "synced" ]; then
UPDATED_ITEMS+=("opencode.json Data Machine instructions")
fi
UPDATED_ITEMS+=("opencode.json plugin array (added managed entries; unexpected entries still present)")
OPENCODE_JSON_DRIFT=true
;;
repaired)
log " opencode.json fully repaired (backup: ${OPENCODE_JSON_FILE}.backup.$TIMESTAMP)"
log " $repair_out"
if [ "$prompt_migration" = "migrated" ]; then
UPDATED_ITEMS+=("opencode.json prompt → instructions migration")
fi
if [ "$instruction_sync" = "synced" ]; then
UPDATED_ITEMS+=("opencode.json Data Machine instructions")
fi
UPDATED_ITEMS+=("opencode.json plugin array (repaired)")
;;
drift)
# Only reachable if we passed neither --apply nor --additive, which
# shouldn't happen with the dispatch above. Defensive.
warn "Phase 3b: opencode.json has drift — $repair_out"
OPENCODE_JSON_DRIFT=true
;;
skipped)
log " $repair_out"
;;
*)
warn " repair-opencode-json.py returned status=$repair_status (rc=$repair_rc)"
warn " $repair_out"
;;
esac
}
# ============================================================================
# Phase 4: Sync wp-coding-agents upgrade skill
# ============================================================================
sync_skills() {
_run_filter_active skills || return 0
log "Phase 4: Syncing wp-coding-agents upgrade skill..."
if [ "$DRY_RUN" = true ]; then
SKILLS_DIR="$(runtime_skills_dir)"
echo -e "${BLUE}[dry-run]${NC} Would install upgrade skill from $SCRIPT_DIR/skills → $SKILLS_DIR"
if [ "$CHAT_BRIDGE" = "kimaki" ]; then
echo -e "${BLUE}[dry-run]${NC} Would copy upgrade skill to kimaki skills dir"
fi
return 0
fi
install_skills
UPDATED_ITEMS+=("wp-coding-agents upgrade skill")
}
# ============================================================================
# Phase 5: Regenerate AGENTS.md
# ============================================================================
regenerate_agents_md() {
_run_filter_active agents-md || return 0
log "Phase 5: Regenerating AGENTS.md..."
local AGENTS_MD="$SITE_PATH/AGENTS.md"
local BACKUP="$SITE_PATH/AGENTS.md.backup.$TIMESTAMP"
local CLAUDE_MD="$SITE_PATH/CLAUDE.md"
if [ "$DRY_RUN" = true ]; then
echo -e "${BLUE}[dry-run]${NC} Would backup $AGENTS_MD → $BACKUP"
echo -e "${BLUE}[dry-run]${NC} Would sync WordPress coding-agent boundary guidance mu-plugin"
echo -e "${BLUE}[dry-run]${NC} Would sync Homeboy AGENTS.md CLI guidance mu-plugin"
echo -e "${BLUE}[dry-run]${NC} Would run (as ${SERVICE_USER:-caller}): $WP_CMD datamachine memory compose AGENTS.md"
if _runtime_detected opencode; then
echo -e "${BLUE}[dry-run]${NC} Would symlink $CLAUDE_MD → AGENTS.md (Claude-model context)"
fi
return 0
fi
guidance_sync_all
sync_homeboy_availability
sync_homeboy_agents_md_guidance
# Backup existing (compose writes in-place to the registered location)
if [ -f "$AGENTS_MD" ]; then
cp "$AGENTS_MD" "$BACKUP"
service_file_normalize_perms "$BACKUP"
log " Backup: $BACKUP"
fi
# `datamachine memory compose AGENTS.md` writes in-place to the registered
# composable file path. It does NOT accept an arbitrary output path —
# the filename must be a registered MemoryFileRegistry entry.
#
# Composed AS THE SERVICE USER, not as the caller. The generated text encodes
# the composing process's euid — data-machine and data-machine-code both
# append `--allow-root` to their WP-CLI examples when posix_geteuid() === 0 —
# and upgrade.sh runs under sudo. Composing here as root would write an
# AGENTS.md instructing a non-root agent to run `wp --allow-root`, i.e. a file
# that misdescribes the agent's own environment (#93, #322).
#
# Permissions are still normalized afterward: compose writes as whichever
# identity ran it, and without this every other writer is locked out until the
# next normalize.
if (cd "$SITE_PATH" && wp_run_as_service_user datamachine memory compose AGENTS.md >/dev/null 2>&1); then
service_file_normalize_perms "$AGENTS_MD"
if [ -f "$BACKUP" ] && cmp -s "$BACKUP" "$AGENTS_MD"; then
log " AGENTS.md unchanged"
rm -f "$BACKUP" 2>/dev/null || true
else
log " AGENTS.md regenerated"
if [ -f "$BACKUP" ]; then
log " Diff (first 40 lines):"
diff -u "$BACKUP" "$AGENTS_MD" 2>/dev/null | head -40 | sed 's/^/ /' || true
fi
UPDATED_ITEMS+=("AGENTS.md")
fi
agents_md_prune_backups "$SITE_PATH"
else
warn " datamachine memory compose failed — AGENTS.md unchanged"
# Restore from backup if compose wrote a partial file
if [ -f "$BACKUP" ] && [ -f "$AGENTS_MD" ] && ! cmp -s "$BACKUP" "$AGENTS_MD"; then
cp "$BACKUP" "$AGENTS_MD"
service_file_normalize_perms "$AGENTS_MD"
warn " Restored AGENTS.md from backup"
fi
fi
# Symlink CLAUDE.md → AGENTS.md so Claude-model OpenCode sessions get the same DM context.
# OpenCode reads both filenames from the cwd glob (AGENTS.md, CLAUDE.md, CONTEXT.md),
# Claude Code reads only CLAUDE.md. Symlink keeps both runtimes covered without
# duplicating content or risking drift on AGENTS.md regeneration. Relative target
# ensures the symlink survives directory moves.
# See: Extra-Chill/wp-coding-agents#108
if [ -f "$AGENTS_MD" ] && _runtime_detected opencode; then
# Skip if CLAUDE.md exists as a regular file (e.g. claude-code runtime
# generates its own CLAUDE.md from a template — don't clobber it).
if [ -L "$CLAUDE_MD" ] || [ ! -e "$CLAUDE_MD" ]; then
(cd "$SITE_PATH" && ln -sf AGENTS.md CLAUDE.md)
log " Symlinked CLAUDE.md → AGENTS.md (covers Claude-model opencode sessions)"
else
log " CLAUDE.md exists as a regular file — leaving it alone (runtime-managed)"
fi
fi
}
_runtime_detected() {
local candidate="$1"
local runtime
for runtime in "${DETECTED_RUNTIMES[@]:-}"; do
[ "$runtime" = "$candidate" ] && return 0
done