-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathorbit.sh
More file actions
executable file
·4619 lines (4222 loc) · 175 KB
/
Copy pathorbit.sh
File metadata and controls
executable file
·4619 lines (4222 loc) · 175 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
#!/usr/bin/env bash
set -euo pipefail
ORBIT_VERSION="0.2.0"
ORBIT_ROOT="${ORBIT_ROOT:-}"
ORBIT_DEFAULT_BRANCH_PREFIX="ws"
ORBIT_CMD="${0##*/}"
# --- Messages (all decorative output goes to stderr) ---
# new: editor prompts (before creation)
ORBIT_NEW_PROMPTS=(
"What's the mission?"
"Plot your course."
"Set your heading."
"Name your target."
"Where to, pilot?"
"Log your objective."
)
# new: farewells (after creation)
# shellcheck disable=SC2034
ORBIT_NEW_FAREWELLS=(
"Godspeed."
"Ad astra."
"Go for orbit."
"Fly true."
"All systems nominal."
"Good hunting."
)
# goal: editor prompts (before update)
ORBIT_GOAL_PROMPTS=(
"Revise the mission."
"Adjust your heading."
"Recalculate trajectory."
"Update the briefing."
"New orders, pilot."
"Amend the flight plan."
)
# goal: farewells (after update)
# shellcheck disable=SC2034
ORBIT_GOAL_FAREWELLS=(
"Target locked."
"Course corrected."
"New heading confirmed."
"Objective updated."
"Coordinates set."
"Recalibrating..."
)
# goal: farewells (after clear)
# shellcheck disable=SC2034
ORBIT_GOAL_CLEAR_FAREWELLS=(
"Target disengaged."
"Drifting free."
"Off the grid."
"Signal lost. Standing by."
)
# done: farewells (after marking done)
# shellcheck disable=SC2034
ORBIT_DONE_FAREWELLS=(
"Mission complete."
"Orbit achieved."
"Touchdown confirmed."
"Splashdown."
"Payload delivered."
"That's one for the books."
)
orbit_random_msg() {
local _arr_name=$1
eval "local _len=\${#${_arr_name}[@]}"
# shellcheck disable=SC2154
local idx=$(( RANDOM % _len ))
eval "local _msg=\${${_arr_name}[$idx]}"
# shellcheck disable=SC2154
printf '\n%s\n' "$_msg" >&2
}
# --- Utilities ---
orbit_usage() {
cat <<EOF
Usage:
$ORBIT_CMD clone <url> [--push <fork-url>] [--name <repo>] [--branch <branch>]
$ORBIT_CMD repos
$ORBIT_CMD info <repo>
$ORBIT_CMD memo [<repo>] [--refresh|--scaffold]
$ORBIT_CMD new "<goal>" [--name <name>] [--no-goal] [--exec "<cmd>"]
$ORBIT_CMD add <repo> [--ref <tag/branch>] [-s|--silent]
$ORBIT_CMD switch [-c] [repo] <name>
$ORBIT_CMD sync [repo...] [--force] [--branch <branch>]
$ORBIT_CMD done [--pr <url>...] [--json]
$ORBIT_CMD status [workspace] [--json]
$ORBIT_CMD goal ["text"] [--clear]
$ORBIT_CMD jot [<repo>] ["text"] [--pop] [--json]
$ORBIT_CMD prune [workspace] [--older <dur>] [--dry-run] [--force]
$ORBIT_CMD config [<key> [<value> | --unset]]
$ORBIT_CMD context [<key>] [--startup|--prime|--reignite] [--json]
$ORBIT_CMD doctor
$ORBIT_CMD completion <zsh|bash>
$ORBIT_CMD version
Options: --json for machine-readable output (repos, status, info, done, context, jot --pop)
Config keys (project-level, via '$ORBIT_CMD config <key> <value>'):
agent.recommend Launch command recommended after 'new' (e.g. 'claude "orbit start"')
branch.prefix Scoped-mode tracking branch prefix (default: ws)
memo.minLines Memo card soft lower bound / thin floor (default: 4)
memo.maxLines Memo card hard upper bound / compress + README-fallback cap (default: 16)
jot.bufferSize Jot entries per repo before aggregation is nudged (default: memo.minLines = 4)
explore.paths Cold-start memo exploration scope: comma-delimited <path>:<depth>
list, e.g. '.:1,src:1,docs:2' (default: .:1)
Environment:
ORBIT_ROOT Explicit project root (default: discover from CWD)
EOF
}
orbit_fail() {
printf 'orbit: %s\n' "$*" >&2
return 1
}
# orbit_plural <count> <singular> <plural> — human-facing counts read wrong
# with a bare "s" ("1 repos"); branch→branches style plurals need both forms.
orbit_plural() {
if [ "$1" = "1" ]; then
printf '%s' "$2"
else
printf '%s' "$3"
fi
}
# One path segment, legal inside a git refname, and not something that reads as
# an option on a command line. git check-ref-format is the authority on the
# rest (rejects '.'-leading, '..', spaces, control chars).
orbit_valid_branch_prefix() {
case "$1" in
''|*/*|-*) return 1 ;;
esac
git check-ref-format "refs/heads/$1/w/n" >/dev/null 2>&1
}
# List pool repos holding local branches under <prefix>/, as "repo (n)" pairs.
# Returns 1 when there are none.
orbit_branches_under_prefix() {
local root="$1" prefix="$2" repo_dir count total=0 hits=""
for repo_dir in "$root/.repos"/*/; do
[ -d "$repo_dir" ] || continue
count=$(git -C "$repo_dir" for-each-ref --format='%(refname:short)' "refs/heads/$prefix/" 2>/dev/null | grep -c . || true)
[ "${count:-0}" -gt 0 ] || continue
hits="$hits $(basename "$repo_dir") ($count)"
total=$((total + count))
done
[ "$total" -gt 0 ] || return 1
printf '%s\n' "${hits# }"
}
# The tracking-branch prefix is a durable project property, not per-invocation
# state: it is baked into every branch name orbit creates AND it is the selector
# prune uses to decide which branches are orbit's to delete. Those two moments
# must agree — if they can disagree, branches leak (created under one prefix,
# looked for under another) or, worse, prune claims branches it never created.
# So it lives in project config, written deliberately and persisting across
# sessions, rather than in an environment variable any single call can flip.
orbit_require_prefix() {
local prefix="" root
if root=$(orbit_find_root 2>/dev/null); then
prefix=$(git config --file "$root/.repos/.orbit" --get branch.prefix 2>/dev/null || true)
fi
[ -n "$prefix" ] || prefix="$ORBIT_DEFAULT_BRANCH_PREFIX"
orbit_valid_branch_prefix "$prefix" || { orbit_fail "invalid branch.prefix in project config: $prefix"; return 1; }
printf '%s\n' "$prefix"
}
orbit_find_root() {
if [ -n "$ORBIT_ROOT" ]; then
[ -d "$ORBIT_ROOT/.repos" ] || return 1
printf '%s\n' "$ORBIT_ROOT"
return 0
fi
local dir
dir="$(pwd)"
while [ "$dir" != "/" ]; do
if [ -d "$dir/.repos" ]; then
printf '%s\n' "$dir"
return 0
fi
dir=$(dirname "$dir")
done
return 1
}
orbit_require_root() {
local root
root=$(orbit_find_root) || { orbit_fail "not in an orbit project (no .repos/ found); use 'orbit clone' or 'orbit new' to start"; return 1; }
printf '%s\n' "$root"
}
# Pool infrastructure marker. .repos/ is orbit's pool, not an agent API surface:
# it lives outside the workspace sandbox and all access goes through orbit
# commands. This README is a passive warning that surfaces if an agent ever
# lists .repos/ directly. Idempotent — written once, never overwritten.
orbit_write_pool_readme() {
local repos_dir="$1"
[ -f "$repos_dir/README.md" ] && return 0
cat > "$repos_dir/README.md" <<'EOF'
# .repos/ — orbit pool infrastructure (do not access directly)
This directory is orbit's repo pool. It is internal infrastructure, not an API
surface. Do not read, edit, or run git inside `.repos/` directly.
All pool access goes through orbit commands:
- `orbit repos` / `orbit info <repo>` — list and inspect pool repos
- `orbit add <repo>` — bring a repo into your workspace as a worktree
- `orbit sync <repo>` — update a pool repo from its upstream
- `orbit memo <repo>` — read/write a repo's memo card
Work happens in workspace worktrees created by `orbit add`, never here.
EOF
}
orbit_ensure_init() {
local root
if root=$(orbit_find_root); then
mkdir -p "$root/.repos"
[ -f "$root/.repos/.orbit" ] || touch "$root/.repos/.orbit"
orbit_write_pool_readme "$root/.repos"
printf '%s\n' "$root"
return 0
fi
root="$(pwd)"
mkdir -p "$root/.repos"
touch "$root/.repos/.orbit"
orbit_write_pool_readme "$root/.repos"
printf '%s\n' "$root"
}
orbit_repo_basename() {
local remote name
remote="$1"
name="${remote%/}"
name="${name##*/}"
name="${name##*:}"
name="${name%.git}"
[ -n "$name" ] || orbit_fail "cannot derive repo name from: $remote"
printf '%s\n' "$name"
}
orbit_default_branch() {
local repo="$1" head branch
head=$(git -C "$repo" symbolic-ref --quiet refs/remotes/origin/HEAD 2>/dev/null || true)
# Trust the local pointer only if it actually resolves — guards a dangling
# origin/HEAD left behind by a deleted default branch.
if [ -n "$head" ] && git -C "$repo" rev-parse --verify --quiet "$head" >/dev/null 2>&1; then
printf '%s\n' "${head#refs/remotes/origin/}"
return 0
fi
if git -C "$repo" rev-parse --verify --quiet origin/main >/dev/null 2>&1; then
printf 'main\n'
return 0
fi
if git -C "$repo" rev-parse --verify --quiet origin/master >/dev/null 2>&1; then
printf 'master\n'
return 0
fi
# Fallback: ask the remote directly. Handles a non-standard default branch
# (e.g. develop/trunk) when origin/HEAD is missing — as after a single-branch
# clone. Persist the answer so the fast local path works next time.
branch=$(git -C "$repo" ls-remote --symref origin HEAD 2>/dev/null \
| awk '/^ref:/ {sub("refs/heads/", "", $2); print $2; exit}')
if [ -n "$branch" ]; then
git -C "$repo" remote set-head origin --auto >/dev/null 2>&1 || true
printf '%s\n' "$branch"
return 0
fi
orbit_fail "cannot determine default branch for $repo
the remote has no detectable default branch — it is likely empty (no commits/branches pushed yet) or missing origin/HEAD.
fix: push an initial commit to the remote, then run 'orbit sync'."
}
orbit_git_supports_orphan_worktree() {
local ver
ver=$(git --version | awk '{print $3}')
[ "$(printf '%s\n' "2.42" "$ver" | sort -V | head -n1)" = "2.42" ]
}
orbit_reserved_workspace() {
case "$1" in
''|.|..|.repos|.git|*/*) return 0 ;;
.*) return 0 ;;
*) return 1 ;;
esac
}
# Print the name of the workspace containing the given path, nothing if none.
# "Looks like a workspace" = a non-reserved direct child of the project root;
# any depth below it counts (workspaces host repos and nested dirs). Detection
# is purely structural — it does NOT require a .orbit marker: workspace metadata
# is disposable (Principle 3), so a lost or absent .orbit must never quietly
# disable a destructive-op guard. orbit_reserved_workspace already excludes
# .repos/.git and every dotdir, so the pool index cannot be mistaken for one.
orbit_ws_containing_dir() {
local root="$1" path="$2" root_phys path_phys rel first
root_phys=$(cd "$root" 2>/dev/null && pwd -P) || return 1
[ -d "$path" ] || return 1
path_phys=$(cd "$path" 2>/dev/null && pwd -P) || return 1
case "$path_phys" in
"$root_phys") return 1 ;;
"$root_phys"/*) ;;
*) return 1 ;;
esac
rel="${path_phys#"$root_phys/"}"
first="${rel%%/*}"
orbit_reserved_workspace "$first" && return 1
printf '%s\n' "$first"
}
orbit_tracking_branch() {
local prefix ws name
prefix=$(orbit_require_prefix) || return 1
ws="$1"; name="$2"
printf '%s/%s/%s\n' "$prefix" "$ws" "$name"
}
orbit_branch_is_checked_out_elsewhere() {
local repo="$1" branch="$2"
git -C "$repo" worktree list --porcelain | grep -Fqx "branch refs/heads/$branch"
}
orbit_set_upstream() {
local path="$1" local_branch="$2" upstream_branch="$3"
git -C "$path" config "branch.$local_branch.remote" origin
git -C "$path" config "branch.$local_branch.merge" "refs/heads/$upstream_branch"
}
orbit_remote_branch_exists() {
local repo="$1" branch="$2"
git -C "$repo" ls-remote --exit-code --heads origin "$branch" >/dev/null 2>&1
}
# Fetch an existing remote branch's tracking ref with an explicit colon
# refspec: layout-independent — it works under the wildcard map, under a
# single-branch default entry, and under any user-narrowed layout, and it
# never touches config.
# Always fetch, even when origin/<branch> exists locally: the remote branch
# may have advanced or been force-pushed after it was fetched, and checking
# out the stale ref silently builds on abandoned history. Degrade when
# offline: use the local ref with a warning; fail only when there is
# nothing to fall back on.
orbit_ensure_remote_branch() {
local repo="$1" branch="$2"
if ! git -C "$repo" fetch origin "+refs/heads/$branch:refs/remotes/origin/$branch" 2>/dev/null; then
if git -C "$repo" rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null 2>&1; then
printf 'orbit: cannot fetch origin/%s, using possibly-stale local ref\n' "$branch" >&2
else
orbit_fail "cannot fetch origin/$branch"
fi
fi
}
# Read one of the managed-config switches (project config, following the
# branch.prefix convention): always (default) = the key is orbit-maintained
# at every touchpoint; once = written once at clone, then the value is the
# user's; never = never written, never corrected. Unrecognized values read as
# always.
orbit_managed_config_mode() {
local root="$1" key="$2" v
v=$(git config --file "$root/.repos/.orbit" --get "$key" 2>/dev/null || true)
case "$v" in once|never) printf '%s' "$v" ;; *) printf 'always' ;; esac
}
# Config maintenance — one predicate per managed key, no remote comparison,
# no per-branch bookkeeping. The rule (spec-worktree → Git Dependency
# Closure): a config key orbit depends on is either managed here or
# explicitly declared premise-only.
# git.fetchAllBranches = always: remote.origin.fetch is exactly the full wildcard
# (the on-disk form of `git remote set-branches origin "*"`); exact
# entries, scoped wildcards, and emptied configs all converge to it.
# git.fetchPrune = always: fetch.prune=true is set.
# git.pushUpstreamByDefault = always: push.default=upstream is set — scoped local
# names (ws/<ws>/<name>) differ from remote names, so git's default
# "simple" would refuse a bare `git push`.
# once/never pools are user territory — untouched, unreported.
# dry_run=1 prints would-lines on stdout (prune's pool-maintenance plan);
# real runs report each actual change on stderr, one line per key, each
# carrying its escape-hatch command.
orbit_maintain_pool_config() {
local repo="$1" root="$2" dry_run="${3:-0}"
local name wildcard='+refs/heads/*:refs/remotes/origin/*'
name=$(basename "$repo")
if [ "$(orbit_managed_config_mode "$root" git.fetchAllBranches)" = "always" ]; then
local line count=0 exact=1
while IFS= read -r line; do
[ -n "$line" ] || continue
count=$((count + 1))
[ "$line" = "$wildcard" ] || exact=0
done < <(git -C "$repo" config --get-all remote.origin.fetch 2>/dev/null || true)
if [ "$count" -ne 1 ] || [ "$exact" -ne 1 ]; then
if [ "$dry_run" = "1" ]; then
printf 'would converge fetch config: git remote set-branches origin "*"\n'
else
git -C "$repo" config --replace-all remote.origin.fetch "$wildcard"
printf 'orbit: %s: fetch config converged: git remote set-branches origin "*" (stop converging and re-apply yours: orbit config git.fetchAllBranches once)\n' "$name" >&2
fi
fi
fi
if [ "$(orbit_managed_config_mode "$root" git.fetchPrune)" = "always" ]; then
if [ "$(git -C "$repo" config --type=bool --get fetch.prune 2>/dev/null || true)" != "true" ]; then
if [ "$dry_run" = "1" ]; then
printf 'would converge fetch config: git config fetch.prune true\n'
else
git -C "$repo" config fetch.prune true
printf 'orbit: %s: fetch config converged: git config fetch.prune true (stop converging and re-apply yours: orbit config git.fetchPrune once)\n' "$name" >&2
fi
fi
fi
if [ "$(orbit_managed_config_mode "$root" git.pushUpstreamByDefault)" = "always" ]; then
if [ "$(git -C "$repo" config --get push.default 2>/dev/null || true)" != "upstream" ]; then
if [ "$dry_run" = "1" ]; then
printf 'would converge push routing: git config push.default upstream\n'
else
git -C "$repo" config push.default upstream
printf 'orbit: %s: push routing converged: git config push.default upstream (stop converging and re-apply yours: orbit config git.pushUpstreamByDefault once)\n' "$name" >&2
fi
fi
fi
}
# The touchpoint fetch discipline (sync / prune):
# fetch the default branch plus every remote branch a local branch tracks
# (branch.*.merge, deduped — several local branches can share one upstream),
# one explicit refspec per fetch, never a bare fetch: under the wildcard map
# a bare fetch pulls every branch's objects (defeating the single-branch
# clone's economy), and a batch of refspecs dies atomically on the first dead
# branch. Each fetch stands alone: git's fatal is swallowed (this path must
# never leak the "couldn't find remote ref" this model exists to eliminate);
# when anything failed, one closing `git remote prune origin` converges the
# refs of remote-deleted branches — online it cleans, offline it fails and
# deletes nothing. The prune runs only while the full wildcard is in place
# (shape judgment, not mode forking: a narrowed clone/off layout is the
# user's territory). The default branch is the one loud failure: if it does
# not fetch while the remote answers, the remote may have lost its default
# branch — a repo-level event, reported. Returns non-zero iff the default
# branch would not fetch (sync treats this as fetch failure; prune ignores
# it).
orbit_touchpoint_fetch() {
local repo="$1" default_br lb merge b failed=0 default_failed=0
default_br=$(orbit_default_branch "$repo" 2>/dev/null || true)
local seen=" " branches=""
if [ -n "$default_br" ]; then
branches="$default_br
"
seen=" $default_br "
fi
while IFS= read -r lb; do
[ -n "$lb" ] || continue
[ "$(git -C "$repo" config --get "branch.$lb.remote" 2>/dev/null)" = "origin" ] || continue
merge=$(git -C "$repo" config --get "branch.$lb.merge" 2>/dev/null) || continue
case "$merge" in
refs/heads/*) b="${merge#refs/heads/}" ;;
*) continue ;;
esac
case "$seen" in *" $b "*) continue ;; esac
seen="$seen$b "
branches="$branches$b
"
done < <(git -C "$repo" for-each-ref --format='%(refname:short)' refs/heads/ 2>/dev/null || true)
while IFS= read -r b; do
[ -n "$b" ] || continue
if ! GIT_TERMINAL_PROMPT=0 git -C "$repo" fetch origin "+refs/heads/$b:refs/remotes/origin/$b" >/dev/null 2>&1; then
failed=1
[ "$b" = "$default_br" ] && default_failed=1
fi
done < <(printf '%s' "$branches")
if [ "$failed" = "1" ]; then
if git -C "$repo" config --get-all remote.origin.fetch 2>/dev/null | grep -Fqx '+refs/heads/*:refs/remotes/origin/*'; then
GIT_TERMINAL_PROMPT=0 git -C "$repo" remote prune origin >/dev/null 2>&1 || true
fi
if [ "$default_failed" = "1" ]; then
# Probe once to tell "remote lost its default branch" (repo-level news,
# reported) from "offline" (routine, silent): 0 = branch exists yet the
# fetch failed, 2 = branch gone from a reachable remote — both report.
local rc=0
GIT_TERMINAL_PROMPT=0 git -C "$repo" ls-remote --exit-code --heads origin "$default_br" >/dev/null 2>&1 || rc=$?
case "$rc" in
0|2)
printf 'orbit: %s: WARNING: cannot fetch default branch origin/%s though the remote answers — the remote may have lost its default branch\n' \
"$(basename "$repo")" "$default_br" >&2 ;;
esac
fi
fi
[ "$default_failed" = "0" ]
}
# --- CWD Inference ---
# A repo name is a pool directory basename, never a path. Callers build
# destructive targets by concatenation ($root/.repos/$name), so a traversing
# name ('../<ws>/<repo>') would point the pool operation at a workspace
# worktree instead — check the argument, not just whether the path it lands on
# happens to exist.
# The charset is GitHub's own ([A-Za-z0-9._-]): slashes and spaces are not
# legal remote repo names either. Two GitHub-legal shapes stay rejected on
# purpose: a leading '.' (pool loops glob .repos/*/, which skips hidden dirs)
# and a leading '-' (indistinguishable from an option flag in any argv slot).
orbit_valid_repo_name() {
local name="$1"
case "$name" in
''|.*|-*) return 1 ;;
*[!A-Za-z0-9._-]*) return 1 ;;
esac
return 0
}
orbit_require_repo_name() {
orbit_valid_repo_name "$1" || orbit_fail "invalid repo name: $1 (expected a pool repo basename: [A-Za-z0-9._-], no leading '.' or '-')"
}
orbit_infer_workspace() {
local root="$1" cwd rel first
# Physical paths on both sides: a cwd reached through a symlink (macOS
# /tmp -> /private/tmp) shares no prefix with the logical root, and every
# command that infers its workspace would refuse to work there. This is also
# what keeps inference and the root-only guards answering the same question
# the same way.
cwd=$(pwd -P)
root=$(cd "$root" 2>/dev/null && pwd -P) || root="$1"
case "$cwd" in
"$root") orbit_fail "cannot infer workspace from project root; cd into a workspace first"; return 1 ;;
"$root"/*) ;;
*) orbit_fail "CWD is not under project root"; return 1 ;;
esac
rel="${cwd#"$root/"}"
first="${rel%%/*}"
if orbit_reserved_workspace "$first"; then
orbit_fail "cannot infer workspace: '$first' is reserved"
return 1
fi
printf '%s\n' "$first"
}
# True when the CWD is inside some workspace (the project root itself and
# reserved dirs are not). Delegates to orbit_ws_containing_dir so the cwd guard
# and the ancestry guard answer "what counts as a workspace" with one rule.
# The comparison is on physical paths, because a cwd reached through a symlink
# (macOS /tmp -> /private/tmp) fails a logical prefix match, and an isolation
# guard that silently does not fire is the bug class this whole family of checks
# exists to prevent — which is also why an unreadable cwd answers "inside":
# a deleted working directory cannot be proven to be outside a workspace, and
# guessing "outside" is exactly the silent non-firing to avoid. The refusal that
# follows names the project root, which is the fix for a deleted cwd anyway.
orbit_cwd_inside_workspace() {
local cwd
cwd=$(pwd -P 2>/dev/null) || return 0
orbit_ws_containing_dir "$1" "$cwd" >/dev/null
}
orbit_infer_repo() {
local root="$1" ws="$2" cwd rel repo_name ws_dir
# Physical on both sides, same reason as orbit_infer_workspace.
cwd=$(pwd -P)
ws_dir=$(cd "$root/$ws" 2>/dev/null && pwd -P) || ws_dir="$root/$ws"
case "$cwd" in
"$ws_dir") return 1 ;;
"$ws_dir"/*) ;;
*) return 1 ;;
esac
rel="${cwd#"$ws_dir/"}"
repo_name="${rel%%/*}"
if [ -d "$root/$ws/$repo_name/.git" ] || [ -f "$root/$ws/$repo_name/.git" ]; then
printf '%s\n' "$repo_name"
return 0
fi
return 1
}
# --- Process Ancestry ---
# Ancestor cwds are a property of this process, not of any candidate: collect
# them once per run. Re-walking per candidate costs a ps + lsof round-trip per
# ancestor on macOS, which scales with the number of workspaces for no gain.
ORBIT_ANCESTRY_CACHED=0
ORBIT_ANCESTOR_CWDS=""
# Print the cwd of a process; nothing if unreadable (exited, permissions).
# On hosts with neither /proc nor lsof this prints nothing for every pid and
# session detection degrades to the root-level guard — orbit doctor warns.
# `|| true` keeps the function safe under set -e in any calling context.
orbit_process_cwd() {
local pid="$1"
if [ -d "/proc/$pid" ]; then
readlink "/proc/$pid/cwd" 2>/dev/null || true
elif command -v lsof >/dev/null 2>&1; then
lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | awk '/^n\//{print substr($0,2); exit}' || true
fi
}
# Print a process's parent pid. Prefers /proc (no external command, and works
# where busybox ps lacks -o); falls back to ps. In /proc/<pid>/stat the comm
# field can itself contain spaces and parens, so fields are read after the last
# ')': state, then ppid.
orbit_process_ppid() {
local pid="$1" stat rest
if [ -r "/proc/$pid/stat" ]; then
stat=$(cat "/proc/$pid/stat" 2>/dev/null) || stat=""
if [ -n "$stat" ]; then
rest=${stat##*') '}
# shellcheck disable=SC2086 # deliberate word split into positionals
set -- $rest
[ "$#" -ge 2 ] && { printf '%s\n' "$2"; return 0; }
fi
fi
ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ' || true
}
# Walk the ppid chain once and cache every readable ancestor cwd.
# Announces its own blind spot: if not a single ancestor cwd could be read, the
# guard cannot see anything, and a guard that silently does nothing is how the
# original incident happened. The check is on the *result*, not on which
# facility is present — a host can have /proc yet no usable ps, and vice versa.
orbit_collect_ancestor_cwds() {
[ "$ORBIT_ANCESTRY_CACHED" = "1" ] && return 0
ORBIT_ANCESTRY_CACHED=1
local pid cwd depth=0
pid=$(orbit_process_ppid $$)
# Cap the walk at 32 ancestors: deep enough for any realistic shell/agent
# stack, and bounds the loop should ps ever report a cyclic ppid chain.
# Ancestors beyond the cap are (deliberately) not checked.
while [ "$depth" -lt 32 ]; do
case "$pid" in ''|*[!0-9]*|0|1) break ;; esac
cwd=$(orbit_process_cwd "$pid")
if [ -n "$cwd" ]; then
ORBIT_ANCESTOR_CWDS="$ORBIT_ANCESTOR_CWDS$cwd
"
fi
pid=$(orbit_process_ppid "$pid")
depth=$((depth + 1))
done
if [ -z "$ORBIT_ANCESTOR_CWDS" ]; then
printf 'orbit: cannot read process ancestry on this host: the initiation guard is inactive\n' >&2
fi
}
# Return 0 if any ancestor process has its cwd inside $1.
# The invoking shell's cwd is agent-controllable (cd), so "is this session
# rooted in <dir>" must be checked on the process tree — a shell can cd out,
# but the session's ancestor chain keeps its launch cwd. Positive match only:
# unreadable cwds are skipped and the walk continues.
orbit_session_workspace() {
local root="$1" cwd ws
# orbit_ws_containing_dir physical-normalizes each ancestor cwd itself
# (lsof//proc report resolved paths).
orbit_collect_ancestor_cwds
[ -n "$ORBIT_ANCESTOR_CWDS" ] || return 1
while IFS= read -r cwd; do
[ -n "$cwd" ] || continue
if ws=$(orbit_ws_containing_dir "$root" "$cwd"); then
printf '%s\n' "$ws"
return 0
fi
done <<EOF
$ORBIT_ANCESTOR_CWDS
EOF
return 1
}
# Shared guard for destructive root-scoped operations (prune, sync --force /
# --branch). One rule: the invocation must come from a process tree standing
# entirely outside every workspace.
# $1 root $2 subcommand name (replay prefix) $3 display name (message
# prefix, may name flags) $4+ original args (for the cd replay)
# Refuses (orbit_fail + return 1) when blocked; returns 0 when it may proceed.
# Every failure path returns explicitly rather than leaning on the caller's
# set -e, so the guard stays correct even if a future caller invokes it in a
# condition context (which would disable set -e for its whole body).
orbit_require_root_scope() {
local root="$1" subcmd="$2" display="$3"
shift 3
local ws_hit
# Walk the ancestry HERE, in this shell. orbit_session_workspace is called in
# a command substitution below, and a subshell's assignments never reach the
# caller — reading ORBIT_ANCESTOR_CWDS after it would always see the empty
# initial value and mistake a readable ancestry for a blind one. Collecting
# first also lets the subshell inherit the cache: one walk, one blind-spot
# warning.
orbit_collect_ancestor_cwds
# Primary, target-independent guard: any ancestor process rooted inside any
# workspace aborts the whole invocation. A parent's cwd can't be cd'd away,
# so there is no remedy to offer — state the fact and stop.
if ws_hit=$(orbit_session_workspace "$root"); then
orbit_fail "$display should not be initiated from inside workspace $ws_hit"
return 1
fi
# Fallback guard: orbit's own cwd is misplaced into a workspace.
if orbit_cwd_inside_workspace "$root"; then
# Replay the intended command ONLY when the ancestry actually ran and came
# back clean (ORBIT_ANCESTOR_CWDS populated above). When it was blind (no
# readable ancestor cwd), we cannot vouch the session isn't rooted in a
# workspace, so handing back a ready-to-run `cd <root> && orbit ...` could
# walk the operator straight into deleting the live workspace they are in
# — give the fact only.
if [ -z "$ORBIT_ANCESTOR_CWDS" ]; then
orbit_fail "$display must be run from the project root"
return 1
fi
local replay="" arg
for arg in "$@"; do replay="$replay $(printf '%q' "$arg")"; done
orbit_fail "$display must be run from the project root — cd $(printf '%q' "$root") && orbit $subcmd$replay"
return 1
fi
return 0
}
orbit_ensure_workspace_orbit() {
local ws_dir="$1"
local orbit_file="$ws_dir/.orbit"
if [ ! -f "$orbit_file" ]; then
local now
now=$(date +%s)
git config --file "$orbit_file" workspace.created "$now"
fi
}
# Memo card line bounds (project config on .repos/.orbit; not shell env — memo
# is project-level state). minLines = soft lower bound (gap/thin floor): below
# it a card isn't real yet. maxLines = hard upper bound (compress/curate ceiling
# + README-fallback cap): above it, curate instead of appending.
orbit_memo_min() {
local root="$1" v
v=$(git config --file "$root/.repos/.orbit" --get memo.minLines 2>/dev/null || true)
case "$v" in ''|*[!0-9]*) v=4 ;; esac
printf '%s' "$v"
}
orbit_memo_max() {
local root="$1" v
v=$(git config --file "$root/.repos/.orbit" --get memo.maxLines 2>/dev/null || true)
case "$v" in ''|*[!0-9]*) v=16 ;; esac
printf '%s' "$v"
}
# Over-budget threshold = maxLines + minLines. A card past the hard ceiling
# by more than the min-floor buffer is genuinely bloated; best-effort curation
# that lands slightly over the ceiling stays under this line and is left alone.
orbit_memo_overlong_threshold() {
local root="$1"
printf '%s' "$(( $(orbit_memo_max "$root") + $(orbit_memo_min "$root") ))"
}
# A memo is "thin" (missing or low-quality) if the file is absent or has fewer
# than memo.minLines non-blank lines. Conservative on purpose: only flags
# genuinely empty/stub cards that still need a real pull-decision card written.
orbit_memo_is_thin() {
local md_file="$1" root="$2"
[ -f "$md_file" ] || return 0
local n min
n=$(grep -c '[^[:space:]]' "$md_file" 2>/dev/null || echo 0)
min=$(orbit_memo_min "$root")
[ "$n" -lt "$min" ]
}
# Cold-start exploration scope for writing a memo card: a comma-delimited list
# of <path>:<depth> entries (project config; default the repo root at depth 1).
# One global knob, consumed only at first `orbit add` of a repo; afterward the
# jot -> incremental-memo pipeline maintains the card. Doc-format agnostic —
# orbit attaches no meaning to what lives at the paths.
orbit_explore_paths() {
local root="$1" v
v=$(git config --file "$root/.repos/.orbit" --get explore.paths 2>/dev/null || true)
[ -n "$v" ] || v=".:1"
printf '%s' "$v"
}
# Render the stored path:depth list as human text so a reader need not know the
# convention: ".:1,src:2" -> ". (depth 1), src (depth 2)".
orbit_explore_paths_human() {
local raw out="" entry path depth
raw=$(orbit_explore_paths "$1")
local oldifs="$IFS"; IFS=,
for entry in $raw; do
IFS="$oldifs"
path="${entry%%:*}"; depth="${entry##*:}"
[ -n "$out" ] && out="$out, "
out="$out$path (depth $depth)"
IFS=,
done
IFS="$oldifs"
printf '%s' "$out"
}
# Jot aggregation buffer (project config on .repos/.orbit): a repo that has
# accumulated enough jots to fill a minimum memo should aggregate them into the
# card. Defaults to memo.minLines; follows it unless explicitly set.
orbit_jot_buffer_size() {
local root="$1" v
v=$(git config --file "$root/.repos/.orbit" --get jot.bufferSize 2>/dev/null || true)
case "$v" in ''|*[!0-9]*) v=$(orbit_memo_min "$root") ;; esac
printf '%s' "$v"
}
# Jot warn level for a count given the buffer size: building | overflow | none.
# Silent at or below bufferSize/2; building up to bufferSize; overflow past it.
orbit_jot_level() {
local count="$1" buf="$2"
local half=$(( buf / 2 ))
if [ "$count" -gt "$buf" ]; then printf 'overflow'
elif [ "$count" -gt "$half" ]; then printf 'building'; fi
}
# Memo state for context/status purposes: thin | ok | over.
# thin = missing or fewer than memo.minLines non-blank lines (no real card yet);
# over = more than maxLines+minLines non-blank lines (over budget, curate once).
orbit_memo_state() {
local md_file="$1" root="$2" n min over_t
[ -f "$md_file" ] || { printf 'thin'; return; }
n=$(grep -c '[^[:space:]]' "$md_file" 2>/dev/null || echo 0)
min=$(orbit_memo_min "$root")
over_t=$(orbit_memo_overlong_threshold "$root")
if [ "$n" -lt "$min" ]; then printf 'thin'
elif [ "$n" -gt "$over_t" ]; then printf 'over'
else printf 'ok'; fi
}
# Print the worktree's upstream tracking state: "untracked" when the branch
# has no upstream config or its tracking ref is not materialized yet (a
# branch that was never pushed — cruise block surfaces this so the agent
# knows), a number when behind, or empty when tracked and up-to-date.
# Uses local refs only — never fetches.
orbit_repo_upstream_behind() {
local wt_dir="$1" upstream behind
# See orbit_status: a failing rev-parse can still print '@{upstream}' —
# gate on the exit code, not on the captured text.
if ! upstream=$(git -C "$wt_dir" rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null); then
upstream=""
fi
if [ -z "$upstream" ]; then
printf 'untracked'
return 0
fi
behind=$(git -C "$wt_dir" rev-list --count "HEAD..${upstream}" 2>/dev/null || echo 0)
[ "$behind" = "0" ] && behind=""
printf '%s' "$behind"
}
# Per-repo status for a workspace, one line per worktree repo (unfiltered):
# <name>|<jot_count>|<jot_level>|<behind>|<memo_state>|<branch>|<is_scoped>
# jot_level: building|overflow (empty when count <= bufferSize/2);
# behind: commits behind the worktree branch's @{upstream}, "untracked" when
# no upstream (raw-mode), or empty when tracked and up-to-date;
# memo_state: ok|thin|over (see orbit_memo_state);
# branch: the worktree's current branch name (for the untracked hint);
# is_scoped: 1 when branch name starts with ws/<workspace>/ (scoped mode),
# 0 otherwise (raw mode — recommend orbit switch -c to convert).
# Shared by `orbit context` (cruise/reignite blocks) and `orbit done`.
orbit_collect_repo_status() {
local root="$1" ws_dir="$2"
local orbit_file="$ws_dir/.orbit"
local buf
buf=$(orbit_jot_buffer_size "$root")
local ws_name
ws_name=$(basename "$ws_dir")
local d name branch count level behind mstate is_scoped
for d in "$ws_dir"/*/; do
[ -d "$d" ] || continue
[ -d "$d/.git" ] || [ -f "$d/.git" ] || continue
name=$(basename "$d")
branch=$(git -C "$d" branch --show-current 2>/dev/null || echo "detached")
case "$branch" in
ws/"$ws_name"/*) is_scoped=1 ;;
*) is_scoped=0 ;;
esac
count=$(git config --file "$orbit_file" --get-all "jot.$name.entry" 2>/dev/null | grep -c . || true)
[ -n "$count" ] || count=0
level=$(orbit_jot_level "$count" "$buf")
behind=$(orbit_repo_upstream_behind "$d")
mstate=$(orbit_memo_state "$root/.repos/.$name.md" "$root")
printf '%s|%s|%s|%s|%s|%s|%s\n' "$name" "$count" "$level" "$behind" "$mstate" "$branch" "$is_scoped"
done
}
# --- Brief Extraction ---
orbit_brief_extract() {
local file="$1"
[ -e "$file" ] || [ "$file" = "/dev/stdin" ] || return 1
local line found=""
# State for multi-line constructs common in GitHub READMEs:
# in_fence — the opening fence marker (``` or ~~~), empty when outside
# in_comment — inside a multi-line <!-- --> comment
# in_tag — inside a multi-line HTML tag (<img ...\n src="..."\n width="50%">)
# html_stack — open non-void HTML blocks (<p align="center"> … </p>)
# html_lines — lines spent inside html_stack; an unclosed block is common
# in hand-written README HTML, so after a budget we drop the stack and
# resume normal scanning instead of swallowing the rest of the file
local in_fence="" in_comment=0 in_tag=0 html_stack="" html_lines=0
while IFS= read -r line || [ -n "$line" ]; do
line="${line#"${line%%[![:space:]]*}"}"
if [ "$in_comment" = "1" ]; then
case "$line" in *'-->'*) in_comment=0 ;; esac
continue
fi
if [ "$in_tag" = "1" ]; then
case "$line" in *'>'*) in_tag=0 ;; esac
continue
fi
case "$line" in
'```'*|'~~~'*)
# Typed fences: only the same fence type closes the block, so a ~~~
# line inside a ``` fence (or vice versa) is content, not a toggle.
if [ -n "$in_fence" ]; then
case "$line" in "$in_fence"*) in_fence="" ;; esac
else
in_fence="${line:0:3}"
fi
continue ;;
esac
[ -n "$in_fence" ] && continue
if [ -n "$html_stack" ]; then
html_lines=$((html_lines + 1))
if [ "$html_lines" -gt 50 ]; then
html_stack="" html_lines=0
else
local top="${html_stack##* }"
case "$line" in
'</'"$top"'>'*)
html_stack="${html_stack% *}"
[ -z "$html_stack" ] && html_lines=0 ;;
esac
continue
fi
fi
case "$line" in
''|'#'*) continue ;;
'['*|'!['*) continue ;; # badges, link-only/nav lines
'* '*|'- '*|[0-9]*'. '*) continue ;;
'---'*|'***'*|'==='*) continue ;;
'<!--'*)
case "$line" in *'-->'*) ;; *) in_comment=1 ;; esac
continue ;;
esac
case "$line" in
'<'[a-zA-Z]*)
# no '>' on the line → multi-line tag, skip until it closes
case "$line" in *'>'*) ;; *) in_tag=1; continue ;; esac
local tag
tag="${line#<}"
tag="${tag%% *}"
tag="${tag%%>*}"
case "$tag" in
# void elements never open a block
img|br|hr|source|input|meta|link|area|base|col|embed|track|wbr) ;;
*)
# inline-closed (<h2>Text</h2>) or self-closing (<br/>) don't open
case "$line" in
*'/>'*|*'</'"$tag"'>'*) ;;
*) html_stack="$html_stack $tag" ;;
esac ;;
esac
continue ;;
'</'[a-zA-Z]*) continue ;;
esac
line="${line#> }"
if [ ${#line} -gt 120 ]; then
line="${line:0:120}"
line="${line% *}"
fi
printf '%s\n' "$line"
found=1
break
done < "$file"
[ -n "$found" ]
}
# Resolve a pool repo's display brief via the shared fallback model
# (docs/spec-metadata.md "Fallback Rules"): index cache → memo file → README.
# README/memo fallbacks are display-only and never written back to the index.
# Prints two lines: the resolved brief (possibly empty) and the source tag
# (index|memo|readme|none). Presentation is the caller's job — `orbit repos`
# renders steering notes on stderr (human terminal), while the
# `orbit context --startup` prime roster inlines them as stdout sections
# (hook injection only carries stdout).
orbit_pool_brief() {
local root="$1" index="$2" name="$3" repo_dir="$4"
local brief
brief=$(git config --file "$index" --get "repos.$name.brief" 2>/dev/null || true)
if [ -n "$brief" ]; then