@soleur/opencode 3.378.18 → 3.379.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  # shellcheck shell=bash
2
- # The write chokepoint. Every byte that reaches the report goes through lc_emit_checked.
2
+ # The write chokepoint. Every byte that reaches the report, and every byte the issue writer authors into a tracker (scan-only mode), goes through lc_emit_checked.
3
3
  # Requires SKILL_DIR and PLUGIN_DIR. Test seams (honoured only when LAUNCH_CHECK_TEST=1, see lc_seam):
4
4
  # LAUNCH_CHECK_REDACT_SENTINEL, LAUNCH_CHECK_GITLEAKS. Optional LC_DEST_ROOT: the write must stay inside it.
5
5
  source "$SKILL_DIR/scripts/lib/common.sh"
@@ -39,10 +39,17 @@ lc__emit_body() {
39
39
  command -v "$gl" >/dev/null 2>&1 || lc_abort scanner-missing 2 "gitleaks not found"
40
40
  scratch=$(mktemp -d "${TMPDIR:-/tmp}/lc-gate.XXXXXX") || lc_abort scanner-failed 2 "mktemp failed"
41
41
  trap 'rm -rf -- "${scratch:?}"; [ -z "$tmp" ] || rm -f -- "$tmp"' EXIT
42
+ # Both paths are made absolute BEFORE the scans move to the scratch directory: gitleaks reads .gitleaksignore (and the
43
+ # sentinel its own relative files) from the working directory, so a customer's repository or a plan directory must
44
+ # never be the place the scanners run from.
45
+ case "$scratch" in /*) ;; *) scratch="$PWD/$scratch" ;; esac
46
+ case "$src" in /*) ;; *) src="$PWD/$src" ;; esac
47
+ case "$dest" in ""|/*) ;; *) dest="$PWD/$dest" ;; esac
48
+ cd "$scratch" || lc_abort scanner-failed 2 "scratch directory"
42
49
  bash "$REDACT_SENTINEL" "$src" >/dev/null 2>&1 || s_rc=$?
43
50
  [ "$s_rc" -eq 1 ] && lc_abort redaction-hit 1 "layer=sentinel"
44
51
  [ "$s_rc" -eq 0 ] || lc_abort scanner-failed 2 "sentinel rc=$s_rc"
45
- # The repository's own gitleaks configuration must never relax the gate.
52
+ # The repository's own gitleaks configuration must never relax the gate (the scans run from the scratch directory).
46
53
  env -u GITLEAKS_CONFIG -u GITLEAKS_CONFIG_TOML "$gl" detect --source "$src" --no-git --report-format json --report-path "$scratch/r.json" --redact --exit-code 1 >/dev/null 2>"$scratch/e" || g_rc=$?
47
54
  if [ "$g_rc" -eq 1 ] && grep -q '"RuleID"' "$scratch/r.json" 2>/dev/null; then lc_abort redaction-hit 1 "layer=gitleaks"; fi
48
55
  if [ "$g_rc" -ne 0 ]; then err=$(head -c 160 "$scratch/e" | tr '\n\t' ' '); lc_abort scanner-failed 2 "gitleaks rc=$g_rc: $err"; fi
@@ -52,7 +52,7 @@ lc_clean_facts() {
52
52
  lc_validate_judged() {
53
53
  local out
54
54
  out=$(awk -F'\t' -v cat="$CAT" -v facts="$FACTS" '
55
- FILENAME == cat { if ($4 == "judged") j[$1] = 1; next }
55
+ FILENAME == cat { if ($4 == "judged") j[$1] = 1; else if ($1 != "") c[$1] = 1; next }
56
56
  FILENAME == facts { f[$1] = 1; next }
57
57
  /^#/ || /^$/ { next }
58
58
  { bad = ""
@@ -63,7 +63,7 @@ lc_validate_judged() {
63
63
  else if ($2 == "gap" && $3 != "high" && $3 != "medium" && $3 != "low") bad = "severity"
64
64
  else if ($2 != "gap" && $3 != "-") bad = "severity-must-be-dash-unless-gap"
65
65
  else if ($2 == "gap" && $4 == "-") bad = "evidence-required"
66
- else if ($4 != "-") { k = split($4, ev, ","); for (i = 1; i <= k; i++) if (!(ev[i] in f)) bad = "evidence-id" }
66
+ else if ($4 != "-") { k = split($4, ev, ","); for (i = 1; i <= k; i++) if (!(ev[i] in c) || !(ev[i] in f)) bad = "evidence-id" }
67
67
  seen[$1] = 1
68
68
  if (bad != "") { print "line " FNR ": " bad; exit 1 } }' "$CAT" "$FACTS" "$1") || lc_abort judged-schema 2 "$out"
69
69
  }
@@ -90,16 +90,28 @@ lc_prev_state() {
90
90
  [ "$rc" -eq 0 ] || lc_abort prev-report-invalid 2 "no state block in $REPORT_REL (restore it from git, or delete the file to start fresh)"
91
91
  }
92
92
 
93
- lc_render() {
94
- local rep="$WORK/report.md" prev="$WORK/prev.tsv" gaps="$WORK/gaps.tsv" judged_in="$WORK/judged.in"
95
- local has_prev=0 has_judged=0 prev_hash prev_schema cat_hash today catalog_changed=0
96
- [ -n "${JUDGED:-}" ] && has_judged=1
97
- if [ "$has_judged" = 1 ]; then cp "$JUDGED" "$judged_in"; else : > "$judged_in"; fi
93
+ # lc_prepare_inputs: everything that must happen to the caller's inputs before a report or an issue plan is derived from them.
94
+ # Contract: TARGET, WORK, FACTS, JUDGED (may be empty) are set; sets STACK and CAT, and points FACTS at the sanitized copy.
95
+ # Both render and the issue writer go through here, so a raw facts file can never reach a body.
96
+ lc_prepare_inputs() {
97
+ # scan records the stack in the facts header; only an older or hand-made facts file needs the repository walked again.
98
+ STACK=$(awk -F= '/^# stack=/ {print $2; exit}' "$FACTS")
99
+ if [ -z "$STACK" ]; then lc_walk "$TARGET" "$WORK/files"; STACK=$(lc_stack "$WORK/files"); fi
100
+ CAT="$WORK/catalog.tsv"; lc_build_catalog "$CAT"
101
+ lc_clean_facts
102
+ [ -z "${JUDGED:-}" ] || lc_validate_judged "$JUDGED"
103
+ }
104
+
105
+ # lc_compute_gaps: the one partition of findings into open and accepted, shared by render and the issue writer so the report
106
+ # and the issues cannot disagree. Needs lc_prepare_inputs first. Writes into $WORK: judged.in (a copy of the judged file, empty
107
+ # when there is none), prev.tsv and prev.tsv.bad (the previous report's state lines), gaps.tsv (rank, id, domain, class, severity,
108
+ # title, evidence, closing command, remedy; critical first, then by id), prev.accepted.ids, cur.ids, open.ids, accepted.ids,
109
+ # prev.ids, cat.ids and new.ids. Whether a previous report existed is `[ -f "$TARGET/$REPORT_REL" ]`.
110
+ lc_compute_gaps() {
111
+ local prev="$WORK/prev.tsv" gaps="$WORK/gaps.tsv" judged_in="$WORK/judged.in" has_prev=0
112
+ if [ -n "${JUDGED:-}" ]; then cp "$JUDGED" "$judged_in"; else : > "$judged_in"; fi
98
113
  lc_prev_state "$TARGET/$REPORT_REL" "$prev"
99
114
  [ -f "$TARGET/$REPORT_REL" ] && has_prev=1
100
- cat_hash=$(git hash-object --stdin < "$CAT")
101
- today=$(date -u +%F)
102
-
103
115
  # Open gaps (deterministic facts + judged), sorted critical -> low then id.
104
116
  awk -F'\t' -v OFS='\t' -v cat="$CAT" -v facts="$FACTS" -v judged="$judged_in" '
105
117
  function rank(s) { return s == "critical" ? 1 : s == "high" ? 2 : s == "medium" ? 3 : 4 }
@@ -116,6 +128,15 @@ lc_render() {
116
128
  cut -f1 "$prev" | sort > "$WORK/prev.ids"
117
129
  cut -f1 "$CAT" | sort > "$WORK/cat.ids"
118
130
  if [ "$has_prev" = 1 ]; then comm -23 "$WORK/open.ids" "$WORK/prev.ids" > "$WORK/new.ids"; else : > "$WORK/new.ids"; fi
131
+ }
132
+
133
+ lc_render() {
134
+ local rep="$WORK/report.md" prev="$WORK/prev.tsv" gaps="$WORK/gaps.tsv" judged_in="$WORK/judged.in"
135
+ local has_prev=0 prev_hash prev_schema cat_hash today catalog_changed=0
136
+ lc_compute_gaps
137
+ [ -f "$TARGET/$REPORT_REL" ] && has_prev=1
138
+ cat_hash=$(git hash-object --stdin < "$CAT")
139
+ today=$(date -u +%F)
119
140
  # Positive evidence that a check ran clean: a deterministic fact with status ok, or a judged line saying ok/na.
120
141
  awk -F'\t' '$2 == "ok" {print $1}' "$FACTS" | sort -u > "$WORK/ok.ids"
121
142
  awk -F'\t' '!/^#/ && ($2 == "ok" || $2 == "na") {print $1}' "$judged_in" | sort -u > "$WORK/judged.settled.ids"
@@ -0,0 +1,12 @@
1
+ <!-- launch-check:epic -->
2
+
3
+ > **How to read this report.** It lists gaps identified by an automated scan of the files in this repository and by a short AI-assisted review of four areas. It is not a security review, a penetration test, legal advice, or an attestation of any standard. A gap that is not listed was not identified in the files read; that is not assurance that none exists. Findings can be wrong. The scan covers the last commit, not git history: a secret removed from the current tree may still be live in history, so rotate it. Keep this file in a private repository: it lists weaknesses that have not been fixed yet.
4
+
5
+ # Launch-check gaps
6
+
7
+ This issue tracks the gaps found by a launch-check run on this repository. Each gap is its own sub-issue.
8
+
9
+ <!-- launch-check:begin -->
10
+ <!-- launch-check:end -->
11
+
12
+ Add your own notes anywhere outside the marked section; a re-run leaves them as they are.
@@ -0,0 +1,13 @@
1
+ <!-- launch-check:gap=CI-01 -->
2
+
3
+ > **How to read this report.** It lists gaps identified by an automated scan of the files in this repository and by a short AI-assisted review of four areas. It is not a security review, a penetration test, legal advice, or an attestation of any standard. A gap that is not listed was not identified in the files read; that is not assurance that none exists. Findings can be wrong. The scan covers the last commit, not git history: a secret removed from the current tree may still be live in history, so rotate it. Keep this file in a private repository: it lists weaknesses that have not been fixed yet.
4
+
5
+ **Severity:** high. **Domain:** Tests & CI/CD. **Check:** CI-01.
6
+
7
+ **Finding:** CI workflow present
8
+
9
+ **Evidence:** `missing: .github/workflows/*.yml`
10
+
11
+ **Fix:** Add CI that builds and tests every pull request.
12
+
13
+ If this does not apply to your repository, close the issue rather than removing its label.
@@ -0,0 +1,8 @@
1
+ repo=acme-fixture/launch-demo
2
+ host=github.com
3
+ visibility=PRIVATE
4
+ catalog_hash=da39a3ee5e6b4b0d3255bfef95601890afd80709
5
+ report_hash=e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
6
+ created=2026-11-03T00:00:00Z
7
+ id severity domain class action title
8
+ CI-01 high tests-ci readiness create CI workflow present
@@ -0,0 +1,392 @@
1
+ #!/usr/bin/env bash
2
+ # gh-stub.sh: a stateful fake of the GitHub CLI for test/issues-common.sh (sourced by issues-guards.test.sh and issues-resume.test.sh). The suite copies this file to <bin>/gh and
3
+ # puts <bin> first on PATH. It never touches the network and never reads a credential.
4
+ #
5
+ # STUB CONTRACT. Each emulated shape is marked either
6
+ # [verified 2026-11-03] checked against a real response when this stub was written (gh 2.103.3), or
7
+ # [UNVERIFIED-STUB-ONLY] invented here from documentation; a suite row that depends on it is tagged in its label.
8
+ # The live check of the unverified shapes is the tracked follow-up (#11956); nothing here is proof of GitHub's behaviour.
9
+ # gh auth status [--hostname H] exit 0, or 1 under GH_STUB_AUTH=fail [UNVERIFIED-STUB-ONLY]
10
+ # gh repo view --json F[,F] [--jq E] F in nameWithOwner,isFork,isArchived,visibility,url,name,owner;
11
+ # any other field exits 1 "Unknown JSON field" [UNVERIFIED-STUB-ONLY]
12
+ # gh api -X GET <path> [-f k=v]... [--jq E] [--paginate] [--hostname H]
13
+ # repos/O/R object with visibility, archived, has_issues, fork, permissions.push [UNVERIFIED-STUB-ONLY]
14
+ # repos/O/R/issues listing: labels, state, per_page, page; default page size 30; --jq runs per page;
15
+ # rows carry number, id, state, title, body (may be null), labels, user.login, and
16
+ # pull_request only for a PR [verified 2026-11-03: rows and the -X GET -f ... --paginate form]
17
+ # repos/O/R/issues/N one issue [UNVERIFIED-STUB-ONLY]
18
+ # repos/O/R/issues/N/sub_issues 200 and a list of children [verified 2026-11-03: the 200 on a real repository]
19
+ # repos/O/R/labels listing [UNVERIFIED-STUB-ONLY]
20
+ # user {"login": GH_STUB_LOGIN} [UNVERIFIED-STUB-ONLY]
21
+ # gh api -X POST repos/O/R/labels -f name= -f color= -f description= 201, or 422 already_exists [UNVERIFIED-STUB-ONLY]
22
+ # gh api -X POST repos/O/R/issues -f title= -F body=@file|-f body= -f labels[]=...
23
+ # 201 with .number and .id (a database id far above 2^31);
24
+ # a label that does not exist is a 422 (stricter than GitHub) [UNVERIFIED-STUB-ONLY]
25
+ # gh api -X POST repos/O/R/issues/N/sub_issues -F sub_issue_id=<integer>
26
+ # GH_STUB_SUBISSUE=ok|403|404|410|422 [UNVERIFIED-STUB-ONLY bodies];
27
+ # a string-typed sub_issue_id (-f) or a second parent is a 422
28
+ # gh api -X PATCH repos/O/R/issues/N -F body=@file the only accepted field keys are body and title [UNVERIFIED-STUB-ONLY]
29
+ # Failure output: stderr "gh: <message> (HTTP <code>)" and the JSON error body on stdout. [UNVERIFIED-STUB-ONLY]
30
+ # gojq differs from jq on null handling; this stub runs real jq, so null-body rows are tagged UNVERIFIED-STUB-ONLY.
31
+ #
32
+ # Contract enforcement (a stub that accepts anything proves nothing): an unknown subcommand, flag or method exits 64 with a
33
+ # REFUSE line in refused.log; a field key outside title, body, labels[], sub_issue_id, name, color, description exits 64;
34
+ # an api call that carries no explicit -X is written to violations.log (a field flag flips an implicit call to POST).
35
+ #
36
+ # State directory (GH_STUB_STATE): repo.json, labels.json, issues.json, calls.log (JSON lines, one per MATCHED call,
37
+ # written inside the dispatch branch only), refused.log, violations.log, pages.log, bodies/<seq>-<key> (the bytes
38
+ # received for every body field, stored independently of the caller's own files).
39
+ # Failure injection (environment): GH_STUB_AUTH=ok|fail; GH_STUB_REPO=ok|unresolved|ambiguous; GH_STUB_HOST (default
40
+ # github.com); GH_STUB_LOGIN (default stub-user); GH_STUB_FAIL_AFTER=<n> (every item create after the n-th fails, the
41
+ # epic is not counted); GH_STUB_FAIL_KIND=server|ratelimit|secret; GH_STUB_TRANSPORT_ERROR_AFTER_CREATE=<n> (alias
42
+ # GH_STUB_KILL_AFTER_CREATE: right after storing the n-th item create exit 1 with no output, once; the harness is never
43
+ # killed); GH_STUB_SUBISSUE=ok|403|404|410|422|ratelimit|502 (the link POST only); GH_STUB_SLEEP=<seconds> (an item create sleeps that long after storing the issue, before it answers: a window for a signal); GH_STUB_PER_PAGE=<n> (forces pagination); GH_STUB_EDIT_EPIC_BETWEEN=get|write (a customer
44
+ # edit of the epic body: before serving the first epic GET that follows a listing, or after the first item create);
45
+ # GH_STUB_CRLF=1 (the epic body is stored with CRLF line endings); GH_STUB_LIST=ok|fail|emptyfail|malformed (the issue listing; emptyfail is exit 1
46
+ # with nothing on stdout or stderr); GH_STUB_FAIL_ROUTE=<names, comma separated> (labels-get, labels-post, epic-post, epic-patch, user-get: that call
47
+ # answers HTTP 500); GH_STUB_PAGE_FAIL_AFTER=<n> (a paginated read serves n pages, then fails with HTTP 502); GH_STUB_LABELS_STALE=1 (the labels
48
+ # listing answers an empty list while the labels POST still sees the real set: a label created by someone else after the listing).
49
+ set -u
50
+ S=${GH_STUB_STATE:-}
51
+ if [ -z "$S" ] || [ ! -d "$S" ]; then printf 'gh-stub: REFUSE GH_STUB_STATE unset or missing\n' >&2; exit 64; fi
52
+ mkdir -p "$S/bodies"
53
+ HOST=${GH_STUB_HOST:-github.com}
54
+ LOGIN=${GH_STUB_LOGIN:-stub-user}
55
+
56
+ refuse() { printf '%s\n' "$*" >> "$S/refused.log"; printf 'gh-stub: REFUSE %s\n' "$*" >&2; exit 64; }
57
+ violation() { printf '%s\n' "$*" >> "$S/violations.log"; }
58
+ counter() { # counter <name>: increment and print
59
+ local n; n=$(( $(cat "$S/$1" 2>/dev/null || echo 0) + 1 )); printf '%s' "$n" > "$S/$1"; printf '%s' "$n"
60
+ }
61
+ secret_shaped() { printf '%s%s' 'ghp_' 'Q3nW8tY1kD6vB2xM9cL5hZ7pR4aE0sJ2fG1u'; }
62
+ http_fail() { # http_fail <code> <message> [extra stderr line]
63
+ printf '{"message":"%s","status":"%s"}\n' "$2" "$1"
64
+ printf 'gh: %s (HTTP %s)\n' "$2" "$1" >&2
65
+ [ -n "${3:-}" ] && printf '%s\n' "$3" >&2
66
+ exit 1
67
+ }
68
+ env_json() { # names of the hostile variables that are set, with their values (never a token)
69
+ local v out='{}'
70
+ for v in GH_REPO GH_HOST GH_ENTERPRISE_TOKEN GITHUB_ENTERPRISE_TOKEN GH_DEBUG DEBUG GH_CONFIG_DIR GH_PATH GH_FORCE_TTY SSL_CERT_FILE SSL_CERT_DIR HTTP_PROXY HTTPS_PROXY ALL_PROXY NO_PROXY http_proxy https_proxy all_proxy no_proxy; do
71
+ if [ -n "${!v+x}" ]; then
72
+ case "$v" in GH_ENTERPRISE_TOKEN|GITHUB_ENTERPRISE_TOKEN) out=$(jq -nc --argjson o "$out" --arg k "$v" '$o + {($k): "(set)"}') ;;
73
+ *) out=$(jq -nc --argjson o "$out" --arg k "$v" --arg val "${!v}" '$o + {($k): $val}') ;; esac
74
+ fi
75
+ done
76
+ printf '%s' "$out"
77
+ }
78
+ record() { # record <class> <method> <path> <explicit 0|1> [extra-json-object]
79
+ local seq; seq=$(counter seq)
80
+ CUR_SEQ=$seq
81
+ jq -nc --argjson seq "$seq" --arg class "$1" --arg method "$2" --arg path "$3" --argjson explicit "$4" \
82
+ --argjson fields "${FIELDS:-[]}" --arg jq "${JQEXPR:-}" --argjson paginate "${PAGINATE:-0}" --arg hostname "${HOSTNAME_FLAG:-}" \
83
+ --argjson env "$(env_json)" --arg cwd "$PWD" --arg stdin "$(readlink "/proc/$$/fd/0" 2>/dev/null || echo unknown)" --argjson token "$([ -n "${GH_TOKEN:-}" ] && echo true || echo false)" \
84
+ --argjson extra "${5:-{\}}" \
85
+ '{seq:$seq,class:$class,method:$method,path:$path,explicit_method:($explicit==1),fields:$fields,jq:$jq,paginate:($paginate==1),hostname:$hostname,env:$env,cwd:$cwd,stdin:$stdin,token_present:$token} + $extra' >> "$S/calls.log"
86
+ }
87
+ jq_out() { # jq_out <json> : apply --jq (real jq -r) or print compact JSON
88
+ if [ -n "${JQEXPR:-}" ]; then printf '%s' "$1" | jq -r "$JQEXPR" || exit 1; else printf '%s' "$1" | jq -c .; fi
89
+ }
90
+ repo_field() { jq -r "$1" "$S/repo.json"; }
91
+ route_fails() { # route_fails <name>: GH_STUB_FAIL_ROUTE names this call
92
+ case ",${GH_STUB_FAIL_ROUTE:-}," in *",$1,"*) return 0 ;; esac
93
+ return 1
94
+ }
95
+ need_auth() { if [ "${GH_STUB_AUTH:-ok}" = fail ]; then printf 'gh: To use GitHub CLI, run: gh auth login\n' >&2; exit 4; fi; }
96
+
97
+ sub=${1:-}; [ $# -gt 0 ] && shift
98
+ case "$sub" in
99
+ --version)
100
+ record other VERSION "--version" 0; printf 'gh version 2.103.3 (stub)\n'; exit 0 ;;
101
+ auth)
102
+ [ "${1:-}" = status ] || refuse "auth subcommand ${1:-}"
103
+ shift; host=""
104
+ while [ $# -gt 0 ]; do case "$1" in --hostname) host=${2:-}; shift 2 ;; *) refuse "auth status flag $1" ;; esac; done
105
+ FIELDS='[]'; HOSTNAME_FLAG=$host; record auth GET "auth status" 0
106
+ if [ "${GH_STUB_AUTH:-ok}" = fail ]; then printf 'You are not logged into any GitHub hosts. To log in, run: gh auth login\n' >&2; exit 1; fi
107
+ printf '%s\n Logged in to %s account %s (keyring)\n' "$HOST" "$HOST" "$LOGIN"; exit 0 ;;
108
+ repo)
109
+ [ "${1:-}" = view ] || refuse "repo subcommand ${1:-}"
110
+ shift; json=""; JQEXPR=""
111
+ while [ $# -gt 0 ]; do case "$1" in --json) json=${2:-}; shift 2 ;; --jq|-q) JQEXPR=${2:-}; shift 2 ;; *) refuse "repo view argument $1" ;; esac; done
112
+ [ -n "$json" ] || refuse "repo view without --json"
113
+ FIELDS='[]'; record repo GET "repo view" 0 "$(jq -nc --arg j "$json" '{json:$j}')"
114
+ need_auth
115
+ case "${GH_STUB_REPO:-ok}" in
116
+ unresolved) printf 'none of the git remotes configured for this repository point to a known GitHub host. To tell gh about a new GitHub host, please use `gh auth login`\n' >&2; exit 1 ;;
117
+ ambiguous) printf 'multiple remotes detected. please specify which repo to use by providing the -R, --repo argument, or run `gh repo set-default`\n' >&2; exit 1 ;;
118
+ esac
119
+ obj='{}'
120
+ IFS=, read -r -a want <<<"$json"
121
+ for f in "${want[@]}"; do
122
+ case "$f" in
123
+ nameWithOwner) v=$(repo_field '.full_name') ;;
124
+ name) v=$(repo_field '.name') ;;
125
+ owner) v=$(repo_field '.owner.login') ;;
126
+ isFork) v=$(repo_field '.fork') ;;
127
+ isArchived) v=$(repo_field '.archived') ;;
128
+ visibility) v=$(repo_field '.visibility|ascii_upcase') ;;
129
+ url) v="https://$HOST/$(repo_field '.full_name')" ;;
130
+ *) printf 'Unknown JSON field: "%s"\n' "$f" >&2; exit 1 ;;
131
+ esac
132
+ case "$f" in isFork|isArchived) obj=$(jq -nc --argjson o "$obj" --arg k "$f" --argjson v "$v" '$o + {($k): $v}') ;;
133
+ *) obj=$(jq -nc --argjson o "$obj" --arg k "$f" --arg v "$v" '$o + {($k): $v}') ;; esac
134
+ done
135
+ jq_out "$obj"; exit 0 ;;
136
+ api) ;;
137
+ *) refuse "subcommand $sub" ;;
138
+ esac
139
+
140
+ # ---- gh api ----
141
+ METHOD=""; EXPLICIT=0; JQEXPR=""; PAGINATE=0; HOSTNAME_FLAG=""; ENDPOINT=""; FIELDS='[]'
142
+ FK=(); FV=(); FT=()
143
+ while [ $# -gt 0 ]; do
144
+ case "$1" in
145
+ -X|--method) [ $# -ge 2 ] || refuse "api flag $1 needs a value"; METHOD=$(printf '%s' "$2" | tr '[:lower:]' '[:upper:]'); EXPLICIT=1; shift 2 ;;
146
+ -f|--raw-field|-F|--field)
147
+ [ $# -ge 2 ] || refuse "api flag $1 needs a value"
148
+ t=f; case "$1" in -F|--field) t=F ;; esac
149
+ kv=$2; case "$kv" in *=*) ;; *) refuse "api field without =: $kv" ;; esac
150
+ FK+=("${kv%%=*}"); FV+=("${kv#*=}"); FT+=("$t"); shift 2 ;;
151
+ --jq|-q) [ $# -ge 2 ] || refuse "api flag $1 needs a value"; JQEXPR=$2; shift 2 ;;
152
+ --paginate) PAGINATE=1; shift ;;
153
+ --hostname) [ $# -ge 2 ] || refuse "api flag $1 needs a value"; HOSTNAME_FLAG=$2; shift 2 ;;
154
+ -*) refuse "api flag $1" ;;
155
+ *) [ -z "$ENDPOINT" ] || refuse "api extra positional $1"; ENDPOINT=$1; shift ;;
156
+ esac
157
+ done
158
+ [ -n "$ENDPOINT" ] || refuse "api without an endpoint"
159
+ nf=${#FK[@]}
160
+ if [ -z "$METHOD" ]; then
161
+ if [ "$nf" -gt 0 ]; then METHOD=POST; else METHOD=GET; fi
162
+ fi
163
+ case "$METHOD" in GET|POST|PATCH) ;; *) refuse "api method $METHOD" ;; esac
164
+ ENDPOINT=${ENDPOINT#/}
165
+ QUERY=""; case "$ENDPOINT" in *\?*) QUERY=${ENDPOINT#*\?}; ENDPOINT=${ENDPOINT%%\?*} ;; esac
166
+ # Field-key allowlist (an independent witness of the wrapper's own list).
167
+ i=0
168
+ while [ "$i" -lt "$nf" ]; do
169
+ case "${FK[$i]}" in
170
+ title|body|'labels[]'|sub_issue_id|name|color|description) ;;
171
+ *) if [ "$METHOD" != GET ]; then refuse "field key ${FK[$i]}"; fi ;;
172
+ esac
173
+ i=$((i + 1))
174
+ done
175
+ [ "$EXPLICIT" = 1 ] || violation "implicit-method $ENDPOINT"
176
+
177
+ # Build the fields JSON (and store every body-like field's bytes independently).
178
+ CUR_SEQ=$(( $(cat "$S/seq" 2>/dev/null || echo 0) + 1 ))
179
+ i=0
180
+ while [ "$i" -lt "$nf" ]; do
181
+ k=${FK[$i]}; v=${FV[$i]}; t=${FT[$i]}
182
+ if [ "$t" = F ] && [ "${v#@}" != "$v" ]; then
183
+ path=${v#@}
184
+ [ "$path" != "-" ] || refuse "stdin field operand"
185
+ if [ ! -f "$path" ]; then printf 'open %s: no such file or directory\n' "$path" >&2; exit 1; fi
186
+ if [ "$METHOD" != GET ]; then cp "$path" "$S/bodies/$CUR_SEQ-${k//[^A-Za-z0-9]/_}"; fi
187
+ FIELDS=$(jq -nc --argjson a "$FIELDS" --arg k "$k" --arg v "$v" --arg t "$t" --arg file "$path" --rawfile c "$path" \
188
+ --arg stored "bodies/$CUR_SEQ-${k//[^A-Za-z0-9]/_}" '$a + [{k:$k,v:$v,t:$t,file:$file,content:$c,stored:$stored}]')
189
+ else
190
+ FIELDS=$(jq -nc --argjson a "$FIELDS" --arg k "$k" --arg v "$v" --arg t "$t" '$a + [{k:$k,v:$v,t:$t}]')
191
+ if [ "$METHOD" != GET ] && [ "$k" = body ]; then printf '%s' "$v" > "$S/bodies/$CUR_SEQ-body"; fi
192
+ fi
193
+ i=$((i + 1))
194
+ done
195
+
196
+ fld() { # fld <key>: first value of a field (or query) key
197
+ jq -rn --argjson f "$FIELDS" --arg k "$1" --arg q "$QUERY" '
198
+ ([$f[] | select(.k == $k) | .v] | first) // ([$q | split("&")[] | select(startswith($k + "=")) | sub("^[^=]*="; "")] | first) // empty'
199
+ }
200
+ fld_all() { jq -rn --argjson f "$FIELDS" --arg k "$1" '$f[] | select(.k == $k) | .v'; }
201
+ fld_type() { jq -rn --argjson f "$FIELDS" --arg k "$1" '[$f[] | select(.k == $k) | .t] | first // empty'; }
202
+
203
+ repo_ok() { # the path's owner/name must be the stub's repository
204
+ local want; want=$(repo_field '.full_name' | tr '[:upper:]' '[:lower:]')
205
+ [ "$(printf '%s/%s' "$1" "$2" | tr '[:upper:]' '[:lower:]')" = "$want" ]
206
+ }
207
+ issue_pub='del(.parent)'
208
+ PATTERN_REPO='^repos/([^/]+)/([^/]+)$'
209
+ PATTERN_SUB='^repos/([^/]+)/([^/]+)/issues/([0-9]+)/sub_issues$'
210
+ PATTERN_ONE='^repos/([^/]+)/([^/]+)/issues/([0-9]+)$'
211
+ PATTERN_LIST='^repos/([^/]+)/([^/]+)/(issues|labels)$'
212
+
213
+ paginate_emit() { # paginate_emit <json array>: pages of per_page (default 30), jq per page, pages.log
214
+ local arr=$1 per total n s pages=0 slice
215
+ per=$(fld per_page); per=${per:-30}; [ -n "${GH_STUB_PER_PAGE:-}" ] && per=$GH_STUB_PER_PAGE
216
+ total=$(jq 'length' <<<"$arr")
217
+ if [ "$PAGINATE" = 0 ]; then
218
+ slice=$(jq -c --argjson s 0 --argjson n "$per" '.[$s:$s+$n]' <<<"$arr"); pages=1; jq_out "$slice"
219
+ else
220
+ s=0
221
+ while :; do
222
+ n=$(jq -r --argjson s "$s" --argjson n "$per" '.[$s:$s+$n] | length' <<<"$arr")
223
+ slice=$(jq -c --argjson s "$s" --argjson n "$per" '.[$s:$s+$n]' <<<"$arr")
224
+ pages=$((pages + 1)); jq_out "$slice" || exit 1
225
+ if [ -n "${GH_STUB_PAGE_FAIL_AFTER:-}" ] && [ "$pages" -ge "$GH_STUB_PAGE_FAIL_AFTER" ] && [ "$((s + per))" -lt "$total" ]; then
226
+ printf '%s\t%s\n' "$CUR_SEQ" "$pages" >> "$S/pages.log"; printf 'gh: Server Error (HTTP 502)\n' >&2; exit 1
227
+ fi
228
+ s=$((s + per)); [ "$n" -ge "$per" ] && [ "$s" -lt "$total" ] || break
229
+ done
230
+ fi
231
+ printf '%s\t%s\n' "$CUR_SEQ" "$pages" >> "$S/pages.log"
232
+ }
233
+
234
+ route="$METHOD $ENDPOINT"
235
+ case "$route" in
236
+ "GET user")
237
+ record read GET "$ENDPOINT" "$EXPLICIT"; need_auth
238
+ ! route_fails user-get || http_fail 500 "Server Error"
239
+ jq_out "$(jq -nc --arg l "$LOGIN" '{login:$l}')"; exit 0 ;;
240
+ esac
241
+
242
+ if [[ "$ENDPOINT" =~ $PATTERN_REPO ]]; then
243
+ if [ "$METHOD" = GET ]; then
244
+ record read GET "$ENDPOINT" "$EXPLICIT"; need_auth
245
+ repo_ok "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" || http_fail 404 "Not Found"
246
+ jq_out "$(cat "$S/repo.json")"; exit 0
247
+ fi
248
+ fi
249
+
250
+ if [[ "$ENDPOINT" =~ $PATTERN_LIST ]]; then
251
+ o=${BASH_REMATCH[1]}; r=${BASH_REMATCH[2]}; kind=${BASH_REMATCH[3]}
252
+ if [ "$METHOD" = GET ] && [ "$kind" = labels ]; then
253
+ record read GET "$ENDPOINT" "$EXPLICIT"; need_auth
254
+ repo_ok "$o" "$r" || http_fail 404 "Not Found"
255
+ ! route_fails labels-get || http_fail 500 "Server Error"
256
+ if [ "${GH_STUB_LABELS_STALE:-0}" = 1 ]; then paginate_emit '[]'; exit 0; fi
257
+ paginate_emit "$(cat "$S/labels.json")"; exit 0
258
+ fi
259
+ if [ "$METHOD" = POST ] && [ "$kind" = labels ]; then
260
+ record write POST "$ENDPOINT" "$EXPLICIT"; need_auth
261
+ repo_ok "$o" "$r" || http_fail 404 "Not Found"
262
+ ! route_fails labels-post || http_fail 500 "Server Error"
263
+ name=$(fld name); color=$(fld color); desc=$(fld description)
264
+ [ -n "$name" ] || http_fail 422 "Validation Failed"
265
+ if jq -e --arg n "$name" 'map(.name | ascii_downcase) | index($n | ascii_downcase)' "$S/labels.json" >/dev/null; then
266
+ # the error body (with its errors array) is on STDOUT, as the CLI prints it; stderr carries only the one-line message
267
+ printf '{"message":"Validation Failed","errors":[{"resource":"Label","code":"already_exists","field":"name"}],"status":"422"}\n'
268
+ printf 'gh: Validation Failed (HTTP 422)\n' >&2
269
+ exit 1
270
+ fi
271
+ new=$(jq -nc --arg n "$name" --arg c "${color:-ededed}" --arg d "$desc" '{name:$n,color:$c,description:$d}')
272
+ jq -c --argjson l "$new" '. + [$l]' "$S/labels.json" > "$S/labels.json.new" && mv "$S/labels.json.new" "$S/labels.json"
273
+ jq_out "$new"; exit 0
274
+ fi
275
+ if [ "$METHOD" = GET ] && [ "$kind" = issues ]; then
276
+ record read GET "$ENDPOINT" "$EXPLICIT"; need_auth
277
+ repo_ok "$o" "$r" || http_fail 404 "Not Found"
278
+ case "${GH_STUB_LIST:-ok}" in
279
+ fail) http_fail 500 "Server Error" ;;
280
+ emptyfail) exit 1 ;;
281
+ malformed) printf '<<not a listing>>\n\037\n'; exit 0 ;;
282
+ esac
283
+ st=$(fld state); st=${st:-open}; lab=$(fld labels)
284
+ touch "$S/listing_seen"
285
+ arr=$(jq -c --arg st "$st" --arg lab "$lab" '
286
+ [.[] | select($st == "all" or .state == $st)
287
+ | select($lab == "" or ((.labels | map(.name)) as $n | ($lab | split(",")) | all(. as $w | $n | index($w))))
288
+ | del(.parent)]' "$S/issues.json")
289
+ paginate_emit "$arr"; exit 0
290
+ fi
291
+ if [ "$METHOD" = POST ] && [ "$kind" = issues ]; then
292
+ record write POST "$ENDPOINT" "$EXPLICIT"; need_auth
293
+ repo_ok "$o" "$r" || http_fail 404 "Not Found"
294
+ title=$(fld title); [ -n "$title" ] || http_fail 422 "Validation Failed"
295
+ labs=$(fld_all 'labels[]' | jq -R . | jq -sc .)
296
+ epic=false; jq -e 'index("lc:epic")' <<<"$labs" >/dev/null && epic=true
297
+ if [ "$epic" = true ] && route_fails epic-post; then http_fail 500 "Server Error"; fi
298
+ missing=$(jq -nr --argjson l "$labs" --slurpfile all "$S/labels.json" '[$l[] | select(. as $w | ($all[0] | map(.name) | index($w)) == null)] | join(",")')
299
+ [ -z "$missing" ] || http_fail 422 "Validation Failed"
300
+ if [ "$epic" = false ]; then
301
+ done_n=$(cat "$S/creates" 2>/dev/null || echo 0)
302
+ if [ -n "${GH_STUB_FAIL_AFTER:-}" ] && [ "$done_n" -ge "$GH_STUB_FAIL_AFTER" ]; then
303
+ case "${GH_STUB_FAIL_KIND:-server}" in
304
+ ratelimit) http_fail 403 "You have exceeded a secondary rate limit. Please wait a few minutes before you try again." ;;
305
+ secret) http_fail 502 "Server Error" "request id token=$(secret_shaped)" ;;
306
+ *) http_fail 502 "Server Error" ;;
307
+ esac
308
+ fi
309
+ fi
310
+ bodyf="$S/bodies/$CUR_SEQ-body"; [ -f "$bodyf" ] || : > "$bodyf"
311
+ crlf=false; [ "$epic" = true ] && [ "${GH_STUB_CRLF:-0}" = 1 ] && crlf=true
312
+ num=$(( $(cat "$S/next_number" 2>/dev/null || echo 100) + 1 )); printf '%s' "$num" > "$S/next_number"
313
+ id=$((4000000000 + num * 13))
314
+ new=$(jq -nc --argjson n "$num" --argjson id "$id" --arg t "$title" --rawfile b "$bodyf" --argjson crlf "$crlf" --arg login "$LOGIN" --argjson l "$labs" \
315
+ '{number:$n,id:$id,state:"open",title:$t,body:(if $crlf then ($b | gsub("\n"; "\r\n")) else $b end),labels:($l|map({name:.})),user:{login:$login},parent:null,html_url:("https://example.invalid/issues/"+($n|tostring))}')
316
+ jq -c --argjson i "$new" '. + [$i]' "$S/issues.json" > "$S/issues.json.new" && mv "$S/issues.json.new" "$S/issues.json"
317
+ if [ "$epic" = false ]; then
318
+ made=$(counter creates)
319
+ if [ "${GH_STUB_EDIT_EPIC_BETWEEN:-}" = write ] && [ ! -e "$S/epic_edit_write_done" ]; then
320
+ : > "$S/epic_edit_write_done"
321
+ jq -c '(.[] | select(.labels | map(.name) | index("lc:epic"))) |= (.body += "\nCUSTOMER-EDIT-MIDRUN\n")' "$S/issues.json" > "$S/issues.json.new" && mv "$S/issues.json.new" "$S/issues.json"
322
+ printf 'epic edited after item create %s\n' "$made" >> "$S/events.log"
323
+ fi
324
+ [ -z "${GH_STUB_SLEEP:-}" ] || sleep "$GH_STUB_SLEEP"
325
+ tx=${GH_STUB_TRANSPORT_ERROR_AFTER_CREATE:-${GH_STUB_KILL_AFTER_CREATE:-}}
326
+ if [ -n "$tx" ] && [ "$made" = "$tx" ] && [ ! -e "$S/transport_fired" ]; then : > "$S/transport_fired"; exit 1; fi
327
+ fi
328
+ jq_out "$(jq -c "$issue_pub" <<<"$new")"; exit 0
329
+ fi
330
+ fi
331
+
332
+ if [[ "$ENDPOINT" =~ $PATTERN_SUB ]]; then
333
+ o=${BASH_REMATCH[1]}; r=${BASH_REMATCH[2]}; n=${BASH_REMATCH[3]}
334
+ cls="read"; if [ "$METHOD" = POST ]; then cls="write"; fi
335
+ [ "$METHOD" = GET ] || [ "$METHOD" = POST ] || refuse "sub_issues method $METHOD"
336
+ record "$cls" "$METHOD" "$ENDPOINT" "$EXPLICIT"; need_auth
337
+ repo_ok "$o" "$r" || http_fail 404 "Not Found"
338
+ case "${GH_STUB_SUBISSUE:-ok}" in
339
+ ok) ;;
340
+ 403) http_fail 403 "Forbidden" ;;
341
+ 404) http_fail 404 "Not Found" ;;
342
+ 410) http_fail 410 "Gone" ;;
343
+ 422) http_fail 422 "Validation Failed" ;;
344
+ ratelimit) http_fail 403 "You have exceeded a secondary rate limit. Please wait a few minutes before you try again." ;;
345
+ 502) http_fail 502 "Server Error" ;;
346
+ esac
347
+ jq -e --argjson n "$n" 'map(select(.number == $n)) | length > 0' "$S/issues.json" >/dev/null || http_fail 404 "Not Found"
348
+ if [ "$METHOD" = GET ]; then
349
+ paginate_emit "$(jq -c --argjson n "$n" '[.[] | select(.parent == $n) | del(.parent)]' "$S/issues.json")"; exit 0
350
+ fi
351
+ sid=$(fld sub_issue_id)
352
+ if [ "$(fld_type sub_issue_id)" != F ] || ! [[ "$sid" =~ ^[0-9]+$ ]]; then
353
+ violation "sub_issue_id-not-integer $sid"; http_fail 422 "Validation Failed"
354
+ fi
355
+ jq -e --argjson id "$sid" 'map(select(.id == $id)) | length > 0' "$S/issues.json" >/dev/null || http_fail 404 "Not Found"
356
+ if jq -e --argjson id "$sid" 'map(select(.id == $id and .parent != null)) | length > 0' "$S/issues.json" >/dev/null; then http_fail 422 "Validation Failed"; fi
357
+ jq -c --argjson id "$sid" --argjson n "$n" '(.[] | select(.id == $id) | .parent) |= $n' "$S/issues.json" > "$S/issues.json.new" && mv "$S/issues.json.new" "$S/issues.json"
358
+ jq_out "$(jq -c --argjson n "$n" '.[] | select(.number == $n) | del(.parent)' "$S/issues.json")"; exit 0
359
+ fi
360
+
361
+ if [[ "$ENDPOINT" =~ $PATTERN_ONE ]]; then
362
+ o=${BASH_REMATCH[1]}; r=${BASH_REMATCH[2]}; n=${BASH_REMATCH[3]}
363
+ if [ "$METHOD" = GET ]; then
364
+ record read GET "$ENDPOINT" "$EXPLICIT"; need_auth
365
+ repo_ok "$o" "$r" || http_fail 404 "Not Found"
366
+ if [ "${GH_STUB_EDIT_EPIC_BETWEEN:-}" = get ] && [ -e "$S/listing_seen" ] && [ ! -e "$S/epic_edited" ] \
367
+ && jq -e --argjson n "$n" '.[] | select(.number == $n) | .labels | map(.name) | index("lc:epic")' "$S/issues.json" >/dev/null; then
368
+ : > "$S/epic_edited"
369
+ jq -c '(.[] | select(.labels | map(.name) | index("lc:epic"))) |= (.body += "\nCUSTOMER-EDIT-MIDRUN\n")' "$S/issues.json" > "$S/issues.json.new" && mv "$S/issues.json.new" "$S/issues.json"
370
+ printf 'epic edited before the first GET after a listing\n' >> "$S/events.log"
371
+ fi
372
+ one=$(jq -c --argjson n "$n" '[.[] | select(.number == $n)] | first // empty | del(.parent)' "$S/issues.json")
373
+ [ -n "$one" ] || http_fail 404 "Not Found"
374
+ jq_out "$one"; exit 0
375
+ fi
376
+ if [ "$METHOD" = PATCH ]; then
377
+ record write PATCH "$ENDPOINT" "$EXPLICIT"; need_auth
378
+ repo_ok "$o" "$r" || http_fail 404 "Not Found"
379
+ ! route_fails epic-patch || http_fail 500 "Server Error"
380
+ bad=$(jq -rn --argjson f "$FIELDS" '[$f[] | select(.k != "body" and .k != "title") | .k] | join(",")')
381
+ [ -z "$bad" ] || refuse "PATCH field $bad"
382
+ jq -e --argjson n "$n" 'map(select(.number == $n)) | length > 0' "$S/issues.json" >/dev/null || http_fail 404 "Not Found"
383
+ if [ -f "$S/bodies/$CUR_SEQ-body" ]; then
384
+ jq -c --argjson n "$n" --rawfile b "$S/bodies/$CUR_SEQ-body" '(.[] | select(.number == $n) | .body) |= $b' "$S/issues.json" > "$S/issues.json.new" && mv "$S/issues.json.new" "$S/issues.json"
385
+ fi
386
+ jq_out "$(jq -c --argjson n "$n" '.[] | select(.number == $n) | del(.parent)' "$S/issues.json")"; exit 0
387
+ fi
388
+ fi
389
+
390
+ violation "unrouted $METHOD $ENDPOINT"
391
+ printf '{"message":"Not Found","status":"404"}\n'; printf 'gh: Not Found (HTTP 404)\n' >&2
392
+ exit 1