Merge origin/main into feat/design-lint; stamp 1.91.251.0

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
garrytanandcapy-ai[bot] committed 2026-10-26 17:15:55 +00:00
commit 4b4cadcb9c
289 files changed
+16151 -2303

No files matched your search

+5 -5
View File
@@ -22,11 +22,11 @@ if [ ! -f "$REPO_ROOT/.env" ]; then
fi
fi
# 2. Install dependencies
if [ ! -d "$REPO_ROOT/node_modules" ]; then
echo "Installing dependencies..."
(cd "$REPO_ROOT" && bun install)
fi
# 2. Install dependencies, devDependencies included. Always run: a checkout
# first installed by ./setup has production dependencies only, and an
# up-to-date install is a no-op.
echo "Installing dependencies..."
(cd "$REPO_ROOT" && bun install)
# 3. Create .claude/skills/ inside the repo
mkdir -p "$REPO_ROOT/.claude/skills"
+1 -1
View File
@@ -74,7 +74,7 @@ if [ ! -d "$ROOT/node_modules/playwright" ]; then
[ "$CHECK" -eq 1 ] && fail "playwright is not installed under $ROOT/node_modules" "cd $ROOT && ./setup"
command -v bun >/dev/null 2>&1 || fail "playwright is not installed under $ROOT/node_modules and bun is not on PATH" "install Bun, then cd $ROOT && ./setup"
log "gstack-browser-ensure: installing node modules (bun install)..."
(cd "$ROOT" && { bun install --frozen-lockfile >/dev/null 2>&1 || bun install >/dev/null; }) || fail "bun install failed under $ROOT" "cd $ROOT && bun install, then re-run $0"
(cd "$ROOT" && { bun install --production --frozen-lockfile >/dev/null 2>&1 || { bun install --lockfile-only >/dev/null && bun install --production --frozen-lockfile >/dev/null; }; }) || fail "bun install failed under $ROOT" "cd $ROOT && bun install --production --frozen-lockfile, then re-run $0"
fi
probe
+46 -4
View File
@@ -34,7 +34,10 @@
# Chromium is lazy by default (bin/gstack-browser-ensure
# installs it on first use); --with-browser installs it now. The last lines
# are the GSTACK_LAUNCH line the parent supplies to every gstack command it
# launches and the doctor's trailer (`gstack: ok ...` or `gstack: fail ...`;
# launches, GSTACK_LAUNCH_PATH when the certified Bun is not first on PATH,
# GSTACK_LAUNCH_FILE on a passing run (the same assignments as a sourceable
# mode-0600 file beside the verdict; callers and their children `. <file>` it,
# never re-type it) and the doctor's trailer (`gstack: ok ...` or `gstack: fail ...`;
# grep that, never pipe through tail).
# Exit: 0 ok, 1 a component failed, 2 usage, 3 preflight stopped before ./setup.
set -u
@@ -374,10 +377,13 @@ SETUP_RECORD="head=$HEAD_SHA hosts=claude,codex model=gpt-6-astra browser=$WITH_
if [ -n "$FOR" ]; then set -- --for "$FOR"; else set -- --require "$REQUIRE"; fi
[ "$WITH_BROWSER" -eq 1 ] && [ -z "$FOR" ] && set -- --require "$REQUIRE,browse-bundle,browser"
certify() { OUT=$(cd "$ORIG_PWD" && GSTACK_EPHEMERAL="${GSTACK_EPHEMERAL:-1}" "$ROOT/bin/gstack-doctor" --check "$@" ${PROJECT:+--project "$PROJECT"} ${MIN_REVISION:+--min-revision "$MIN_REVISION"} 2>&1); RC=$?; }
# A profile check never narrows an ok verdict a fuller install wrote for this HEAD.
verdict_kept() {
[ "$PROFILE" -eq 1 ] && [ -f "$VERDICT" ] && [ "$(gstack_install_verdict_field "$VERDICT" ok)" = true ] \
&& [ "$(gstack_install_verdict_field "$VERDICT" head)" = "$HEAD_SHA" ] && ! gstack_doctor_install_profile "$(gstack_install_verdict_field "$VERDICT" for)"
}
record_verdict() { # TRAILER OK — --check keeps the recorded resolution (drift is reported, never re-recorded)
# A profile check never narrows an ok verdict a fuller install wrote for this HEAD.
if [ "$PROFILE" -eq 1 ] && [ -f "$VERDICT" ] && [ "$(gstack_install_verdict_field "$VERDICT" ok)" = true ] \
&& [ "$(gstack_install_verdict_field "$VERDICT" head)" = "$HEAD_SHA" ] && ! gstack_doctor_install_profile "$(gstack_install_verdict_field "$VERDICT" for)"; then
if verdict_kept; then
say "kept the install verdict for=$(gstack_install_verdict_field "$VERDICT" for) at $VERDICT (it covers more than $FOR; the trailer below is this check's)"
return 0
fi
@@ -390,6 +396,7 @@ record_verdict() { # TRAILER OK — --check keeps the recorded resolution (drift
}
setup_failed() { # MESSAGE
echo "gstack-capy-install: $1" >&2
rm -f "${VERDICT%.json}.env"
OUT="" record_verdict "gstack: fail setup" 0
echo "gstack: fail setup — $1; fix: re-run the Capy skill installer or $ROOT/bin/gstack-capy-install (setup is re-run until it succeeds)"
exit 1
@@ -549,6 +556,8 @@ EOF_SHIM
# (the session exports GSTACK_CAPY_BEHIND_BLOCKED) is never ok: its ok trailer becomes
# gstack: fail behind — installed <rev> is <n> commits behind origin (latest <ver>)
# and the session-start upgrade was skipped: <reason>; fix: <command> (<CODE>)
# and a passing run whose launch file cannot be written becomes
# gstack: fail launch-file — could not write the launch file <path>; fix: <command> (LAUNCH_FILE_UNWRITABLE)
INSTALLED=$(head -1 "$ROOT/VERSION")
TRAILER="$(printf '%s\n' "$OUT" | grep '^gstack: ' | tail -1)"
NOTES=""
@@ -576,11 +585,44 @@ case "$TRAILER" in "gstack: ok "*) if [ -n "$BLOCKED" ]; then
TRAILER="gstack: fail behind — installed $INSTALLED is ${GSTACK_CAPY_BEHIND:-?} commits behind origin (latest ${GSTACK_CAPY_BEHIND_TO:-unknown}) and the session-start upgrade was skipped: $BLOCKED"
RC=1
elif [ -n "$NOTES" ]; then TRAILER="$TRAILER ($NOTES)"; fi ;; esac
# The launch file: the same assignments as a sourceable script, mode 0600,
# beside the verdict. `. <file>` applies them without ever printing them; the
# line carries no secret, but a caller that re-typed it as `export $(...)`
# ran a bare `export` when the substitution came back empty and dumped the
# whole environment, API keys included, into its tool output (GSTA-96). The
# file is part of the ok verdict: a passing run that cannot write it fails,
# so no caller is left with only the line and the re-typing path.
LAUNCH_FILE="${VERDICT%.json}.env"
write_launch_file() {
local tmp
mkdir -p "$(dirname "$LAUNCH_FILE")" || return 1
tmp=$(umask 077 && mktemp "$LAUNCH_FILE.tmp.XXXXXX") || return 1
{
echo "# gstack launch environment, written by gstack-capy-install; mode 0600."
echo "# Apply it with: . <this file>"
echo "# Never print it or the environment: no \`export \$(...)\`, \`env\`, \`printenv\` or bare \`set\` in a tool fence."
[ -n "$LAUNCH_DIR" ] && echo "case \":\$PATH:\" in *:$(shq "$LAUNCH_DIR"):*) ;; *) PATH=$(shq "$LAUNCH_DIR"):\"\$PATH\" ;; esac; export PATH"
echo "export GSTACK_SESSION_KIND=unattended"
echo "export GSTACK_STATE_ROOT=$(shq "$GSTACK_STATE_ROOT")"
echo "export GSTACK_EPHEMERAL=$(shq "${GSTACK_EPHEMERAL:-1}")"
echo "export GSTACK_CAPY=1"
echo "export GSTACK_INSTALL_VERDICT=$(shq "$VERDICT")"
} > "$tmp" && chmod 0600 "$tmp" && mv -f "$tmp" "$LAUNCH_FILE" || { rm -f "$tmp"; return 1; }
}
if [ "$RC" -eq 0 ] && ! write_launch_file; then
TRAILER="gstack: fail launch-file — could not write the launch file $LAUNCH_FILE; fix: make $(dirname "$LAUNCH_FILE") writable, or set GSTACK_STATE_ROOT to a writable directory (LAUNCH_FILE_UNWRITABLE)"
RC=1
fi
# A failing run announces no launch file and removes the one its verdict owned
# (where the directory lets it); a profile check that keeps a fuller ok verdict
# leaves that verdict's file in place.
[ "$RC" -eq 0 ] || { verdict_kept || rm -f "$LAUNCH_FILE" 2>/dev/null; LAUNCH_FILE=""; }
record_verdict "$TRAILER" "$([ "$RC" -eq 0 ] && echo 1 || echo 0)"
[ "$CHECK_ONLY" -eq 1 ] || [ "$PROFILE" -eq 1 ] || write_shim
printf '%s\n' "$OUT" | grep -v '^gstack: '
say "total: $(( $(now) - T0 ))s"
echo "GSTACK_LAUNCH: ${LAUNCH_DIR:+PATH=$LAUNCH_DIR:\$PATH }GSTACK_SESSION_KIND=unattended GSTACK_STATE_ROOT=$GSTACK_STATE_ROOT GSTACK_EPHEMERAL=${GSTACK_EPHEMERAL:-1} GSTACK_CAPY=1 GSTACK_INSTALL_VERDICT=$VERDICT"
[ -n "$LAUNCH_DIR" ] && echo "GSTACK_LAUNCH_PATH: $LAUNCH_DIR"
[ -n "$LAUNCH_FILE" ] && echo "GSTACK_LAUNCH_FILE: $LAUNCH_FILE"
printf '%s\n' "$TRAILER"
exit "$RC"
+31 -5
View File
@@ -54,8 +54,11 @@ CONFIG_HEADER='# gstack configuration — edit freely, changes take effect on ne
# Docs: https://github.com/garrytan/gstack
#
# ─── Behavior ────────────────────────────────────────────────────────
# proactive: true # Auto-invoke skills when your request matches one.
# # Set to false to only run skills you type explicitly.
# proactive: core # core = auto-invoke only /office-hours, /review, /qa and /ship
# # when your request matches one; every other skill waits
# # for you to type it. all = auto-invoke any matching skill.
# # off = only run skills you type explicitly.
# # (true and false still work: true means all, false means off.)
#
# routing_declined: false # Set to true to skip the CLAUDE.md routing injection
# # prompt. Set back to false to be asked again.
@@ -80,6 +83,9 @@ CONFIG_HEADER='# gstack configuration — edit freely, changes take effect on ne
# ─── Updates ─────────────────────────────────────────────────────────
# auto_upgrade: false # true = silently upgrade on session start
# update_check: true # false = suppress version check notifications
# update_channel: auto # auto = stable when team_mode is true, else main
# # stable = the weekly tagged release (refs/heads/stable)
# # main = every merge to main (docs/releases.md)
#
# ─── Skill naming ────────────────────────────────────────────────────
# skill_prefix: false # true = namespace skills as /gstack-qa, /gstack-ship
@@ -279,11 +285,12 @@ CONFIG_HEADER='# gstack configuration — edit freely, changes take effect on ne
# AND the env override is not set. Keep in sync with the CONFIG_HEADER comments.
lookup_default() {
case "$1" in
proactive) echo "true" ;;
proactive) echo "core" ;; # core | all | off (true = all, false = off); core suggests only /office-hours, /review, /qa, /ship
routing_declined) echo "false" ;;
telemetry) echo "off" ;;
auto_upgrade) echo "false" ;;
update_check) echo "true" ;;
update_channel) echo "auto" ;; # auto | stable | main — bin/gstack-update-channel.sh resolves auto (docs/releases.md)
skill_prefix) echo "false" ;;
explain_level) echo "default" ;;
plan_mode_preamble) echo "on" ;; # on | off — off drops the plan-mode preamble on the next ./setup (#3168)
@@ -742,6 +749,20 @@ $_gstack_legacy_root"
echo "Warning: explain_level '$VALUE' not recognized. Valid values: default, terse. Using default." >&2
VALUE="default"
fi
if [ "$KEY" = "proactive" ]; then
# Case-insensitive, and the YAML yes/no family maps like gstack-skill-start
# reads a hand-edited value: an opt-out must never fail open to core.
VALUE=$(printf '%s' "$VALUE" | tr '[:upper:]' '[:lower:]')
case "$VALUE" in
yes|y|on|1) VALUE="all" ;;
no|n|none|0|disabled|never) VALUE="off" ;;
core|all|off|true|false) ;;
*)
echo "Warning: proactive '$VALUE' not recognized. Valid values: core, all, off (true = all, false = off). Using core." >&2
VALUE="core"
;;
esac
fi
if [ "$KEY" = "plan_mode_preamble" ] && [ "$VALUE" != "on" ] && [ "$VALUE" != "off" ]; then
echo "Warning: plan_mode_preamble '$VALUE' not recognized. Valid values: on, off. Using on." >&2
VALUE="on"
@@ -841,6 +862,11 @@ $_gstack_legacy_root"
echo "Error: $KEY '$VALUE' not recognized. Valid values: local, ubicloud. Existing value left unchanged." >&2
exit 1
fi ;;
update_channel)
case "$VALUE" in auto|stable|main) ;; *)
echo "Error: update_channel '$VALUE' not recognized. Valid values: auto, stable, main. Existing value left unchanged. (https://github.com/garrytan/gstack/blob/main/docs/releases.md#channels)" >&2
exit 1 ;;
esac ;;
esac
# design_detector_install_prompted records "never ask again" for the one-time
# engine install offer. Rejecting a typo keeps the offer from silently coming
@@ -1025,7 +1051,7 @@ $_gstack_legacy_root"
echo ""
echo "# ─── Active values (including defaults for unset keys) ───"
report_root_disagreement
for KEY in proactive routing_declined telemetry auto_upgrade update_check \
for KEY in proactive routing_declined telemetry auto_upgrade update_check update_channel \
skill_prefix explain_level plan_mode_preamble \
codex_reviews gstack_contributor skip_eng_review workspace_root \
artifacts_sync_mode artifacts_sync_mode_prompted artifacts_sync_removals plan_tune_hooks \
@@ -1050,7 +1076,7 @@ $_gstack_legacy_root"
;;
defaults)
echo "# gstack-config defaults"
for KEY in proactive routing_declined telemetry auto_upgrade update_check \
for KEY in proactive routing_declined telemetry auto_upgrade update_check update_channel \
skill_prefix explain_level plan_mode_preamble \
codex_reviews gstack_contributor skip_eng_review workspace_root \
artifacts_sync_mode artifacts_sync_mode_prompted artifacts_sync_removals plan_tune_hooks \
+28 -11
View File
@@ -1,20 +1,27 @@
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
// gstack-design-craft — free craft check for a generated page (/design-html Step 4).
//
// Usage: gstack-design-craft <file.html>
// Usage: gstack-design-craft <file.html> [--accepted <finalized.json>]
//
// Prints one "CRAFT_CHECK: <id> <count> <fix>" line per tell, then
// "CRAFT_RESULT: clean" (exit 0) or "CRAFT_RESULT: <n> issue(s)" (exit 1).
// Exit 2: usage error, a non-HTML file, an unreadable or empty file. Head and
// navigation rules run only on a full HTML document; a fragment gets the copy
// and code rules alone.
// --accepted reads the craft_exceptions a finalized.json recorded: a tell an
// exception covers (same id, count at most the accepted count) prints as
// "CRAFT_ACCEPTED: <id> <count> <reason>" and does not fail the check; the
// result line then adds " (<k> accepted)" or ", <k> accepted".
// Exit 2: usage error, a non-HTML file, or an unreadable or empty file, with
// nothing checked; or an unreadable or malformed exceptions file, after a
// warning and a full check with no exceptions accepted, so a bad record never
// hides the page's tells. Head and navigation rules run only on a full HTML
// document; a fragment gets the copy and code rules alone.
import { readFileSync } from 'fs';
import { checkCraft, formatCraft } from '../lib/design-craft';
import { acceptFindings, checkCraft, formatCraft, parseCraftExceptions, type CraftException } from '../lib/design-craft';
const file = process.argv[2];
if (!file) {
console.error('Usage: gstack-design-craft <file.html>');
const USAGE = 'Usage: gstack-design-craft <file.html> [--accepted <finalized.json>]';
const [file, flag, acceptedFile, ...rest] = process.argv.slice(2);
if (!file || (flag !== undefined && (flag !== '--accepted' || !acceptedFile)) || rest.length > 0) {
console.error(USAGE);
process.exit(2);
}
if (!/\.html?$/i.test(file)) {
@@ -32,6 +39,16 @@ if (source.trim() === '') {
console.error(`gstack-design-craft: ${file} is empty; nothing was checked`);
process.exit(2);
}
const findings = checkCraft(source);
console.log(formatCraft(findings));
process.exit(findings.length === 0 ? 0 : 1);
let exceptions: CraftException[] = [];
let badExceptions = false;
if (acceptedFile) {
try {
exceptions = parseCraftExceptions(readFileSync(acceptedFile, 'utf-8'));
} catch (err) {
console.error(`gstack-design-craft: cannot use exceptions from ${acceptedFile}: ${(err as Error).message}; checked with none accepted`);
badExceptions = true;
}
}
const { issues, accepted } = acceptFindings(checkCraft(source), exceptions);
console.log(formatCraft(issues, accepted));
process.exit(badExceptions ? 2 : issues.length === 0 ? 0 : 1);
+95 -36
View File
@@ -11,7 +11,8 @@
# write updated ~/.gstack/developer-profile.json.
# --profile emit the full profile as JSON (all fields).
# --gap emit declared-vs-inferred gap as JSON.
# --trace <dim> show events that contributed to a dimension.
# --trace <dim> show events that contributed to a dimension, each
# UTC day clamped by the per-day bound, and the total.
# --narrative (v2 stub) output a coach bio paragraph.
# --vibe (v2 stub) output the one-word archetype.
# --check-mismatch detect meaningful gaps between declared and observed.
@@ -416,6 +417,79 @@ do_gap() {
"
}
# -----------------------------------------------------------------------
# Signal accumulation shared by --derive and --trace, so the trace always
# explains exactly the value derive wrote. Each row's SIGNAL_MAP deltas are
# summed per (UTC day, dimension) and each day's sum is clamped to ±cap,
# where cap is the largest single delta in SIGNAL_MAP: one day moves a
# dimension at most as far as one strong answer. Without the bound a single
# /plan-eng-review (about five answers) moved a dimension by 0.25 and about
# eight reviews pinned it at 1.0 (#2623). The bound keys on the row's ts,
# not its session_id: writers log different ids for one review (the
# PostToolUse hook logs the host conversation, the agent the preamble run)
# and an unsubstituted placeholder such as SESSION_ID would merge or split
# reviews. Only an ISO 8601 date or date-time counts as dated; a time
# without a zone is read as UTC. Every other row shares one undated bucket,
# so junk timestamps cannot escape the bound (Date alone parses strings
# like "junk 1" as real days). diversity.days_span counts the same days.
# The body is a single-quoted bash string: its JS must not contain a single
# quote (use double quotes or backticks), or the assignment ends early and
# every subcommand fails to parse.
# -----------------------------------------------------------------------
ACCUMULATE_SIGNALS_JS='
function accumulateSignals(lines, QUESTIONS, SIGNAL_MAP, dims) {
let cap = 0;
for (const byChoice of Object.values(SIGNAL_MAP)) {
for (const deltas of Object.values(byChoice)) {
for (const d of deltas) cap = Math.max(cap, Math.abs(d.delta));
}
}
const contributing = Object.fromEntries(dims.map((d) => [d, 0]));
const buckets = new Map();
const rows = [];
const skills = new Set();
const qids = new Set();
const days = new Set();
let count = 0;
let signalEvents = 0;
for (const line of lines) {
let e;
try { e = JSON.parse(line); } catch { continue; }
if (!e || typeof e !== "object" || typeof e.question_id !== "string" || typeof e.user_choice !== "string" || !e.question_id || !e.user_choice) continue;
count++;
skills.add(e.skill);
qids.add(e.question_id);
const m = typeof e.ts === "string" ? /^(\d{4}-\d\d-\d\d)(?:[Tt ](\d\d:\d\d(?::\d\d(?:\.\d+)?)?)(Z|z|[+-]\d\d:\d\d)?)?$/.exec(e.ts) : null;
const when = m ? new Date(m[2] ? m[1] + "T" + m[2] + (m[3] || "Z").toUpperCase() : m[1]) : null;
const day = when && !Number.isNaN(when.getTime()) ? when.toISOString().slice(0, 10) : null;
if (day) days.add(day);
const def = Object.hasOwn(QUESTIONS, e.question_id) ? QUESTIONS[e.question_id] : undefined;
const byChoice = def && def.signal_key && Object.hasOwn(SIGNAL_MAP, def.signal_key) ? SIGNAL_MAP[def.signal_key] : {};
const deltas = Object.hasOwn(byChoice, e.user_choice) ? byChoice[e.user_choice] : [];
if (!Array.isArray(deltas) || deltas.length === 0) continue;
signalEvents++;
const key = day || "undated";
const sums = buckets.get(key) || {};
buckets.set(key, sums);
for (const d of deltas) {
sums[d.dim] = (sums[d.dim] || 0) + d.delta;
rows.push({ ts: e.ts, question_id: e.question_id, choice: e.user_choice, dim: d.dim, delta: d.delta });
}
for (const dim of new Set(deltas.map((d) => d.dim))) contributing[dim] = (contributing[dim] ?? 0) + 1;
}
const totals = Object.fromEntries(dims.map((d) => [d, 0]));
const capped = [];
for (const [day, sums] of buckets) {
for (const [dim, sum] of Object.entries(sums)) {
const bounded = Math.max(-cap, Math.min(cap, sum));
if (Math.abs(sum - bounded) > 1e-9) capped.push({ day, dim, sum, bounded });
totals[dim] = (totals[dim] ?? 0) + bounded;
}
}
return { cap, totals, contributing, rows, capped, count, signalEvents, skills, qids, days };
}
'
# -----------------------------------------------------------------------
# Derive: recompute inferred dimensions from question-events.jsonl
# -----------------------------------------------------------------------
@@ -435,7 +509,8 @@ do_derive() {
const sigmod = await import('./scripts/psychographic-signals.ts');
const fs = require('fs');
const { QUESTIONS } = regmod;
const { SIGNAL_MAP, applySignal, newDimensionTotals, normalizeToDimensionValue } = sigmod;
const { SIGNAL_MAP, ALL_DIMENSIONS, normalizeToDimensionValue } = sigmod;
$ACCUMULATE_SIGNALS_JS
const profilePath = process.env.PROFILE_FILE_PATH;
const eventsPath = process.env.EVENTS_PATH;
@@ -446,25 +521,8 @@ do_derive() {
lines = fs.readFileSync(eventsPath, 'utf-8').trim().split('\n').filter(Boolean);
}
const totals = newDimensionTotals();
const skills = new Set();
const qids = new Set();
const days = new Set();
let count = 0;
let signalEvents = 0;
for (const line of lines) {
let e;
try { e = JSON.parse(line); } catch { continue; }
if (!e.question_id || !e.user_choice) continue;
count++;
skills.add(e.skill);
qids.add(e.question_id);
if (e.ts) days.add(String(e.ts).slice(0,10));
const def = QUESTIONS[e.question_id];
if (def && def.signal_key && applySignal(totals, def.signal_key, e.user_choice).length > 0) {
signalEvents++;
}
}
const { totals, contributing, count, signalEvents, skills, qids, days } =
accumulateSignals(lines, QUESTIONS, SIGNAL_MAP, ALL_DIMENSIONS);
const values = {};
for (const [dim, total] of Object.entries(totals)) {
@@ -477,6 +535,10 @@ do_derive() {
// Events that actually moved a dimension (B10): sample_size counts every
// logged answer, most of which match no signal and leave the 0.5 seed.
signal_events: signalEvents,
// Unique rows that moved each dimension (#2625). Distinguishes 'no
// evidence' from 'balanced evidence': both print 0.5, which is how
// five 0.5s sat beside sample_size 1286 (#2623).
contributing_events: contributing,
diversity: {
skills_covered: skills.size,
question_ids_covered: qids.size,
@@ -522,29 +584,26 @@ do_trace() {
const sigmod = await import('./scripts/psychographic-signals.ts');
const fs = require('fs');
const { QUESTIONS } = regmod;
const { SIGNAL_MAP } = sigmod;
const { SIGNAL_MAP, ALL_DIMENSIONS, normalizeToDimensionValue } = sigmod;
$ACCUMULATE_SIGNALS_JS
const target = process.env.TRACE_DIM;
const lines = fs.readFileSync(process.env.EVENTS_PATH, 'utf-8').trim().split('\n').filter(Boolean);
const rows = [];
for (const line of lines) {
let e;
try { e = JSON.parse(line); } catch { continue; }
const def = QUESTIONS[e.question_id];
if (!def || !def.signal_key) continue;
const deltas = SIGNAL_MAP[def.signal_key]?.[e.user_choice] || [];
for (const d of deltas) {
if (d.dim === target) {
rows.push({ ts: e.ts, question_id: e.question_id, choice: e.user_choice, delta: d.delta });
}
}
}
const acc = accumulateSignals(lines, QUESTIONS, SIGNAL_MAP, ALL_DIMENSIONS);
const rows = acc.rows.filter((r) => r.dim === target);
const signed = (n, digits) => (n > 0 ? '+' : '') + (digits === undefined ? String(n) : n.toFixed(digits));
const clean = (s) => String(s ?? '').replace(/[\x00-\x1f\x7f-\x9f]/g, '?');
if (rows.length === 0) {
console.log('TRACE: no events contribute to ' + target);
} else {
console.log('TRACE: ' + rows.length + ' events for ' + target);
for (const r of rows) {
console.log(' ' + (r.ts || '').slice(0,19) + ' ' + r.question_id + ' → ' + r.choice + ' (' + (r.delta > 0 ? '+' : '') + r.delta + ')');
console.log(' ' + clean(r.ts).slice(0,19) + ' ' + clean(r.question_id) + ' → ' + clean(r.choice) + ' (' + signed(r.delta) + ')');
}
for (const c of acc.capped.filter((c) => c.dim === target)) {
console.log(' day ' + clean(c.day) + ': ' + signed(c.sum, 3) + ' capped to ' + signed(c.bounded, 3));
}
const total = acc.totals[target] ?? 0;
console.log('TOTAL: ' + signed(total, 3) + ' (each UTC day capped at ±' + acc.cap + ') → ' + normalizeToDimensionValue(total).toFixed(3));
}
});
"
+4
View File
@@ -277,6 +277,9 @@ gstack_result_anchor() {
QUEUE_TRAIN_REBUILD_REFUSED) printf '%s' 'queue-train-rebuild-refused' ;;
QUEUE_TRAIN_TREE_MISMATCH) printf '%s' 'queue-train-tree-mismatch' ;;
QUEUE_TRAIN_FROZEN) printf '%s' 'queue-train-frozen' ;;
QUEUE_RECEIPT_MISSING) printf '%s' 'queue-receipt-missing' ;;
QUEUE_RECEIPT_STALE) printf '%s' 'queue-receipt-stale' ;;
QUEUE_SCREEN_STALE_REF) printf '%s' 'queue-screen-stale-ref' ;;
READY_SCREEN_CHOICE_REQUIRED) printf '%s' 'ready-screen-choice-required' ;;
PREGATE_TIMING_ASSERTION) printf '%s' 'pregate-timing-assertion' ;;
APPROVAL_CLASSES_INVALID) printf '%s' 'approval-classes-invalid' ;;
@@ -297,6 +300,7 @@ gstack_result_anchor() {
PR_SHOTS_INPUT_REFUSED) printf '%s' 'pr-shots-input-refused' ;;
PR_SHOTS_IDENTICAL) printf '%s' 'pr-shots-identical' ;;
PR_SHOTS_RENDER_FAILED) printf '%s' 'pr-shots-render-failed' ;;
LAUNCH_FILE_UNWRITABLE) printf '%s' 'capy-install-launch-file-unwritable' ;;
*) return 1 ;;
esac
}
+99 -7
View File
@@ -19,9 +19,24 @@
* `tests_ran` (zero-run green, W3 of docs/designs/HONEST_WORK_GATE_INTEGRITY.md)
* is parsed from a bounded tail of the streamed output for the supported
* runners only: bun (shard-engine's summary parser where importable; executed =
* pass + fail, so an all-skip run is 0), jest, vitest, pytest, rspec, and Go's
* zero-only case (every package `[no test files]`). The last summary per
* runner wins; anything else is "unknown". Three states, never merged:
* pass + fail, so an all-skip run is 0), jest, vitest, pytest, rspec, Go's
* zero-only case (every package `[no test files]`), gstack's own shard runner
* (`bun run test:free` / `test:ubicloud`: the sum of its per-shard
* `[test:free] PASS — N tests` epilogues, or a files-from run's
* `FILES-FROM RESULT: … tests=N`), and a `gstack-pregate --remote` lane (the
* remote gate's `PREGATE_REMOTE: … tests=N` row, or the cleared obligation's
* `cleared by remote-gate … tests=N` receipt). The shard runner and the remote
* gate print only bun's terminal totals, which count skipped tests, so for
* those two the number is "ran, skips included" rather than executed (the shard
* runner refuses a shard whose bun summary counts fewer files than planned, but
* a shard whose files all loaded and executed nothing still passes with that
* total). When the shard runner spoke, its verdict stands for the whole tail:
* the tail is the stdout tail then the stderr tail, so a line's position says
* nothing about when it was printed across streams, and bun's own counts (on
* stderr) would otherwise outrank a 10k-test run whichever of the two ran
* first. Any summary when it did not speak follows the last-summary-wins rule;
* anything else is "unknown".
* Three states, never merged:
* a count, 0 (ZERO-RUN, graded like STALE by `check`) and unknown (non-blocking).
*
* TRANSPARENCY INVARIANT (load-bearing): the child's exit code is ALWAYS the
@@ -76,7 +91,7 @@ interface EvidenceRecord {
wtree?: string;
log_path?: string;
redacted?: boolean;
/** Executed tests per the runner's own summary; "unknown" when no supported summary was seen. */
/** The runner's own test count (executed for bun/jest/vitest/pytest/rspec; ran with skips included for gstack's shard runner and the remote gate), 0 for ZERO-RUN, or "unknown" when no supported summary was seen. */
tests_ran?: number | "unknown";
}
@@ -108,7 +123,17 @@ const ANSI = /\u001B\[[0-?]*[ -/]*[@-~]/g;
const strip = (l: string) => l.replace(ANSI, "").replace(/\r$/, "");
const count = (text: string, word: string): number => Number(new RegExp(`(\\d+) ${word}\\b`).exec(text)?.[1] ?? 0);
/** Bun: the last "Ran N tests across M files" block; executed = its " N pass" + " N fail" lines. */
/**
* Bun: the last "Ran N tests across M files" block; executed = its " N pass" +
* " N fail" lines. Bun always prints that counts block (" 0 pass" / " 0 fail"
* even for an all-skip or empty run), so a terminal line with no " N pass"
* above it is a line gstack's quiet shard runner forwarded (it forwards the
* terminal line without the " N pass" line), not a bun summary:
* it is skipped and the shard runner's own epilogue counts. A terminal line
* that itself says "Ran 0 tests" is ZERO-RUN even without counts, unless the
* shard runner spoke: a forwarded "Ran 0 tests across 1 file" is one shard's
* empty file, not the run.
*/
async function bunTestsRan(lines: string[]): Promise<{ at: number; ran: number } | null> {
let isTerminal = (l: string) => /^Ran \d+ tests? across \d+ files?\. \[/.test(l);
try {
@@ -119,7 +144,7 @@ async function bunTestsRan(lines: string[]): Promise<{ at: number; ran: number }
}
for (let i = lines.length - 1; i >= 0; i--) {
if (!isTerminal(lines[i])) continue;
let pass = 0;
let pass: number | null = null;
let fail = 0;
for (let j = i - 1; j >= 0 && j >= i - 12; j--) {
if (isTerminal(lines[j])) break;
@@ -128,11 +153,64 @@ async function bunTestsRan(lines: string[]): Promise<{ at: number; ran: number }
if (p) pass = Number(p[1]);
if (f) fail = Number(f[1]);
}
if (pass === null) {
if (/^Ran 0 tests? across/.test(lines[i])) return { at: i, ran: 0 };
continue;
}
return { at: i, ran: pass + fail };
}
return null;
}
/**
* gstack's shard runner (scripts/test-free-shards.ts; `bun run test:free` /
* `test:ubicloud`). Its quiet shards forward bun's terminal line without the
* counts the bun branch reads, so each shard's epilogue "[test:free] PASS — N
* tests, M files, Ts." carries the shard's "Ran N" total (skips included) and
* the run's total is their sum; a files-from run ends with "[test:free]
* FILES-FROM RESULT: files=F tests=N failed=K exit=E", the same sum. Only the
* last run in the tail counts (its "[test:free] full suite:" / "files-from" /
* "QUICK SUBSET" start line); the other parsers decide only when no runner
* line at all is in the tail. A run with a "FAIL —" or "FLAKY-PASS —" epilogue and no FILES-FROM
* total has lost a shard's count (a FAIL epilogue carries none; the flaky retry
* re-runs only the failing files), so it is unknown rather than a partial sum.
* The runner's verdict covers the whole tail once it spoke: the tail is
* stdout-then-stderr, bun's counts block is on stderr and the runner's
* epilogues are on stdout, so "after" cannot be told from "before" across the
* two streams and a bun block printed before the suite (a focused file run
* first) would otherwise record its count, or ZERO-RUN, for a 10k-test run.
* The quiet shards forward only count-less terminal lines (a shard's "Ran 0
* tests across 1 file" is one empty file, not the run); under `--verbose` they
* forward whole blocks, which the runner's sum outranks. The epilogue is
* matched as the runner's whole line (the log path may contain spaces); like
* every runner summary here it is the child's own stdout, so a test that
* forges one is trusted the same way a forged bun summary is (see W3's trust
* model), and the exit is never derived from it. Returns undefined when no
* runner line is in the tail. A verdict line (PASS/FAIL/FLAKY-PASS epilogue or
* FILES-FROM RESULT) without its start line means the start line was evicted
* from the tail (a chatty default-mode or --verbose run): the runner spoke,
* the sum is incomplete, so the result is unknown rather than a forwarded
* shard block's count. A full-suite start line names its shard count
* ("across N shard processes", plus one exclusive host-state shard when it
* says so); fewer PASS epilogues than that (killed mid-shards, `--ci-verify`)
* is unknown, never a partial sum. An empty shard prints "shard i/N: 0 files,
* 0s, pass" instead of a PASS epilogue and counts as zero.
*/
function shardRunnerTestsRan(lines: string[]): number | "unknown" | undefined {
const verdictLine = /^\s*\[test:free\] (?:PASS — |FAIL — |FLAKY-PASS — |FILES-FROM RESULT: )/;
const start = lines.findLastIndex((l) => /^\s*\[test:free\] (?:full suite:|files-from |QUICK SUBSET:)/.test(l));
if (start < 0) return lines.some((l) => verdictLine.test(l)) ? "unknown" : undefined;
const run = lines.slice(start);
const result = /^\s*\[test:free\] FILES-FROM RESULT: files=\d+ tests=(\d+) failed=\d+ exit=\d+\s*$/;
const total = run.findLast((l) => result.test(l));
if (total) return Number(result.exec(total)![1]);
if (run.some((l) => /^\s*\[test:free\] (?:FAIL|FLAKY-PASS) — /.test(l) || /^\s*\[test:free\] PASS — \? tests/.test(l))) return "unknown";
const counts = run.map((l) => /^\s*\[test:free\] PASS — (\d+) tests?, \d+ files?, \d+s\. Full log: \S.*$/.exec(l)?.[1] ?? (/^\s*\[test:free\] shard \d+\/\d+: 0 files, \d+s, pass\s*$/.test(l) ? "0" : undefined)).filter((n): n is string => n !== undefined);
const planned = /across (\d+) shard processes/.exec(run[0]!);
const expected = planned ? Number(planned[1]) + (/exclusive host-state file/.test(run[0]!) ? 1 : 0) : 1;
return counts.length >= expected ? counts.reduce((sum, n) => sum + Number(n), 0) : "unknown";
}
function otherRunnersTestsRan(lines: string[]): { at: number; ran: number } | null {
const hits: { at: number; ran: number }[] = [];
const last = (re: RegExp) => {
@@ -162,14 +240,28 @@ function otherRunnersTestsRan(lines: string[]): { at: number; ran: number } | nu
const goNoTests = lines.filter((l) => /^\?\s+\S+\s+\[no test files\]$/.test(l));
const goRan = lines.some((l) => /^(?:ok|FAIL|---)\s/.test(l));
if (goNoTests.length > 0 && !goRan) hits.push({ at: last(/\[no test files\]$/), ran: 0 });
// gstack-pregate --remote: the remote gate's own "PREGATE_REMOTE: tree=… tests=N failed=M"
// line (tests = the shard runner's FILES-FROM RESULT sum, relayed by scripts/ubicloud/pregate-remote.sh;
// lib/pregate/checks/lanes.ts parseRemoteReport is the canonical parser), rendered as a lane
// row under "lanes:" in the pregate table, and the obligation's "requires-remote: … cleared by
// remote-gate tree=… tests=N" receipt line (lib/pregate/index.ts). Whole lines, like every
// other runner pattern here, so a prefixed or quoted echo does not count (the row is indented
// under "lanes:" by design, so indentation is accepted). When both appear they carry the same
// count; the later one wins.
for (const re of [/^\s*(?:lanes:\s+)?PREGATE_REMOTE: tree=\S+ tests=(\d+) failed=\d+(?: spent=\S+)?\s*$/, /^\s*requires-remote: .* cleared by remote-gate tree=\S+ tests=(\d+)\b/]) {
i = last(re);
if (i >= 0) hits.push({ at: i, ran: Number(re.exec(lines[i])![1]) });
}
if (hits.length === 0) return null;
return hits.reduce((a, b) => (b.at > a.at ? b : a));
}
/** The executed-test count from the output tail, or "unknown". Never throws into the caller's exit path. */
/** The runner-reported test count from the output tail (see the header for which runners report executed vs ran), 0, or "unknown". Never throws into the caller's exit path. */
async function parseTestsRan(tail: string): Promise<number | "unknown"> {
if (process.env.GSTACK_EVIDENCE_FAULT === "tests_ran") throw new Error("injected tests_ran parser fault");
const lines = tail.split("\n").map(strip);
const shard = shardRunnerTestsRan(lines);
if (shard !== undefined) return shard;
const candidates = [await bunTestsRan(lines), otherRunnersTestsRan(lines)].filter((c): c is { at: number; ran: number } => c !== null);
if (candidates.length === 0) return "unknown";
return candidates.reduce((a, b) => (b.at > a.at ? b : a)).ran;
+5 -4
View File
@@ -29,7 +29,7 @@ import * as os from 'node:os';
import { scanCandidate, parseGateIntegrityBlock, specDirectoryHoldsSpecs, type FileDiff, type CommitInfo } from '../lib/gate-diff/index';
import {
commitInfo, commitsInRange, defaultBase, diffCommit, diffWorkingTree, firstParent, headSha, mergeBase, noBaseFix, readClaudeMd, repoRoot,
resolvesToCommit, treePaths, untrackedAsAdded,
resolveBase, resolvesToCommit, treePaths, untrackedAsAdded,
} from '../lib/gate-diff/git';
import { renderDiagnostics, renderJsonl, renderJsonlBody, renderTable } from '../lib/gate-diff/render';
import { resolveStateRoot } from '../lib/state-root';
@@ -142,13 +142,14 @@ function main(argv: string[]): number {
specIsTestPath = specDirectoryHoldsSpecs(treePaths(root, sha));
} else {
const baseRef = parsed.base ?? defaultBase(root);
const baseSha = resolvesToCommit(baseRef, root);
const head = headSha(root);
if (!baseSha || !head) {
const base = resolveBase(baseRef, root, head ?? undefined);
if (!base || !head) {
process.stdout.write(`GATE_ERROR=no_base ref=${baseRef} fix=${noBaseFix(baseRef, root)}\n`);
return 2;
}
const mb = mergeBase(baseSha, head, root);
if (base.local) console.error(`gstack-gate-diff: ${base.local === 'unrelated' ? `local ${baseRef} shares no history with HEAD` : `no local branch ${baseRef}`}; base is ${base.ref}`);
const mb = mergeBase(base.sha, head, root);
if (!mb) {
process.stdout.write(`GATE_ERROR=no_base ref=${baseRef} fix=${noBaseFix(baseRef, root)}\n`);
return 2;
+5 -1
View File
@@ -133,11 +133,15 @@ gstack_install_admission() {
fix="run the Capy skill installer (scripts/install.sh --for $skill) on this machine, then launch with the GSTACK_LAUNCH line it prints"
if [ ! -f "$file" ]; then
detail="no install verdict at $file for $src"
fix="run the Capy skill installer (scripts/install.sh --for $skill) from ${project:-this directory}: the verdict is keyed by the project directory the installer runs in, so a run from the skill's own folder does not cover ${project:-it}; then launch with the GSTACK_LAUNCH line it prints"
else
trailer=$(gstack_install_verdict_field "$file" trailer)
v_head=$(gstack_install_verdict_field "$file" head)
head=$(git -C "$src" rev-parse HEAD 2>/dev/null)
if [ "$(gstack_install_verdict_field "$file" ok)" != true ]; then
v_schema=$(gstack_install_verdict_field "$file" schema_version)
if { [ -z "$(gstack_install_verdict_field "$file" ok)" ] && [ -z "$v_schema" ]; } || { [ "$v_schema" != 1 ] && [ "$v_schema" != 2 ]; }; then
detail="the install verdict at $file is unreadable or has an unsupported schema_version; rerun the installer"
elif [ "$(gstack_install_verdict_field "$file" ok)" != true ]; then
detail="the install verdict says: $trailer"
elif [ "$(gstack_install_verdict_field "$file" checkout)" != "$src" ]; then
detail="the install verdict is for checkout $(gstack_install_verdict_field "$file" checkout), not $src"
+1
View File
@@ -97,6 +97,7 @@ function report(r: RestampResult, json: boolean): number {
process.stdout.write(`FILES: ${(r.files ?? []).join(' ') || '(none)'}\n`);
if (r.mergeCondition) process.stdout.write(`MERGE_CONDITION: sha=${r.mergeCondition}\n`);
if (r.status === 'gate-ahead' && r.gateAhead) process.stdout.write(`next: run the verification gate in ${r.gateAhead.worktree}, then \`gstack-evidence bundle --out <file>\` there; the branch is untouched. At this PR's turn rerun \`gstack-restamp --next\` here and read \`gstack-tree-receipt --from ${GATE_AHEAD_REL}\` before deciding what to rerun.\n`);
else if ((r.status === 'stamped' || r.status === 'noop') && r.queueMode === 'stamp-at-merge') process.stdout.write(`next: NEW_VERSION=${r.newVersion}; commit and push only the stamp diff above (FILES), with no edit of your own: the train's verify accepts the CHANGELOG only as the base's plus this PR's entry re-headed; merge with the expected head ${r.mergeCondition ?? 'sha'} and recompute on a stale queue.\n`);
else if (r.status === 'stamped' || r.status === 'noop') process.stdout.write(`next: NEW_VERSION=${r.newVersion}; record the release decision, then write the CHANGELOG entry text only (the heading is already ${r.newVersion}); merge with the expected head ${r.mergeCondition ?? 'sha'} and recompute on a stale queue.\n`);
}
process.stdout.write(formatResult('restamp', status, r.journal ?? JOURNAL_REL) + '\n');
+70 -4
View File
@@ -24,6 +24,13 @@
# the release are shelved in refs/gstack/rescue/<oid>, never left as conflict
# markers, and the next session start names them (at most once a day).
#
# Channel (bin/gstack-update-channel.sh, docs/releases.md): a team install
# follows refs/heads/stable, the weekly tagged release, so it moves once a
# week (plus hotfixes) instead of at every merge; update_channel=main follows
# every merge as before. Until the first release is cut, origin has no stable
# and the updater follows main (CHANNEL_FALLBACK in the log). An install
# already past the release waits for stable to catch up; nothing moves back.
#
# Stages (B11): pull, setup and migrations are tracked separately. The
# "just upgraded" marker is written only when every stage succeeded. A failed
# stage is persisted in $STATE_DIR/session-update-pending and retried even
@@ -47,6 +54,14 @@ STATE_DIR="$(gstack_state_root; printf x)"; STATE_DIR="${STATE_DIR%x}"
# Bun floor comparison (E1): the incoming release's floor is applied before
# the live checkout moves. Missing helper fails open, like every error here.
. "$(cd "$(dirname "$0")" && pwd)/gstack-bun-version.sh" 2>/dev/null
# Update channel (docs/releases.md): a team install follows refs/heads/stable,
# the weekly tagged release, unless update_channel says main. A missing
# helper means main, the behaviour before channels existed.
. "$(cd "$(dirname "$0")" && pwd)/gstack-update-channel.sh" 2>/dev/null || {
gstack_update_channel() { echo main; }
gstack_update_channel_refspec() { :; }
gstack_update_channel_missing() { return 1; }
}
THROTTLE_FILE="$STATE_DIR/.last-session-update"
LOCK_DIR="$STATE_DIR/.setup-lock"
LOG_FILE="$STATE_DIR/analytics/session-update.log"
@@ -162,6 +177,25 @@ rescue_note() {
grep -q "^$1 " "$RESCUE_FILE" 2>/dev/null && return 0
printf '%s %s -\n' "$1" "$2" >> "$RESCUE_FILE" 2>/dev/null
}
# channel_behind_release <release> <head> — true when the release commit is at
# or behind this install's head: an ancestor of it, or, when the shallow
# history cannot relate the two, a VERSION that is not higher.
channel_behind_release() {
git -C "$GSTACK_DIR" merge-base --is-ancestor "$1" "$2" 2>/dev/null && return 0
git -C "$GSTACK_DIR" merge-base --is-ancestor "$2" "$1" 2>/dev/null && return 1
_cb_rel=$(git -C "$GSTACK_DIR" show "$1:VERSION" 2>/dev/null | head -1)
_cb_head=$(git -C "$GSTACK_DIR" show "$2:VERSION" 2>/dev/null | head -1)
[ -n "$_cb_rel" ] && [ -n "$_cb_head" ] || return 1
_cb_i=1
while :; do
_cb_a=$(printf '%s' "$_cb_rel" | cut -d. -f"$_cb_i"); _cb_b=$(printf '%s' "$_cb_head" | cut -d. -f"$_cb_i")
[ -z "$_cb_a" ] && [ -z "$_cb_b" ] && return 0
case "${_cb_a:-0}${_cb_b:-0}" in *[!0-9]*) return 1 ;; esac
[ "${_cb_a:-0}" -lt "${_cb_b:-0}" ] && return 0
[ "${_cb_a:-0}" -gt "${_cb_b:-0}" ] && return 1
_cb_i=$((_cb_i + 1))
done
}
pending_get() { sed -n "s/^$1=//p" "$PENDING_FILE" 2>/dev/null | head -1; }
# pending_save — persist the P_* stage state; nothing pending removes the file.
pending_save() {
@@ -392,15 +426,47 @@ CALLER_PID=$(gstack_harness_pid "$PPID")
# bin/gstack-ff-update carries them over the release instead.
# Capture stderr: the log must carry WHY a pull failed, never just the code.
PULL_ERR_FILE=$(mktemp "${TMPDIR:-/tmp}/gstack-session-pull-XXXXXX" 2>/dev/null || echo "")
GSTACK_HOME="$STATE_DIR" _receipted_git open session-update "${UPDATE_HOST:-unknown}" gstack-self-update-pull "auto_upgrade=true" \
bash -c 'git -C "$1" fetch -q 2>"${2:-/dev/null}"' _ "$GSTACK_DIR" "$PULL_ERR_FILE"
PULL_EXIT=$?
# The channel decides which ref is fetched and followed. stable is fetched
# by refspec: team installs are single-branch clones, whose plain fetch
# brings main only. Before the first release is cut origin has no stable,
# and the updater follows main instead of standing still.
CHANNEL=$(gstack_update_channel "$GSTACK_DIR" 2>/dev/null) || CHANNEL=main
PULL_EXIT=0
if [ "$CHANNEL" = stable ]; then
GSTACK_HOME="$STATE_DIR" _receipted_git open session-update "${UPDATE_HOST:-unknown}" gstack-self-update-pull "auto_upgrade=true" \
bash -c 'git -C "$1" fetch -q origin "$3" 2>"${2:-/dev/null}"' _ "$GSTACK_DIR" "$PULL_ERR_FILE" "$(gstack_update_channel_refspec stable)"
PULL_EXIT=$?
if [ "$PULL_EXIT" -ne 0 ] && gstack_update_channel_missing "$(cat "${PULL_ERR_FILE:-/dev/null}" 2>/dev/null)"; then
log_entry "CHANNEL_FALLBACK stable->main reason=no-stable-on-origin"
CHANNEL=main
fi
fi
if [ "$CHANNEL" = main ]; then
GSTACK_HOME="$STATE_DIR" _receipted_git open session-update "${UPDATE_HOST:-unknown}" gstack-self-update-pull "auto_upgrade=true" \
bash -c 'git -C "$1" fetch -q 2>"${2:-/dev/null}"' _ "$GSTACK_DIR" "$PULL_ERR_FILE"
PULL_EXIT=$?
fi
# The fast-forward targets the exact revision whose requirement was read.
# Setup runs `bun` from this PATH, so that is the binary checked; a
# version it cannot read holds too (bun-version-unreadable, #3195).
INCOMING="" HELD=""
if [ "$PULL_EXIT" -eq 0 ]; then
INCOMING=$(git -C "$GSTACK_DIR" rev-parse --verify '@{upstream}^{commit}' 2>"${PULL_ERR_FILE:-/dev/null}") || PULL_EXIT=1
if [ "$CHANNEL" = stable ]; then
INCOMING=$(git -C "$GSTACK_DIR" rev-parse --verify 'refs/remotes/origin/stable^{commit}' 2>"${PULL_ERR_FILE:-/dev/null}") || PULL_EXIT=1
# An install ahead of the release (it followed main until now) waits
# for stable to pass it; the updater never moves a checkout backwards.
# A depth-1 clone cannot see that an older release is its ancestor, so
# when the histories look unrelated the VERSIONs decide: main stamps a
# higher version at every merge, and stable is always a main commit.
if [ "$PULL_EXIT" -eq 0 ] && [ "$INCOMING" != "$OLD_HEAD" ] && channel_behind_release "$INCOMING" "$OLD_HEAD"; then
log_entry "CHANNEL stable ahead_of_release head=$OLD_HEAD stable=$INCOMING"
INCOMING=$OLD_HEAD
elif [ "$PULL_EXIT" -eq 0 ]; then
log_entry "CHANNEL stable target=$INCOMING"
fi
else
INCOMING=$(git -C "$GSTACK_DIR" rev-parse --verify '@{upstream}^{commit}' 2>"${PULL_ERR_FILE:-/dev/null}") || PULL_EXIT=1
fi
fi
if [ "$PULL_EXIT" -eq 0 ] && [ "$INCOMING" != "$OLD_HEAD" ]; then
HELD=$(gstack_bun_incoming_hold "$GSTACK_DIR" "$INCOMING" 2>/dev/null) || HELD=""
+3 -1
View File
@@ -4,6 +4,7 @@
* step (field list 2, W1; docs/ship-policy.md#run-a-shared-merge-queue).
*
* gstack-ship-queue ready --pr <n> [--pregate <pregate.json>] [--gate-exit <rc> --gate-log <file>]
* (refused with QUEUE_RECEIPT_MISSING|STALE unless the PR body carries /ship's receipt for HEAD)
* gstack-ship-queue stamp --pr <n> --version <X> --expect-gated <sha> --expect-base <sha>
* [--expect-order <pr,...>] [--allow-repo-commands] [--gate-exit <rc> --gate-log <file>]
* gstack-ship-queue verify --pr <n> (--gated <sha> | --record <gate-ahead.json>) [--receipt <sha256>]
@@ -33,7 +34,8 @@ import { attemptFile, listAttempts, prepareGateAhead, recordGateAhead, type Queu
const HELP = `gstack-ship-queue — the shared merge queue's protocol steps (docs/ship-policy.md#run-a-shared-merge-queue)
ready --pr <n> [--pregate <file>] [--gate-exit <rc> --gate-log <file>]
READY #<n> <head> STAMP_VERSION=<X|unstamped>, CI at that head, PREGATE, gate state
READY #<n> <head> STAMP_VERSION=<X|unstamped>, CI at that head, PREGATE, gate state,
SHIP_RECEIPT (refused unless the PR body carries /ship's receipt for that head)
stamp --pr <n> --version <X> --expect-gated <sha> --expect-base <sha> [--expect-order <pr,...>] [--allow-repo-commands]
[--gate-exit <rc> --gate-log <file>]
restamp, commit and prove: QUEUE_STAMP: <pr> <X> head= gated= tree= receipt=
+80 -2
View File
@@ -10,11 +10,16 @@
* [--out <file>] [--body <pr-body.md>] [--json]
* gstack-ship-receipt read --pr <n> [--repo <owner/repo>] [--json]
* gstack-ship-receipt read --body <file> [--json]
* gstack-ship-receipt result (--pr <n> [--repo <owner/repo>] | --body <file>) [--head <sha>] [--out <dir>] [--json]
* gstack-ship-receipt census --repo <owner/repo> --since <tag|YYYY-MM-DD> [--cohort <file>] [--limit <n>] [--json]
*
* `write` validates against `gstack-artifact schema ship-receipt`, prints the
* fenced block (and SHIP_RECEIPT: <identifiers> on stderr), writes it to --out,
* and with --body makes it the first section of that PR body file.
* `result` is /ship's terminal step: it binds the receipt to HEAD, writes the
* run record under <state>/ship/runs/ (ship-run.json: a /ship record, not a
* `run` v1 manifest, so `gstack-artifact validate` does not apply to it) and
* prints GSTACK_RESULT: skill=ship. A gh failure prints status=incomplete.
* Query commands: no GSTACK_RESULT line. Logic: lib/ship-receipt.ts.
*/
import { spawnSync } from 'node:child_process';
@@ -27,15 +32,20 @@ import { readPregateFile, verifyPregate } from '../lib/pregate/index';
import { resolveBaseBranch } from '../lib/ship-policy';
import { approvalForReceipt } from '../lib/approval-citations';
import {
computeCensus, extractReceipt, missingIssueLines, orderReceipt, placeReceiptFirst, receiptIssuesFrom, receiptSummaryLine, renderCensus, renderReceiptBlock,
validateReceipt, type CensusPr,
bindReceipt, computeCensus, extractReceipt, missingIssueLines, orderReceipt, placeReceiptFirst, receiptIssuesFrom, receiptSummaryLine, renderCensus,
renderReceiptBlock, validateReceipt, type CensusPr,
} from '../lib/ship-receipt';
import { resolveStateRoot } from '../lib/state-root';
const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block (docs/ship-policy.md#ship-receipt)
write [flags] compose, validate and print the block; --body <file> puts it first in that PR body
read --pr <n> [--repo <r>] parse the block from the PR body through gh (RECEIPT_MISSING / RECEIPT_INVALID)
read --body <file> parse the block from a file
result --pr <n> [--repo <r>] | --body <file> [--head <sha>] [--out <dir>]
/ship's terminal line: binds the receipt to HEAD (QUEUE_RECEIPT_MISSING / QUEUE_RECEIPT_STALE),
writes <state>/ship/runs/<utc>-<head12>/{ship-run.json,ship-receipt.md} and prints
GSTACK_RESULT: skill=ship status=complete run=<dir> (refused: status=refused run=-)
census --repo <r> --since <tag|date> [--cohort <file>]
the P7 adoption number over merged PRs (deduplicated by run and thread)
@@ -182,6 +192,73 @@ function cmdRead(rest: string[], json: boolean): number {
return EXIT.ok;
}
/**
* /ship's terminal line (docs/unattended.md#the-terminal-line). The receipt in
* the PR body (or the handoff file) must bind to HEAD: then the run record
* goes under <state>/ship/runs/ with the head, the PR and the receipt, and
* the last stdout line is GSTACK_RESULT: skill=ship status=complete run=<dir>.
* A missing or stale receipt is status=refused run=- (exit 3), so a parent
* never has to parse the PR body to know whether /ship finished at this head.
*/
function cmdResult(rest: string[], json: boolean): number {
const bodyFile = flag(rest, '--body');
const prFlag = flag(rest, '--pr');
if (prFlag !== undefined && !/^[1-9]\d*$/.test(prFlag)) { process.stderr.write(`gstack-ship-receipt result: --pr must be a PR number, got ${JSON.stringify(prFlag.slice(0, 40))}\n`); return EXIT.usage; }
const pr = prFlag;
if (prFlag !== undefined && flag(rest, '--body') !== undefined) { process.stderr.write('gstack-ship-receipt result: pass --pr <n> (the PR body, checked against its pushed head) or --body <file> (the handoff receipt), not both\n'); return EXIT.usage; }
const repoRoot = git(['rev-parse', '--show-toplevel']);
const head = (flag(rest, '--head') ?? (repoRoot ? git(['rev-parse', 'HEAD'], repoRoot) : undefined))?.toLowerCase();
const refused = (code: 'QUEUE_RECEIPT_MISSING' | 'QUEUE_RECEIPT_STALE', message: string) => {
process.stderr.write(resultLineWithDocs('gstack-ship-receipt result', code, message) + '\n');
process.stdout.write(json ? JSON.stringify({ skill: 'ship', status: 'refused', run: '-', code, message }) + '\n' : 'GSTACK_RESULT: skill=ship status=refused run=-\n');
return EXIT.refused;
};
if (!head) { process.stderr.write('gstack-ship-receipt result: --head <sha> is required outside a git repository\n'); return EXIT.usage; }
if (!/^[0-9a-f]{40,64}$/i.test(head)) { process.stderr.write(`gstack-ship-receipt result: --head must be a full hex commit id, got ${JSON.stringify(head.slice(0, 40))}\n`); return EXIT.usage; }
const incomplete = (why: string) => {
process.stderr.write(`gstack-ship-receipt result: ${why}\n`);
process.stdout.write(json ? JSON.stringify({ skill: 'ship', status: 'incomplete', run: '-', message: why }) + '\n' : 'GSTACK_RESULT: skill=ship status=incomplete run=-\n');
return EXIT.fail;
};
let body: string;
let source: string;
if (bodyFile) {
if (!fs.existsSync(bodyFile)) return refused('QUEUE_RECEIPT_MISSING', `${bodyFile} does not exist; /ship did not write its receipt`);
try { body = fs.readFileSync(bodyFile, 'utf8'); } catch (e) { return incomplete(`cannot read ${bodyFile}: ${e instanceof Error ? e.message : String(e)}`); }
source = path.resolve(bodyFile);
} else if (pr) {
const repo = flag(rest, '--repo');
const r = gh(['pr', 'view', pr, ...(repo ? ['--repo', repo] : []), '--json', 'body,headRefOid']);
if (!r.ok) return incomplete(`gh pr view failed: ${r.err.trim()}`);
let pushed: unknown;
try { const v = JSON.parse(r.out); body = v.body ?? ''; pushed = v.headRefOid; } catch { return incomplete('gh returned no JSON body'); }
if (typeof pushed !== 'string' || !/^[0-9a-f]{12,64}$/i.test(pushed)) return incomplete(`gh pr view returned no headRefOid for PR #${pr}`);
if (!pushed.toLowerCase().startsWith(head.toLowerCase())) {
return refused('QUEUE_RECEIPT_STALE', `HEAD ${head.slice(0, 12)} is not PR #${pr}'s pushed head ${pushed.slice(0, 12)}; push it, then rerun gstack-ship-receipt result`);
}
source = `PR #${pr}${repo ? ` (${repo})` : ''}`;
} else { process.stderr.write(`gstack-ship-receipt result: --pr <n> or --body <file> is required\n${HELP}\n`); return EXIT.usage; }
const bound = bindReceipt(body, pr, [head]);
if (!bound.ok) return refused(bound.code, bound.message);
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const out = flag(rest, '--out');
const dir = out ? path.resolve(out) : path.join(resolveStateRoot(), 'ship', 'runs', `${stamp}-${head.slice(0, 12)}`);
const receiptPath = path.join(dir, 'ship-receipt.md');
try {
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(receiptPath, renderReceiptBlock(bound.receipt));
} catch (e) { return incomplete(`cannot write the run record under ${dir}: ${e instanceof Error ? e.message : String(e)}`); }
const run = {
schema_version: 1, skill: 'ship', status: 'complete', head, pr: bound.receipt.pr ?? (pr ? Number(pr) : null), base: bound.receipt.base, version: bound.receipt.version ?? null,
queue_mode: bound.receipt.queue_mode ?? null, session_kind: bound.receipt.session_kind ?? process.env.GSTACK_SESSION_KIND ?? null,
receipt: receiptPath, receipt_source: source, branch: repoRoot ? git(['rev-parse', '--abbrev-ref', 'HEAD'], repoRoot) ?? null : null, created_at: new Date().toISOString(),
};
try { fs.writeFileSync(path.join(dir, 'ship-run.json'), JSON.stringify(run, null, 2) + '\n'); } catch (e) { return incomplete(`cannot write ${path.join(dir, 'ship-run.json')}: ${e instanceof Error ? e.message : String(e)}`); }
process.stderr.write(bound.line + '\n');
process.stdout.write(json ? JSON.stringify({ ...run, run: dir }) + '\n' : `GSTACK_RESULT: skill=ship status=complete run=${dir}\n`);
return EXIT.ok;
}
function sinceDate(repo: string, since: string): string | undefined {
if (/^\d{4}-\d{2}-\d{2}/.test(since)) return since.slice(0, 10);
const local = git(['log', '-1', '--format=%cI', since]);
@@ -214,6 +291,7 @@ function main(argv: string[]): number {
if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; }
if (cmd === 'write') return cmdWrite(rest, json);
if (cmd === 'read') return cmdRead(rest, json);
if (cmd === 'result') return cmdResult(rest, json);
if (cmd === 'census') return cmdCensus(rest, json);
process.stderr.write(`gstack-ship-receipt: unknown command ${cmd}\n${HELP}\n`);
return EXIT.usage;
+41 -17
View File
@@ -132,8 +132,27 @@ find "$_GH/sessions" -mmin +120 -type f -exec rm {} + 2>/dev/null || true
}
_SESSIONS=$(find "$_GH/sessions" -mmin -120 -type f 2>/dev/null | wc -l | tr -d ' ')
_PROACTIVE=$("$_BIN/gstack-config" get proactive 2>/dev/null || echo "true")
_PROACTIVE=$("$_BIN/gstack-config" get proactive 2>/dev/null || echo "core")
# A hand-edited config can hold anything: drop quotes and a trailing comment,
# lowercase, read the legacy true/false and the YAML yes/no family as all/off
# (an opt-out must never fail open), and anything else as core, so STATUS only
# ever says core | all | off.
_PROACTIVE=$(printf '%s' "$_PROACTIVE" | sed -e 's/[[:space:]]*#.*$//' -e "s/^[[:space:]]*[\"']*//" -e "s/[\"']*[[:space:]]*$//" | tr '[:upper:]' '[:lower:]')
case "$_PROACTIVE" in
true|yes|y|on|1) _PROACTIVE="all" ;;
false|no|n|none|0|disabled|never) _PROACTIVE="off" ;;
core|all|off) ;;
*) _PROACTIVE="core" ;;
esac
# off silences every unasked surface below: the tips, the one-time prompt and
# the CLAUDE.md routing offer. A stored off also answers the one-time prompt,
# so the marker is written here, before STATUS reports it.
case "$_PROACTIVE" in off) _PROACTIVE_OFF="yes" ;; *) _PROACTIVE_OFF="no" ;; esac
_PROACTIVE_PROMPTED=$([ -f "$_GH/.proactive-prompted" ] && echo "yes" || echo "no")
if [ "$_PROACTIVE_PROMPTED" = "no" ] && [ "$_PROACTIVE_OFF" = "yes" ]; then
touch "$_GH/.proactive-prompted" 2>/dev/null || true
_PROACTIVE_PROMPTED="yes"
fi
# Branch name is embedded in concatenated JSON below; strip anything outside
# the gstack-slug BRANCH alphabet so a hostile ref name can't forge fields.
_BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-')
@@ -322,7 +341,7 @@ echo "GSTACK_PLAN_MODE: $GSTACK_PLAN_MODE"
# GSTACK_SESSION_KIND=spawned override must light this up too.
[ "$_SESSION_KIND" = "spawned" ] && echo "SPAWNED_SESSION: true" || true
[ "$_SESSION_KIND" = "unattended" ] && echo "UNATTENDED_SESSION: true" || true
[ "$_SESSION_KIND" = "unattended" ] && [ "$SKILL_NAME" = "ship" ] && echo "UNATTENDED_SHIP: no push, no PR; Step 18 takes the handoff section; receipt at .gstack/tmp/ship-receipt.md" || true
[ "$_SESSION_KIND" = "unattended" ] && [ "$SKILL_NAME" = "ship" ] && echo "UNATTENDED_SHIP: no push, no new PR; an open PR at HEAD gets its body updated (pr-body section, receipt first), else Step 18 takes the handoff section; receipt at .gstack/tmp/ship-receipt.md; end with gstack-ship-receipt result" || true
# ---------------------------------------------------------------------------
# Artifacts sync (the former "Artifacts Sync (skill start)" fence, verbatim
@@ -544,15 +563,15 @@ Always run: \`touch "$_GH/.telemetry-prompted"\`.
EOI
fi
# Proactive-suggestions opt-in (interactive).
# Proactive-suggestions opt-in (interactive; a stored off answered it above).
if [ "$_PROACTIVE_PROMPTED" = "no" ] && [ "$_TEL_PROMPTED" = "yes" ]; then
_emit_block proactive-prompt <<EOI
Ask once:
> Let gstack proactively suggest skills, like /qa for "does this work?" or /investigate for bugs?
> Let gstack proactively suggest skills? By default it suggests only the four core ones: /office-hours for a new idea, /review for a diff, /qa for "does this work?", /ship to land it.
Options: A) Keep it on (recommended) B) Turn it off — I'll type /commands myself
If A: \`$_BIN/gstack-config set proactive true\`. If B: \`$_BIN/gstack-config set proactive false\`.
Options: A) Keep the core four (recommended) B) Suggest every matching skill C) Turn it off — I'll type /commands myself
If A: \`$_BIN/gstack-config set proactive core\`. If B: \`$_BIN/gstack-config set proactive all\`. If C: \`$_BIN/gstack-config set proactive off\`.
Always run: \`touch "$_GH/.proactive-prompted"\`.
EOI
fi
@@ -562,12 +581,14 @@ fi
if [ "$_ACTIVATED" = "no" ]; then
_FT_TIP=""
case "$_FIRST_TASK" in
greenfield) _FT_TIP="Fresh repo — shape it first with \`/spec\` or \`/office-hours\`." ;;
code_node|code_python|code_rust|code_go|code_ruby|code_ios) _FT_TIP="There's code here — \`/qa\` to see it work, or \`/investigate\` if something's off." ;;
greenfield) _FT_TIP="Fresh repo — shape it first with \`/office-hours\`." ;;
code_node|code_python|code_rust|code_go|code_ruby|code_ios) _FT_TIP="There's code here — \`/qa\` to see it work, or \`/review\` on your latest diff." ;;
branch_ahead) _FT_TIP="Unshipped work on this branch — \`/review\` then \`/ship\`." ;;
dirty_default) _FT_TIP="Uncommitted changes — \`/review\` before committing." ;;
clean_default) _FT_TIP="Pick one: \`/spec\`, \`/investigate\`, or \`/qa\`." ;;
clean_default) _FT_TIP="Pick one: \`/office-hours\`, \`/qa\`, or \`/review\`." ;;
esac
# Under off the tips are the suggestions the user turned off.
[ "$_PROACTIVE_OFF" = "yes" ] && _FT_TIP=""
if [ -n "$_FT_TIP" ]; then
_emit_block first-run-tip <<EOI
Show this one project-specific line as a heads-up, then CONTINUE with whatever the user actually asked — do NOT halt their task: $_FT_TIP
@@ -576,16 +597,19 @@ EOI
fi
touch "$_GH/.activated" 2>/dev/null || true
elif [ "$_FIRST_LOOP_SHOWN" = "no" ]; then
_emit_block first-loop-tip <<EOI
Say once as a heads-up (then continue): Tip: gstack pays off when you complete one loop — **plan → review → ship**. A common first loop: \`/office-hours\` or \`/spec\` to shape it, \`/plan-eng-review\` to lock it, then \`/ship\`.
if [ "$_PROACTIVE_OFF" = "no" ]; then
_emit_block first-loop-tip <<EOI
Say once as a heads-up (then continue): Tip: gstack pays off when you complete one loop — **plan → review → ship**. A common first loop: \`/office-hours\` to shape it, \`/review\` to check it, then \`/ship\`.
EOI
touch "$_GH/.first-loop-tip-shown" 2>/dev/null || true
touch "$_GH/.first-loop-tip-shown" 2>/dev/null || true
fi
fi
# Routing injection (interactive: AUQ + CLAUDE.md append + commit). The body
# is a quoted heredoc (markdown backticks must stay literal), so the resolved
# bin path is substituted via sed on the __BIN__ placeholder.
if [ "$_HAS_ROUTING" = "no" ] && [ "$_ROUTING_DECLINED" = "false" ] && [ "$_PROACTIVE_PROMPTED" = "yes" ]; then
# bin path is substituted via sed on the __BIN__ placeholder. Under off the
# routing rules are the auto-invocation the user turned off, so no offer.
if [ "$_HAS_ROUTING" = "no" ] && [ "$_ROUTING_DECLINED" = "false" ] && [ "$_PROACTIVE_PROMPTED" = "yes" ] && [ "$_PROACTIVE_OFF" = "no" ]; then
sed "s|__BIN__|$_BIN|g" <<'EOI' | _emit_block routing-injection
gstack works best when the project CLAUDE.md includes skill routing rules. If no CLAUDE.md exists in the project root, create it. Use AskUserQuestion:
@@ -648,13 +672,13 @@ if [ "$_SESSION_KIND" = "unattended" ]; then
case "$SKILL_NAME" in
autoplan) _UA_RECORD="This skill writes a run directory through gstack-autoplan (plan.md, review-record.md, tasks.jsonl, decisions.jsonl, findings.jsonl, timing.json, run.json, gate.json): append each recommended choice to decisions.jsonl with kind \"auto\" and each pending one with kind \"approval\" and status \"pending\". The final approval gate is written as a gate list (gstack-gate render) and this run ENDS there with \`GSTACK_RESULT: skill=autoplan status=gate_pending run=<dir>\`." ;;
eval-plan) _UA_RECORD="This run ENDS at the Step 4 spend approval, left pending, with \`GSTACK_RESULT: skill=eval-plan status=gate_pending run=<outdir>\`, where <outdir> is the pilot's --out directory. No helper writes a gate.json for this skill yet, so the parent reads the pilot report and spend ledger in <outdir>." ;;
ship) _UA_RECORD="$_UA_NONE The parent reads the ship receipt from .gstack/tmp/ship-receipt.md when nothing was pushed, and from the PR body (\`gstack-ship-receipt read --pr <n> --json\`) only once a PR exists." ;;
ship) _UA_RECORD="This skill ends with \`gstack-ship-receipt result\` (Step 22), which writes <state root>/ship/runs/<utc>-<head12>/ship-run.json (a /ship record, not a run manifest) and prints \`GSTACK_RESULT: skill=ship status=complete run=<dir>\`; a run that stops earlier prints \`GSTACK_RESULT: skill=ship status=refused run=-\` itself. The one publication allowed here: when an open PR for this branch exists and HEAD is its pushed head, update that PR's body and title with the receipt through the pr-body section's existing-PR path (never pr-create, never a push, and never \`gh pr ready\`: the draft-state items there concern an early PR this run never opened); otherwise the handoff section writes the receipt to .gstack/tmp/ship-receipt.md and the parent reads it there." ;;
review) _UA_RECORD="$_UA_NONE The parent reads the review-log rows (\`gstack-review-read\`)." ;;
qa) _UA_RECORD="$_UA_NONE The parent reads the \`qa-report-*.md\` file." ;;
*) _UA_RECORD="$_UA_NONE The parent reads this skill's own record (docs/unattended.md)." ;;
esac
_emit_block unattended-session <<EOI
You are running unattended: a parent agent started this run and reads its record, not your prose (docs/unattended.md names each skill's record). Rules: do NOT call AskUserQuestion and do NOT render prose decision briefs. At every question take the option marked (recommended). A question with no recommendation, any consent, any destructive or irreversible option, and the final approval gate stay pending: never choose them. You never approve a gate, never mark a plan APPROVED, never publish, push, sync or send data off this machine, and never record a consent. $_UA_RECORD Skip every onboarding, upgrade, telemetry, routing and lake instruction. Host adaptation: there may be no Skill tool, no slash commands and no hooks here; read the skill file with your file-reading tool, run its bash blocks as written, treat each bash block's printed STATUS lines as the only source of session facts, and write results to files the parent names rather than relying on chat text being read.
You are running unattended: a parent agent started this run and reads its record, not your prose (docs/unattended.md names each skill's record). Rules: do NOT call AskUserQuestion and do NOT render prose decision briefs. At every question take the option marked (recommended). A question with no recommendation, any consent, any destructive or irreversible option, and the final approval gate stay pending: never choose them. You never approve a gate, never mark a plan APPROVED, never publish, push, sync or send data off this machine, and never record a consent; the only exception is the one named in your skill's record rule below. $_UA_RECORD Skip every onboarding, upgrade, telemetry, routing and lake instruction. Host adaptation: there may be no Skill tool, no slash commands and no hooks here; read the skill file with your file-reading tool, run its bash blocks as written, treat each bash block's printed STATUS lines as the only source of session facts, and write results to files the parent names rather than relying on chat text being read.
EOI
fi
@@ -665,7 +689,7 @@ fi
# live in its rules, never here.
if [ "$_CAPY" = "on" ] && [ "${GSTACK_CAPY_ASKS:-}" != "0" ]; then
_emit_block capy-asks <<EOI
You run under Capy. Every decision this workflow cannot take itself (a pending gate item, a consent, an unrecommended question, a plan approval) goes through Capy's messaging, never as a bare question or gate codes: in a crew thread, a needs-you report to your Captain; with no Captain, a Capy question to the person. Write it in plain language: what it is, why it matters, what each answer does and costs, your pick, and the one-word reply. A plan approval is rendered with \`gstack-owner-brief render --captain --out <run dir>\` (before -> after, why it matters, what caused this work, big decisions, what we need) and relayed whole; fix the plan first if it exits CAPTAIN_BRIEF_INCOMPLETE. Record every answer with the person's exact words: \`gstack-approvals add\` (or \`gstack-approvals import --autoplan <run dir>\` after an autoplan answer). Cite standing approvals your Captain lists instead of asking again; always ask fresh for a product or behaviour decision, spend over a stated cap, anything published outside the repository, a threshold, budget or trial-count change, closing someone's contribution without landing it, and anything destructive. A pull request opened by /ship follows its Capy section (What changed with before/after images, Why, Approvals). Guide: capy/skill/gstack/captain.md in the gstack checkout.
You run under Capy. Every decision this workflow cannot take itself (a pending gate item, a consent, an unrecommended question, a plan approval) goes through Capy's messaging, never as a bare question or gate codes: in a crew thread, a needs-you report to your Captain; with no Captain, a Capy question to the person. Write it in plain language: what it is, why it matters, what each answer does and costs, your pick, and the one-word reply. A plan approval is rendered with \`gstack-owner-brief render --captain --out <run dir>\` (before -> after, why it matters, what caused this work, big decisions, what we need) and relayed whole; fix the plan first if it exits CAPTAIN_BRIEF_INCOMPLETE. Record every answer with the person's exact words: \`gstack-approvals add\` (or \`gstack-approvals import --autoplan <run dir>\` after an autoplan answer). Cite standing approvals your Captain lists instead of asking again; always ask fresh for a product or behaviour decision, spend over a stated cap, anything published outside the repository, a threshold, budget or trial-count change, closing someone's contribution without landing it, and anything destructive. A pull request opened by /ship follows its Capy section (What changed with before/after images, Why, Approvals). The launch environment reaches a command, your own or a child's, through \`. <the GSTACK_LAUNCH_FILE the installer printed>\` in the shell that runs it; never \`export \$(...)\`, \`env\`, \`printenv\` or a bare \`set\` in a tool fence: a bare \`export\` prints every variable, credentials included. Guide: capy/skill/gstack/captain.md in the gstack checkout.
EOI
fi
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env bash
# gstack-update-channel.sh — which branch of garrytan/gstack an install follows.
#
# Sourced by bin/gstack-session-update, bin/gstack-update-check and
# bin/gstack-upgrade; runnable by the /gstack-upgrade skill. Bash 3.2 plus git.
#
# Channels (docs/releases.md):
# main every merge to main (a version per merge, a dozen a day)
# stable the weekly tagged release: refs/heads/stable on origin, moved only
# forward along main's first-parent history by the release workflow
#
# The config key update_channel (bin/gstack-config) is auto | stable | main.
# auto, the default, is stable when team_mode is true and main otherwise, so a
# team install follows releases and a contributor install follows main with
# nothing to migrate. GSTACK_UPDATE_CHANNEL overrides the config (tests, a
# one-off command). Any other value counts as auto.
#
# Functions (never fail; a broken config means main, the behaviour before
# channels existed):
# gstack_update_channel <install dir> prints stable | main
# gstack_update_channel_refspec <channel> prints the fetch refspec for
# stable, "" for main (callers
# keep their @{upstream} /
# default-branch path)
# gstack_update_channel_missing <git stderr> true when a fetch failed only
# because origin has no such ref
# (no release cut yet): callers
# fall back to main
#
# CLI (the /gstack-upgrade skill): `bash bin/gstack-update-channel.sh [--fetch-ref] [<install dir>]`
# prints the channel; --fetch-ref fetches the channel ref from origin and
# prints the revision to fast-forward to (origin/stable or origin/main),
# falling back to origin/main only when origin has no stable yet. Any other
# fetch failure keeps origin/stable (the fast-forward then stops or finds
# nothing new); a team install never moves to main because the network
# blinked.
gstack_update_channel() {
_uc_dir=${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}
_uc_value=${GSTACK_UPDATE_CHANNEL:-}
if [ -z "$_uc_value" ] && [ -x "$_uc_dir/bin/gstack-config" ]; then
_uc_value=$("$_uc_dir/bin/gstack-config" get update_channel 2>/dev/null) || _uc_value=""
fi
case "$_uc_value" in
stable|main) printf '%s\n' "$_uc_value"; return 0 ;;
esac
_uc_team=""
[ -x "$_uc_dir/bin/gstack-config" ] && { _uc_team=$("$_uc_dir/bin/gstack-config" get team_mode 2>/dev/null) || _uc_team=""; }
if [ "$_uc_team" = true ]; then printf 'stable\n'; else printf 'main\n'; fi
}
gstack_update_channel_refspec() {
case "${1:-}" in stable) printf '+refs/heads/stable:refs/remotes/origin/stable\n' ;; *) printf '\n' ;; esac
}
gstack_update_channel_missing() {
printf '%s' "${1:-}" | grep -qiE "couldn't find remote ref|no such ref was fetched|invalid refspec" 2>/dev/null
}
if [ "${BASH_SOURCE[0]}" = "$0" ]; then
_uc_fetch=0 _uc_arg=""
for _uc_a in "$@"; do
case "$_uc_a" in
--fetch-ref) _uc_fetch=1 ;;
-h|--help) sed -n '2,36p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
*) _uc_arg=$_uc_a ;;
esac
done
_uc_root=${_uc_arg:-$(cd "$(dirname "$0")/.." && pwd)}
_uc_ch=$(gstack_update_channel "$_uc_root")
if [ "$_uc_fetch" -eq 0 ]; then printf '%s\n' "$_uc_ch"; exit 0; fi
# Egress receipts for the fetches below, fail-open like /gstack-upgrade's own.
. "$(dirname "$0")/gstack-egress-lib.sh" 2>/dev/null || _receipted_git() { shift 5; "$@"; }
_uc_host=$(git -C "$_uc_root" remote get-url origin 2>/dev/null); _uc_host=${_uc_host#*://}; _uc_host=${_uc_host#*@}; _uc_host=${_uc_host%%[/:]*}
export GIT_TERMINAL_PROMPT=0
if [ "$_uc_ch" = stable ]; then
_uc_err=$(_receipted_git open gstack-upgrade "${_uc_host:-unknown}" gstack-self-update-pull "user ran /gstack-upgrade" git -C "$_uc_root" fetch -q origin "$(gstack_update_channel_refspec stable)" 2>&1 >/dev/null) \
&& { printf 'origin/stable\n'; exit 0; }
if gstack_update_channel_missing "$_uc_err"; then
echo "gstack-update-channel: origin has no stable release yet; following origin/main until the first weekly release is cut" >&2
else
echo "gstack-update-channel: fetching origin/stable failed ($(printf '%s' "$_uc_err" | head -1 | head -c 200)); staying on origin/stable as last fetched" >&2
printf 'origin/stable\n'; exit 0
fi
fi
_receipted_git open gstack-upgrade "${_uc_host:-unknown}" gstack-self-update-pull "user ran /gstack-upgrade" git -C "$_uc_root" fetch -q origin 2>/dev/null || true
printf 'origin/main\n'
fi
+31 -9
View File
@@ -5,7 +5,9 @@
# JUST_UPGRADED <old> <new> — marker found from recent upgrade
# UPGRADE_AVAILABLE <old> <new> — remote VERSION differs from local
# UPGRADE_AVAILABLE <ver> <ver>+<n> <sha>
# — VERSION is equal but main moved <n>
# — VERSION is equal but the channel branch
# (main, or stable for a team install:
# bin/gstack-update-channel.sh) moved <n>
# commits past this checkout's HEAD (the
# GitHub compare API says so); the snooze
# is keyed by <sha>
@@ -74,9 +76,15 @@ CACHE_FILE="$STATE_DIR/last-update-check"
MARKER_FILE="$STATE_DIR/just-upgraded-from"
SNOOZE_FILE="$STATE_DIR/update-snoozed"
VERSION_FILE="$GSTACK_DIR/VERSION"
REMOTE_URL="${GSTACK_REMOTE_URL:-https://raw.githubusercontent.com/garrytan/gstack/main/VERSION}"
REMOTE_REPO="${GSTACK_REMOTE_REPO:-https://github.com/garrytan/gstack.git}"
# Channel (bin/gstack-update-channel.sh, docs/releases.md): a stable install
# compares with refs/heads/stable, the weekly release, so it is not told every
# hour that main moved. A missing helper means main.
. "$GSTACK_DIR/bin/gstack-update-channel.sh" 2>/dev/null || gstack_update_channel() { echo main; }
CHANNEL=$(gstack_update_channel "$GSTACK_DIR" 2>/dev/null) || CHANNEL=main
case "$CHANNEL" in stable|main) ;; *) CHANNEL=main ;; esac
REMOTE_RAW_BASE="${GSTACK_REMOTE_RAW_BASE:-https://raw.githubusercontent.com/garrytan/gstack}"
REMOTE_URL="${GSTACK_REMOTE_URL:-$REMOTE_RAW_BASE/$CHANNEL/VERSION}"
REMOTE_REPO="${GSTACK_REMOTE_REPO:-https://github.com/garrytan/gstack.git}"
COMPARE_API="${GSTACK_COMPARE_API:-https://api.github.com/repos/garrytan/gstack/compare}"
# ─── Force flag (busts cache + snooze for standalone /gstack-upgrade) ──
@@ -99,6 +107,8 @@ if [ -e "$GSTACK_DIR/.git" ]; then
if echo "$_H" | grep -qE '^[0-9a-f]{40}$'; then LOCAL_HEAD="$_H"; fi
fi
if [ -n "${GSTACK_REMOTE_URL:-}" ]; then UPSTREAM="$(_display_url "$REMOTE_URL")"; else UPSTREAM="$(_display_url "$REMOTE_REPO")"; fi
# A channel switch is a new upstream: the cached outcome of the other channel never replays.
[ "$CHANNEL" = stable ] && UPSTREAM="$UPSTREAM#stable"
# _identity_field <name> — a field of the cache's IDENTITY line (empty when absent).
_identity_field() {
@@ -309,12 +319,24 @@ if [ -z "${GSTACK_REMOTE_URL:-}" ]; then
# Disable credential prompts and apply a 5-second low-speed timeout so a
# flaky network or captive portal can't hang every skill preamble.
_REPO_HOST="${REMOTE_REPO#*://}"; _REPO_HOST="${_REPO_HOST#*@}"; _REPO_HOST="${_REPO_HOST%%[/:]*}"
_LSR_LINE="$(GSTACK_HOME="$STATE_DIR" _receipted_git open update-check "${_REPO_HOST:-unknown}" version-ls-remote "update_check!=false" \
bash -c 'GIT_TERMINAL_PROMPT=0 GIT_HTTP_LOW_SPEED_LIMIT=1000 GIT_HTTP_LOW_SPEED_TIME=5 \
git ls-remote "$1" refs/heads/main 2>/dev/null' _ "$REMOTE_REPO" || true)"
_ls_remote_branch() { # <branch> — the tip line of refs/heads/<branch> on REMOTE_REPO; exit 0 and nothing when origin has no such branch
GSTACK_HOME="$STATE_DIR" _receipted_git open update-check "${_REPO_HOST:-unknown}" version-ls-remote "update_check!=false" \
bash -c 'GIT_TERMINAL_PROMPT=0 GIT_HTTP_LOW_SPEED_LIMIT=1000 GIT_HTTP_LOW_SPEED_TIME=5 \
git ls-remote "$1" "refs/heads/$2" 2>/dev/null' _ "$REMOTE_REPO" "$1"
}
_LSR_LINE="$(_ls_remote_branch "$CHANNEL")" || _LSR_LINE=""
if [ "$CHANNEL" = stable ] && [ -z "$_LSR_LINE" ] && _ls_remote_branch stable >/dev/null 2>&1; then
# Before the first release origin has no stable (ls-remote answered, empty):
# this check follows main, as bin/gstack-session-update (CHANNEL_FALLBACK)
# and bin/gstack-upgrade do. The cache identity keeps #stable, so the
# outcome replays within its TTL like any other.
CHANNEL=main
REMOTE_URL="$REMOTE_RAW_BASE/main/VERSION"
_LSR_LINE="$(_ls_remote_branch main)" || _LSR_LINE=""
fi
_REMOTE_SHA="$(echo "$_LSR_LINE" | awk '{print $1}')"
if echo "$_REMOTE_SHA" | grep -qE '^[0-9a-f]{40}$'; then
# The same main SHA, HEAD and upstream as the cache: its outcome still holds.
# The same channel SHA, HEAD and upstream as the cache: its outcome still holds.
if [ "$(_identity_field remote)" = "$_REMOTE_SHA" ] && _identity_ok; then
case "$CACHED" in
UP_TO_DATE*)
@@ -385,9 +407,9 @@ if [ "$LOCAL" = "$REMOTE" ]; then
_write_cache "CHECK_FAILED $LOCAL $_CMP_SHOWN ${_WHY:-unreadable}"
if [ "$FORCE" = "1" ]; then
if [ "$_WHY" = "diverged" ]; then
echo "CHECK_FAILED this checkout (${LOCAL_HEAD:0:12}) has diverged from main (${_REMOTE_SHA:0:12}) at the same VERSION $LOCAL — update status UNKNOWN, not up-to-date"
echo "CHECK_FAILED this checkout (${LOCAL_HEAD:0:12}) has diverged from $CHANNEL (${_REMOTE_SHA:0:12}) at the same VERSION $LOCAL — update status UNKNOWN, not up-to-date"
else
echo "CHECK_FAILED could not compare this checkout (${LOCAL_HEAD:0:12}) with main (${_REMOTE_SHA:0:12}) at $_CMP_SHOWN — update status UNKNOWN, not up-to-date"
echo "CHECK_FAILED could not compare this checkout (${LOCAL_HEAD:0:12}) with $CHANNEL (${_REMOTE_SHA:0:12}) at $_CMP_SHOWN — update status UNKNOWN, not up-to-date"
fi
fi
exit 0
+43 -7
View File
@@ -1,7 +1,9 @@
#!/usr/bin/env bash
# gstack-upgrade — move this gstack checkout to the tip of its remote default
# branch, unattended and fast-forward only. The deterministic twin of the
# /gstack-upgrade skill's git fast path, for parent agents and fix lines.
# gstack-upgrade — move this gstack checkout to the tip of its update channel
# (the remote default branch, or refs/heads/stable, the weekly release, for a
# team install: bin/gstack-update-channel.sh), unattended and fast-forward
# only. The deterministic twin of the /gstack-upgrade skill's git fast path,
# for parent agents and fix lines.
#
# Usage:
# gstack-upgrade --check fetch (refs only) and print `gstack-upgrade: current <ver>`
@@ -76,7 +78,25 @@ BRANCH=$(git -C "$ROOT" symbolic-ref -q --short HEAD) \
DEFAULT=$(_receipted_git open gstack-upgrade "${HOST:-unknown}" gstack-self-update-pull "$R" bounded git -C "$ROOT" ls-remote --symref origin HEAD 2>/dev/null | sed -n 's|^ref: refs/heads/\([^[:space:]]*\)[[:space:]]*HEAD$|\1|p' | head -1)
[ -n "$DEFAULT" ] || fetch_failed "git ls-remote origin HEAD failed"
[ "$BRANCH" = "$DEFAULT" ] || refuse "on branch $BRANCH, not the remote default branch $DEFAULT (a pin)" "git -C $ROOT checkout $DEFAULT, then re-run"
_receipted_git open gstack-upgrade "${HOST:-unknown}" gstack-self-update-pull "$R" bounded git -C "$ROOT" fetch --quiet origin "$DEFAULT" 2>/dev/null || fetch_failed "git fetch origin $DEFAULT failed"
# Channel (bin/gstack-update-channel.sh, docs/releases.md): a team install
# follows refs/heads/stable, the weekly release, which is always a commit on
# the default branch's history, so the fast-forward rules below are unchanged.
# Before the first release is cut origin has no stable, and main is followed.
# shellcheck source=bin/gstack-update-channel.sh
. "$ROOT/bin/gstack-update-channel.sh" 2>/dev/null || gstack_update_channel() { echo main; }
CHANNEL=$(gstack_update_channel "$ROOT" 2>/dev/null) || CHANNEL=main
FOLLOW=$DEFAULT
if [ "$CHANNEL" = stable ]; then
if _receipted_git open gstack-upgrade "${HOST:-unknown}" gstack-self-update-pull "$R" bounded git -C "$ROOT" fetch --quiet origin stable 2>/dev/null; then
FOLLOW=stable
echo "gstack-upgrade: channel stable (the weekly release; gstack-config set update_channel main follows every merge)" >&2
elif _LSR=$(_receipted_git open gstack-upgrade "${HOST:-unknown}" gstack-self-update-pull "$R" bounded git -C "$ROOT" ls-remote origin refs/heads/stable 2>/dev/null) && [ -z "$_LSR" ]; then
echo "gstack-upgrade: channel stable has no release on origin yet; following $DEFAULT until the first weekly release is cut" >&2
else
fetch_failed "git fetch origin stable failed"
fi
fi
[ "$FOLLOW" = stable ] || _receipted_git open gstack-upgrade "${HOST:-unknown}" gstack-self-update-pull "$R" bounded git -C "$ROOT" fetch --quiet origin "$DEFAULT" 2>/dev/null || fetch_failed "git fetch origin $DEFAULT failed"
INCOMING=$(git -C "$ROOT" rev-parse FETCH_HEAD)
REMOTE_VER=$(git -C "$ROOT" show FETCH_HEAD:VERSION 2>/dev/null | head -1)
PENDING="$(git -C "$ROOT" rev-parse --absolute-git-dir)/gstack-upgrade.pending"
@@ -148,7 +168,23 @@ reinstall() { # FROM — run the install step; a pending marker survives a failu
echo "gstack-upgrade: the checkout is at $(head -1 "$ROOT/VERSION") but its reinstall failed (exit $_rc); fix: re-run $ROOT/bin/gstack-upgrade (it completes the pending reinstall)" >&2
exit 1
}
if [ "$INCOMING" = "$(git -C "$ROOT" rev-parse HEAD)" ] || git -C "$ROOT" merge-base --is-ancestor FETCH_HEAD HEAD 2>/dev/null; then
# ver_le A B — version A is not higher than B (numeric, part by part). A
# depth-1 clone cannot see that an older release is its ancestor; main stamps
# a higher VERSION at every merge and stable is always a main commit, so a
# release whose VERSION is not higher is at or behind this install.
ver_le() {
_vl_i=1
while :; do
_vl_a=$(printf '%s' "$1" | cut -d. -f"$_vl_i"); _vl_b=$(printf '%s' "$2" | cut -d. -f"$_vl_i")
[ -z "$_vl_a" ] && [ -z "$_vl_b" ] && return 0
case "${_vl_a:-0}${_vl_b:-0}" in *[!0-9]*) return 1 ;; esac
[ "${_vl_a:-0}" -lt "${_vl_b:-0}" ] && return 0
[ "${_vl_a:-0}" -gt "${_vl_b:-0}" ] && return 1
_vl_i=$((_vl_i + 1))
done
}
if [ "$INCOMING" = "$(git -C "$ROOT" rev-parse HEAD)" ] || git -C "$ROOT" merge-base --is-ancestor FETCH_HEAD HEAD 2>/dev/null \
|| { [ "$FOLLOW" = stable ] && ! git -C "$ROOT" merge-base --is-ancestor HEAD FETCH_HEAD 2>/dev/null && [ -n "$REMOTE_VER" ] && ver_le "$REMOTE_VER" "$INSTALLED"; }; then
if [ -f "$PENDING" ]; then
echo "gstack-upgrade: current $INSTALLED; reinstall pending from $(head -1 "$PENDING")"
[ "$CHECK" -eq 1 ] && exit 1
@@ -166,9 +202,9 @@ fi
DIRTY=$(git -C "$ROOT" status --porcelain --untracked-files=no 2>/dev/null | cut -c4- | tr '\n' ' ' | sed 's/ $//')
[ -z "$DIRTY" ] || refuse "tracked files changed: $DIRTY" "commit or move those changes (git -C $ROOT status --short), then re-run"
if ! git -C "$ROOT" merge-base --is-ancestor HEAD FETCH_HEAD 2>/dev/null; then
_receipted_git open gstack-upgrade "${HOST:-unknown}" gstack-self-update-pull "$R" git -C "$ROOT" fetch --quiet --unshallow origin "$DEFAULT" 2>/dev/null || true
_receipted_git open gstack-upgrade "${HOST:-unknown}" gstack-self-update-pull "$R" git -C "$ROOT" fetch --quiet --unshallow origin "$FOLLOW" 2>/dev/null || true
git -C "$ROOT" merge-base --is-ancestor HEAD FETCH_HEAD 2>/dev/null \
|| refuse "diverged: $(git -C "$ROOT" rev-list --count FETCH_HEAD..HEAD 2>/dev/null || echo '?') local commits are not on origin/$DEFAULT" "git -C $ROOT log --oneline FETCH_HEAD..HEAD shows them; move them to another branch, then re-run"
|| refuse "diverged: $(git -C "$ROOT" rev-list --count FETCH_HEAD..HEAD 2>/dev/null || echo '?') local commits are not on origin/$FOLLOW" "git -C $ROOT log --oneline FETCH_HEAD..HEAD shows them; move them to another branch, then re-run"
fi
# Workflow leases (bin/gstack-lease): sessions sharing this installation that
# are alive and not this process's own chain. Moving the checkout under them