mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-09 22:48:57 +02:00
* feat: add optional Memorable workflow memory (cherry picked from commit6bd5d477b2) * fix: refuse the second registration, and say what leaves the machine Two things the first cut got wrong. Memorable's own installer registers the same UserPromptSubmit hook, under its own name and outside gstack's table. `memorable start`, `memorable setup` and `memorable install-hooks` all do it, and that is the documented way to install the CLI, so on most machines it is already there before gstack is asked. Registering ours beside it ran the same command twice on every prompt: context injected twice, and the session captured twice against the user's own extraction allowance. `enable` now looks for it and refuses, naming the entry and the file it lives in; `status` says who registered it rather than reporting none. Matched on the command rather than on a tag, for the reason the hook table already gives: Claude Code rewrites settings and private tags do not survive it. The removal instruction says to delete the entry by hand because Memorable has no command that removes its own hook. `uninstall-hooks` is not a command in 0.5.18; it answers "unknown command". The README said "Memorable, not gstack, owns the captured data and any network access", which answers the question by pointing away from it. It now carries a per-command table of exactly what leaves the machine, in the shape the adopted gbrain section uses, and it is explicit that the hook makes no network call of its own, that every row is the third-party CLI acting under its own consent, and that `gstack-egress` will therefore not show any of it. Under it, the split between what gstack pin-tests (the gating and the wiring) and what is Memorable's claim (storage, sending, and what disable and forget erase). The CHANGELOG entry is removed. This file has never carried an [Unreleased] heading; every entry is a version and a date, written at release. The text is in the pull request for whoever cuts the next one. Three tests added: enable refuses and touches neither consent nor settings when Memorable already holds the hook, status names that registration, and a foreign UserPromptSubmit hook is not mistaken for Memorable's. (cherry picked from commite0899afa8c) * docs: a guide for the Memorable bridge, in the gbrain-sync shape README carries the section and the egress table; this is the page it links to for anyone who wants the whole thing. Same shape as docs/gbrain-sync.md, which is the closest thing in the repo: an optional integration whose interesting questions are all about what leaves the machine and how to turn it off. What it covers that the README cannot at that length: that the hook sees every Claude Code prompt rather than only the ones a skill produced; that capture is a separate consent from this bridge, so turning the bridge off does not turn capture off; what to do when Memorable has already registered the hook itself, which is the common case because its own installer does it; and why the hook has no loud failure path. The egress table is repeated here rather than linked, because the sentence it is answering ("what does this send") is the one somebody arrives on this page already asking. Co-authored-by: Advaiyt Sane <advaiyt.sane@gmail.com> Co-authored-by: Nikhil Krishnaswamy <krishnaswamynikhil@gmail.com> (cherry picked from commit5c108cc0f7) * feat(settings-hook): identity-aware remove-source + read-only list-items remove-source used to inspect only entries still carrying the _gstack_source tag. Claude Code strips that tag when it rewrites settings.json, so an off switch built on remove-source alone silently no-oped on exactly the entries it was written for. Removal is now driven by KNOWN_HOOKS identity for the requested source (tagged or not), keeps the tagged-single-item legacy-stray rule, never touches another source's items, and leaves entries with nothing of ours byte-identical. list-items is the read-only view of the same identity table: one JSON string literal per matching hook command, filters (--owned-by, --command-regex as a JavaScript RegExp) applied inside the JS, empty stdout for no match, and the mutating verbs' exit codes (1 usage, 3 unparseable settings, 4 unexpected shape) so callers can decide mutations from its output without parsing raw command strings. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(config): memorable_recall consent key (on|off, default off, reject-and-preserve) The gstack-side gate for the Memorable UserPromptSubmit bridge. `on` lets a Claude Code hook hand every prompt to a third-party binary, so the key follows the codex_reviews rule: an invalid value is rejected and the stored value kept, never coerced in either direction. Registered in all four places gstack-config keeps in sync (annotated header, DEFAULTS table, the set validator, and both enumeration loops). Memorable's own capture consent (`memorable enable`) is a separate thing gstack never sets. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(hooks): memorable-user-prompt-hook.ts — consent gate, deny veto, HIGH-tier pre-scan, fail-closed receipt, trust envelope; runExternal in spawn-bin The PR's hook exec'd the vendor binary with the full environment and passed its stdout to Claude verbatim. It is now the house pattern: a fail-open bash shim over a .ts twin that (1) gates on the memorable_recall consent key, (2) skips repos whose trust policy is deny or read-only, (3) scans the prompt (raw bytes and decoded string leaves) and refuses to hand over a HIGH-tier credential shape, (4) writes a fail-closed egress receipt naming the local executable it ran, (5) spawns the vendor in its own process group with an allowlisted environment and group-kills it on timeout, (6) accepts only a string additionalContext back, caps it at 8 KiB on a UTF-8 boundary and wraps it in the trust envelope, and (7) records an `output-written` outcome after the stdout write completes. One deadline clock (4.5 s) undercuts Claude Code's 5 s kill and bounds both ledger writes through the new lockBudgetMs option on writeReceipt/writeOutcome (default unchanged). spawn-bin gains runExternal for external executables (detached group, stderr drained, stdin EPIPE handled, stdout capped, win32 refused). The wiring test pins the sink fail-closed and sweeps hosts/. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(gstack-memorable): canonical hook path, no vendor consent, --timeout 5, identity-based status, verified disable, lifecycle lock enable used to bake the hook path from whatever tree the CLI ran in and to run the vendor's own `memorable enable` (its consent for storing AND uploading session traces) before registering anything. It now resolves the canonical install like setup does and refuses when that install does not carry this bridge (version and hook-twin check), registers through the canonical hook manager with --timeout 5, records gstack's own consent in memorable_recall, never executes the vendor, and restores the captured prior state if consent cannot be recorded. disable flips the gate first, removes the entry by identity (tag or no tag), verifies both states and reports partial failure instead of a blended success. status reads only: resolution path, gate, registration by identity (gstack / vendor-own / both / unknown), mismatch lines, receipt count, recent hook errors. enable and disable serialise under a lock with stale takeover. Windows is refused (TODOS.md D21). Exit codes mirror the hook manager (3/4/5). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(setup): --no-team sweep keeps the opt-in gstack-memorable hook `./setup --no-team` finishes its teardown with `prune-stale --all`, which removes every KNOWN_HOOKS item. The Memorable bridge hook is a user-registered opt-in unrelated to team mode, exactly like verify-gate, so it joins the sweep exclusion list. The verify-gate pin now accepts the comma-extended list; a schema-aware case proves the exclusion keeps both opt-ins (tagged or tag-stripped) while the uninstall sweep still removes them. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(uninstall): named gstack-memorable arm, vendor-consent notice, honest kept config The identity sweep already removed the Memorable bridge hook as an unnamed stray. It now has a named arm like every other source, so the summary says what went, and says plainly that Memorable's own consent (if the user granted it) is theirs to revoke. Under --keep-state the kept config is set memorable_recall=off so it never claims a hook that is gone. The canonical-paths pins cover the sixth KNOWN_HOOKS row and the new uninstall source. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(egress): memorable-recall row in gstack-egress grants `gstack-egress grants` promises every standing consent in force with the command that revokes it. The Memorable bridge's memorable_recall key is one, so it gets a row: off by default, granted only when `gstack-memorable enable` set it, revoked by `gstack-memorable disable`. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(memorable): accurate bridge guide; README row, Docs table, privacy pointer; PROJECT_STRUCTURE The README section becomes one row in the Standalone binaries table (the shape every other binary uses) plus a Docs-table row and one Privacy bullet saying that optional third-party bridges are off by default and receipted. The guide now separates the two consents, says what gstack hands to the vendor binary and what the receipt can and cannot attest, attributes every statement about the vendor's network activity to the vendor, describes the hook manager accurately (identity via KNOWN_HOOKS, list-items vs list-sources, rollback is whole-file), states the Claude Code hot-reload behaviour, adds a troubleshooting runbook, and keeps the contributors' credit in the CHANGELOG idiom. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(todos): Memorable bridge follow-ups Filed from the CEO and eng reviews of the bridge fix-up: the generic third-party hook seam, Windows support (deferred whole), the envelope kind parameter, a vendor payload-minimization contract, a latency and timeout revisit, resolver and canonical-root consolidation, a non-interactive MEDIUM-tier redaction policy for hooks, and adopting list-items at setup's plan-tune check. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(settings-hook): list-items --owned-by with --command-regex intersects When both filters are given, an item must satisfy both: owned by the requested source AND matching the pattern. Before, the regex branch skipped every owned row, so the combination could never match. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(gstack-memorable): compat_check reads list-items output before grepping Under pipefail, piping the probe straight into grep -q let a non-zero probe exit mask the match, so a hook manager without list-items was sometimes reported as compatible. Capture the output, then grep. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test: coverage for the memorable bridge (remove-source regression for every KNOWN_HOOKS source) - settings-hook: identity removal pinned for each source in KNOWN_HOOKS; list-items unknown flag and combined --owned-by/--command-regex - gstack-memorable: enable/disable failure paths (lock give-up exit 5 with the test-only lock timeout override, consent-write failures guarded by canRevokeWrites, canonical-version mismatch, no-bun status) - hook: non-object JSON, missing cwd, non-ASCII bytes, held-open stdin, shim without bun, stripControl, resolveVendor, runExternal ENOENT - egress-receipt: lockBudgetMs 0 and writeOutcome on garbage input - uninstall: no memorable entry present reports nothing removed Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(memorable): gbrain backend note and the settings-rewrite race Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * perf(redact-engine): line/col by binary search over a per-scan line index lineColAt walked the input from offset 0 for every finding, so a match-dense input (a pasted log full of emails and IPs) cost O(findings x bytes): 128 KiB took ~400 ms and 900 KiB tens of seconds. The line starts are now indexed once per scan, on the first finding, and each finding is a binary search. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(gbrain-repo-policy-client): repoPolicyTier accepts a spawn timeout The policy script spawn was fixed at 10 s, more than twice the memorable hook's whole budget. Callers on their own deadline pass what they can afford; a timeout reads as unreadable and polarity stays the caller's. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(spawn-bin): runExternal resolves on the child's exit, keeps stdin errors advisory - A vendor that exits 0 but leaves a background child holding its pipes was held to the deadline, group-killed and reported as a timeout with its answer dropped. 'exit' now starts a short stdout drain, then resolves with the real exit code and kills whatever still holds the group. - EPIPE on the child's stdin (it answered before reading a large input) is reported as stdinError, separate from error, so a delivered answer is not classified as a spawn failure. - Stdio streams are destroyed and the child unref'd on resolve so a straggler cannot pin the hook process; tail/grace/drain sizes are named constants. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(hooks): memorable hook closes the review army's gaps - Vendor failures are logged even with empty stderr (a silently hanging vendor taxed every prompt invisibly); the stderr tail is withheld when the redaction engine finds a credential or PII shape in it; hook-errors.log is created 0600. - Trust-policy veto fails closed when git cannot run or answer in time (it read as 'no remote' before); the policy script spawn is bounded by the hook's clock; a payload cwd that is not a directory falls back. - Each secret scan is admitted by the deadline clock (the engine's cost grows with match density); stdin is decoded once. - The pre-spawn gate re-check logs a config failure instead of swallowing it; an incomplete stdin read is named as such, not as 'not JSON'. - Carriage returns are stripped with the other controls. - The vendor env allowlist adds the standard proxy, TLS and XDG variables so a vendor behind a corporate proxy or private CA still reaches its service. - A stdin EPIPE on a delivered answer is recorded in the outcome, not treated as a spawn error. - Stage caps and the truncation marker are named constants; a test-only GSTACK_MEMORABLE_TEST_BUDGET_MS can shorten (never widen) the budget. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(gstack-memorable): lock staleness from the directory mtime; honest messages - A contender that looked between the holder's mkdir and its ts write read a missing ts as 0, called the lock stale and reclaimed it; staleness now comes from the lock directory's own mtime (the settings-hook idiom). - The ensure-event failure is no longer labelled 'warning'; the consent-write rollback message says what was actually kept; a removal that left no entry is reported on stdout, not as an error; receipts are counted from the filtered JSON array, not a formatting artefact; the resolution order and lock tuning are named once. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(uninstall): memorable_recall goes off whether or not state is kept gstack-config resolves its root through GSTACK_STATE_ROOT/GSTACK_HOME, which can differ from the STATE_DIR uninstall removes; a full uninstall could leave memorable_recall=on in a config that survived. Flipped only when currently on. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test: pin the review-army fixes for the memorable bridge Nonce-scoped orphan checks (the system-wide ps grep could see another shard's sleeper); exit-with-lingering-grandchild; advisory stdin EPIPE; withheld stderr; vendor timeout logged with empty stderr; CR stripping; budget seam; rate-limit expiry and 0600 log; unreadable policy store fails closed; file-as-cwd fallback; mtime-based lock staleness and the mkdir gap. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(memorable): vendor environment allowlist and stderr policy; two follow-ups Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(hooks): memorable hook second-pass review fixes - Trust-policy lookup fails closed on any git failure that is not 'no such remote' or 'not a git repository' (a corrupt or unreadable .git/config and dubious ownership exit 128 and used to read as 'no remote'). - pickAdditionalContext takes the first complete top-level JSON object, so a vendor whose background helper appends a line to stdout (or prints a banner first) does not lose its answer. - The hook-errors.log rate limiter keys on a stable string (a vendor's timestamped stderr no longer defeats it); the log is chmod 0600 on every append because sibling hooks create the same file without a mode. - Scan admission is sized by payload bytes (scan() is uninterruptible). - The receipt payload class is a stable token; the prose moved to the docs. - Header, constants and comments match the behaviour (silent skips vs logged refusals; HIGH/MEDIUM withholding; STAGE_CAP_MS scope; runExternal in the spawn-bin header; the ledger lock budget doc). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(gstack-memorable): stale-lock takeover by atomic rename; comments match behaviour Two contenders that both saw a stale lock could both reclaim it with rm -rf; the settings-hook idiom (mv to a private name, exactly one winner) is used instead. The hook-manager fallback comment now says every verb falls back. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test: second-pass coverage for the memorable bridge Policy lookup outcomes (plain dir, repo without policy, corrupt .git/config fails closed); repoPolicyTier timeoutMs; line/col at line starts, after blank lines, CRLF and first char; tolerant first-JSON-object parsing; keyed rate limit; uninstall never creates a config just to say off and flips consent in a GSTACK_STATE_ROOT outside the removed state dir. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(memorable): silent skips vs logged refusals; payload class token; D21/D24 anchors Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(hooks): memorable hook survives host termination and brace-bearing banners - The bash shim runs bun as a job and forwards SIGTERM/SIGINT/SIGHUP (bash holds a signal until a foreground child exits); the .ts kills the in-flight vendor's process group on the way out (runExternal exposes the group kill through onSpawn), so a hook the host terminates cannot leave the vendor running with the prompt on its stdin. - The tolerant stdout parser tries every complete top-level object (bounded) and takes the first carrying a string additionalContext, so a banner with braces or quotes, or a progress object, no longer costs the answer. - git runs with LC_ALL=C and the not-a-repository check is anchored to the start of its message: a localized git or a repository path containing the phrase can no longer flip the lookup. - The rate limiter remembers up to 32 live keys, so alternating failures cost two lines, not one per prompt. - Unicode format characters (bidi overrides, zero-width spaces) are stripped from vendor text at egress; the zero-width joiner stays for emoji. - A killed child (timeout, ENOBUFS) resolves on exit without the stdout drain, and the post-kill grace is 100 ms, so the timeout outcome fits the reserve. - The ledger size warning, which the host discards from an exit-0 hook's stderr, is logged where status looks. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(gstack-memorable): failed stale-lock takeover reaches the give-up; disable runs without gstack-config; status shows ledger size Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test: host termination kills the vendor group; brace banners, decoys and format characters; non-reclaimable stale lock gives up; ledger line in status Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(memorable): the vendor dies with a terminated hook Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test: deterministic stdin EPIPE case for runExternal (child closes stdin, stays alive) Under parallel shard load a child that merely exits fast raced the write and the EPIPE was not always observed; closing the read end first makes it so. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(hooks): outside-model review fixes for the memorable hook and runExternal - Nothing in the vendor's process group outlives the call: the group is killed on every resolve, the clean 'close' path included (a helper the vendor forked with redirected stdio ran on unsupervised before). - A child that already exited when the deadline fires keeps its result; the deadline only ends the drain instead of rewriting a completed exit as a timeout. - The decoded-leaf scan reports when its node/depth bound cut the walk short and the hook refuses the hand-off as unscanned; object keys are scanned too. - git for the trust-policy lookup runs without inherited GIT_* selectors (GIT_DIR, GIT_WORK_TREE, GIT_CONFIG_*), so it inspects the session's repository and no other; a host cancellation kills that git as well. - An unmatched brace in a vendor banner no longer hides the answer after it. - The stderr tail is scanned whole before it is cropped for the log, so a credential's prefix cannot be cropped away from its secret half. - The vendor override reads an empty GSTACK_MEMORABLE_BIN as unset, exactly as bin/gstack-memorable does, so enable checks the binary the hook runs. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(gstack-memorable): stale-lock reclaim checks the inode it judged and the owner's liveness; status reports a failed receipt query as unknown Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(uninstall): revoke memorable_recall independently of the hook manager and name a failed revocation Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test: group kill on clean close, walk exhaustion refused, GIT_DIR cannot bypass the deny, unmatched-brace banner, whole-tail scan, empty-override parity, uninstall revocation without the hook manager Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs(memorable): the process-group guarantee and its setsid boundary Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * chore(release): v1.83.0.0 — Memorable recall bridge, identity-aware hook removal, faster redaction line/col CHANGELOG entry for the Memorable workflow-memory bridge (opt-in, off by default, Claude Code only), the identity-aware remove-source and read-only list-items in the hook manager, the memorable-recall egress sink, runExternal, lockBudgetMs, and the binary-search line/col index in the redaction engine. No migration. Contributed by @AdvaiytSane and @NIkhil-cmd-cmd (#2831). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test: stdin EPIPE observation is scheduling-dependent under shard load; pin the invariant instead A delivered answer is never reclassified as a spawn error; when the EPIPE is observed it is reported as stdinError. Whether it is observed before the child's exit resolves the call is not something the test can force. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs: list the memorable-recall sink among the fail-closed egress sinks CLAUDE.md and ARCHITECTURE.md enumerate the receipt sinks that refuse to send when the ledger cannot be written; the Memorable bridge's per-prompt hand-off is pinned fail-closed in test/egress-receipt-wiring.test.ts but was missing from both lists. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test: memorable bridge tests pass on a runner that enforces file modes; scanner-proof key fixture - The consent-write-failure tests make the state dir read-only, which also blocked the bridge lock directory (exit 5 before the path under test); the locks dir is pre-created so only the consent write fails. - The unreadable-store test leaves a 0600 directory behind (the policy script chmods the store path); cleanup restores the search bit and the suite's afterEach reopens directories before removing. - The AWS-key-shaped fixture is built by concatenation, as every sibling test does, so the CI credential gate does not read it as a live key. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(gstack-memorable): name an unwritable state directory when the lock cannot be created Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: AdvaiytSane <advaiyt.sane@gmail.com> Co-authored-by: Nikhil Krishnaswamy <krishnaswamynikhil@gmail.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
605 lines
33 KiB
Bash
Executable File
605 lines
33 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
# gstack-config — read/write ~/.gstack/config.yaml
|
|
#
|
|
# Usage:
|
|
# gstack-config get <key> — read a config value (falls back to DEFAULTS)
|
|
# gstack-config has <key> — exit 0 iff the key is literally present in the
|
|
# config file (get returns DEFAULTS for absent keys,
|
|
# so callers that need provenance use this instead)
|
|
# gstack-config set <key> <value> — write a config value
|
|
# gstack-config list — show all config (values + defaults)
|
|
# gstack-config defaults — show just the defaults table
|
|
#
|
|
# Env overrides (for testing):
|
|
# GSTACK_STATE_ROOT — override ~/.gstack state directory (highest priority,
|
|
# matches D16 cathedral isolation convention)
|
|
# GSTACK_HOME — override ~/.gstack state directory (aligns with writer scripts)
|
|
# GSTACK_STATE_DIR — legacy alias for GSTACK_HOME (kept for backwards compat)
|
|
set -euo pipefail
|
|
|
|
STATE_DIR="${GSTACK_STATE_ROOT:-${GSTACK_HOME:-${GSTACK_STATE_DIR:-$HOME/.gstack}}}"
|
|
CONFIG_FILE="$STATE_DIR/config.yaml"
|
|
|
|
# Swap a freshly-rendered tmp dir into the live render location (#2569
|
|
# hardening). Installed skills SYMLINK into the live dir, so it is only ever
|
|
# replaced AFTER a successful render — a failed render leaves the previous
|
|
# render (and every link into it) fully intact. Keep in sync with setup's
|
|
# _swap_in_render (same contract, both pinned by
|
|
# test/user-render-out-dir-install.test.ts).
|
|
_swap_in_render() {
|
|
local render_dir="$1" render_tmp="$2"
|
|
local render_old="$render_dir.old.$$"
|
|
rm -rf "$render_old"
|
|
if [ -e "$render_dir" ] || [ -L "$render_dir" ]; then mv "$render_dir" "$render_old"; fi
|
|
mv "$render_tmp" "$render_dir"
|
|
rm -rf "$render_old"
|
|
}
|
|
|
|
# Annotated header for new config files. Written once on first `set`.
|
|
# Default semantics: DEFAULTS table below is the canonical source. Header text
|
|
# is documentation that must stay in sync with DEFAULTS.
|
|
CONFIG_HEADER='# gstack configuration — edit freely, changes take effect on next skill run.
|
|
# 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.
|
|
#
|
|
# routing_declined: false # Set to true to skip the CLAUDE.md routing injection
|
|
# # prompt. Set back to false to be asked again.
|
|
#
|
|
# ─── Telemetry ───────────────────────────────────────────────────────
|
|
# telemetry: off # off | anonymous | community
|
|
# # off — no data sent, no local analytics (default)
|
|
# # anonymous — counter only, no device ID
|
|
# # community — usage data + stable device ID
|
|
#
|
|
# ─── Updates ─────────────────────────────────────────────────────────
|
|
# auto_upgrade: false # true = silently upgrade on session start
|
|
# update_check: true # false = suppress version check notifications
|
|
#
|
|
# ─── Skill naming ────────────────────────────────────────────────────
|
|
# skill_prefix: false # true = namespace skills as /gstack-qa, /gstack-ship
|
|
# # false = short names /qa, /ship
|
|
#
|
|
# ─── Checkpoint ──────────────────────────────────────────────────────
|
|
# checkpoint_mode: explicit # explicit | continuous
|
|
# # explicit — commit only when you run /ship or /checkpoint
|
|
# # continuous — auto-commit after each significant change
|
|
# # with WIP: prefix + [gstack-context] body
|
|
#
|
|
# checkpoint_push: false # true = push WIP commits to remote as you go
|
|
# # false = keep WIP commits local only (default)
|
|
# # Pushing can trigger CI/deploy hooks — opt in carefully.
|
|
#
|
|
# ─── Writing style (V1) ──────────────────────────────────────────────
|
|
# explain_level: default # default = jargon-glossed, outcome-framed prose
|
|
# # (V1 default — more accessible for everyone)
|
|
# # terse = V0 prose style, no glosses, no outcome-framing layer
|
|
# # (for power users who know the terms)
|
|
# # Unknown values default to "default" with a warning.
|
|
# # See docs/designs/PLAN_TUNING_V1.md for rationale.
|
|
#
|
|
# ─── Artifacts sync (renamed from gbrain_sync_mode in v1.27.0.0) ─────
|
|
# artifacts_sync_mode: off # off | artifacts-only | full
|
|
# # off — no sync (default)
|
|
# # artifacts-only — sync plans/designs/retros/learnings only
|
|
# # (skip behavioral data: question-log,
|
|
# # developer-profile, timeline)
|
|
# # full — sync everything allowlisted
|
|
# # Set by the first-run privacy stop-gate. See docs/gbrain-sync.md.
|
|
#
|
|
# artifacts_sync_mode_prompted: false
|
|
# # Set to true once the privacy gate has asked the user.
|
|
# # Flip back to false to be re-prompted.
|
|
#
|
|
# ─── Timeline Stop hook ──────────────────────────────────────────────
|
|
# timeline_stop_hook: yes # Controls whether ./setup registers the timeline
|
|
# # Stop hook (closes dangling session entries).
|
|
# # yes — register on every setup (default)
|
|
# # no — never register; setup also removes a
|
|
# # live registration (persistent opt-out;
|
|
# # --no-team stays a one-shot teardown, #2677)
|
|
#
|
|
# ─── Plan-tune hooks ─────────────────────────────────────────────────
|
|
# plan_tune_hooks: prompt # Controls whether ./setup installs the plan-tune
|
|
# # Claude Code hooks (PostToolUse capture +
|
|
# # PreToolUse preference enforcement).
|
|
# # prompt — ask on a real TTY, skip otherwise (default)
|
|
# # yes — install non-interactively
|
|
# # no — skip non-interactively
|
|
# # Override per-run: ./setup --plan-tune-hooks /
|
|
# # --no-plan-tune-hooks, or env GSTACK_PLAN_TUNE_HOOKS.
|
|
#
|
|
# ─── Memorable recall bridge (opt-in, third party) ──────────────────
|
|
# memorable_recall: off # The gstack-side consent gate for the Memorable
|
|
# # UserPromptSubmit bridge (bin/gstack-memorable).
|
|
# # off — the hook does nothing, spawns nothing (default)
|
|
# # on — the hook hands each prompt to the local
|
|
# # `memorable` CLI, receipted as memorable-recall
|
|
# # Written by `gstack-memorable enable|disable`. An
|
|
# # invalid value is REJECTED and the stored value kept:
|
|
# # a typo must never flip a third-party consent.
|
|
# # The vendor capture consent (`memorable enable`)
|
|
# # is separate; gstack never sets it.
|
|
#
|
|
# ─── Advanced ────────────────────────────────────────────────────────
|
|
# codex_reviews: enabled # Master switch for Codex cross-model review. enabled =
|
|
# # Codex runs as a standard step in /review, /ship,
|
|
# # /document-release, plan reviews, and /autoplan (auto
|
|
# # falls back to a Claude subagent if Codex is missing or
|
|
# # not authenticated). disabled = skip all Codex passes.
|
|
# # Asymmetry on disabled: diff-review (/review, /ship) still
|
|
# # runs the free Claude adversarial subagent; plan-review and
|
|
# # /document-release skip the outside-voice step entirely.
|
|
# # An invalid value is REJECTED (existing value preserved) so
|
|
# # a typo cannot silently turn paid Codex calls on or off.
|
|
# gstack_contributor: false # true = file field reports when gstack misbehaves
|
|
# skip_eng_review: false # true = skip eng review gate in /ship (not recommended)
|
|
#
|
|
# ─── Workspace-aware ship ────────────────────────────────────────────
|
|
# workspace_root: $HOME/conductor/workspaces # Where /ship looks for sibling
|
|
# # Conductor worktrees when picking a VERSION slot.
|
|
# # Set to "null" to disable sibling scanning entirely.
|
|
# # Non-Conductor users can point this at any directory
|
|
# # that holds parallel worktrees of the same repo.
|
|
#
|
|
'
|
|
|
|
# DEFAULTS table — canonical default values for known keys.
|
|
# `get <key>` returns DEFAULTS[key] when the key is absent from the config file
|
|
# AND the env override is not set. Keep in sync with the CONFIG_HEADER comments.
|
|
lookup_default() {
|
|
case "$1" in
|
|
proactive) echo "true" ;;
|
|
routing_declined) echo "false" ;;
|
|
telemetry) echo "off" ;;
|
|
auto_upgrade) echo "false" ;;
|
|
update_check) echo "true" ;;
|
|
skill_prefix) echo "false" ;;
|
|
checkpoint_mode) echo "explicit" ;;
|
|
checkpoint_push) echo "false" ;;
|
|
explain_level) echo "default" ;;
|
|
codex_reviews) echo "enabled" ;;
|
|
gstack_contributor) echo "false" ;;
|
|
skip_eng_review) echo "false" ;;
|
|
workspace_root) echo "$HOME/conductor/workspaces" ;;
|
|
cross_project_learnings) echo "" ;; # intentionally empty → unset triggers first-time prompt
|
|
artifacts_sync_mode) echo "off" ;;
|
|
artifacts_sync_mode_prompted) echo "false" ;;
|
|
plan_tune_hooks) echo "prompt" ;; # prompt | yes | no — controls ./setup plan-tune hook install
|
|
timeline_stop_hook) echo "yes" ;; # yes | no — controls ./setup timeline Stop hook registration (#2677)
|
|
|
|
redact_repo_visibility) echo "" ;; # empty → fall through to gh/glab detection
|
|
redact_prepush_hook) echo "false" ;;
|
|
pair_agent) echo "off" ;; # remote tunnel consent — fail-closed until /pair-agent asks
|
|
memorable_recall) echo "off" ;; # on | off — Memorable bridge gate, fail-closed until `gstack-memorable enable`
|
|
founder_resources) echo "true" ;; # office-hours resource pitch — #538 permanent opt-out sets false
|
|
# Brain-aware planning (v1.48 / T5+T10+T16). Defaults documented inline:
|
|
# brain_trust_policy@<endpoint-id> — unset on fresh install; setup-gbrain
|
|
# writes 'personal' for local engines,
|
|
# asks the user for remote-ambiguous.
|
|
# salience_allowlist — empty falls through to
|
|
# SALIENCE_DEFAULT_ALLOWLIST (D9).
|
|
# user_slug_at_<endpoint-id> — empty triggers resolve-user-slug
|
|
# fallback chain (D4 A3) on first call.
|
|
brain_trust_policy*) echo "unset" ;;
|
|
salience_allowlist) echo "" ;;
|
|
user_slug_at_*) echo "" ;;
|
|
# Read by skill preambles but missing from this table, so they fell through
|
|
# to the catch-all and came back "" with exit 0. Values below are the ones
|
|
# the callers already assume in their own `|| echo "<default>"` fallback.
|
|
question_tuning) echo "false" ;;
|
|
team_mode) echo "false" ;;
|
|
transcript_ingest_mode) echo "off" ;;
|
|
# repo_mode: EMPTY is load-bearing — gstack-repo-mode treats any non-empty
|
|
# answer as a user override and skips its own classification entirely, so
|
|
# a synthesized "unknown" default turns the classifier into dead code.
|
|
# Empty + exit 0 = "no override set, go classify".
|
|
repo_mode) echo "" ;;
|
|
# Unknown key: exit non-zero instead of printing "". The fallback pattern
|
|
# the preambles use,
|
|
# VAR=$(gstack-config get <key> 2>/dev/null || echo "<default>")
|
|
# only fires on a non-zero exit, so a catch-all echoing "" with exit 0 left
|
|
# VAR empty and the written default unreachable.
|
|
# Deliberately *only* the unknown-key path: the keys above whose default is
|
|
# intentionally empty (cross_project_learnings, salience_allowlist,
|
|
# user_slug_at_*, redact_repo_visibility) keep exit 0, because "" is their
|
|
# real answer and their callers rely on it.
|
|
*) return 1 ;;
|
|
esac
|
|
}
|
|
|
|
# ──────────────────────────────────────────────────────────────────────
|
|
# Brain-integration helpers (T5+T10+T16)
|
|
# ──────────────────────────────────────────────────────────────────────
|
|
|
|
# Compute sha8 of a string. Used for endpoint hashing.
|
|
# shasum is macOS/perl; most Linux distros ship only coreutils sha256sum —
|
|
# resolve whichever exists (same fallback chain as the codex-probe timeout
|
|
# wrapper). Without this, any Linux user with a git email hit exit 127 in
|
|
# resolve-user-slug's Layer-3 fallback.
|
|
sha8_of() {
|
|
if command -v sha256sum >/dev/null 2>&1; then
|
|
printf '%s' "$1" | sha256sum | cut -c1-8
|
|
else
|
|
printf '%s' "$1" | shasum -a 256 | cut -c1-8
|
|
fi
|
|
}
|
|
|
|
# Detect the active brain endpoint hash. Reads ~/.claude.json for the gbrain
|
|
# MCP server URL. Falls back to the literal 'local' when no MCP is configured.
|
|
endpoint_hash() {
|
|
_claude_json="$HOME/.claude.json"
|
|
if [ -f "$_claude_json" ] && command -v jq >/dev/null 2>&1; then
|
|
_url=$(jq -r '.mcpServers.gbrain.url // .mcpServers.gbrain.transport.url // empty' "$_claude_json" 2>/dev/null)
|
|
if [ -n "$_url" ] && [ "$_url" != "null" ]; then
|
|
sha8_of "$_url"
|
|
return 0
|
|
fi
|
|
fi
|
|
printf '%s' "local"
|
|
}
|
|
|
|
# Detect endpoint hash collisions. When two distinct endpoints share the same
|
|
# sha8 prefix (rare but possible), escalate to sha16 by emitting the longer
|
|
# hash. Detection: scan config file for existing brain_trust_policy@<hash> or
|
|
# user_slug_at_<hash> keys; if any non-active hash equals the active sha8 but
|
|
# would differ at sha16, the active endpoint needs sha16.
|
|
endpoint_hash_with_collision_check() {
|
|
_active=$(endpoint_hash)
|
|
if [ "$_active" = "local" ]; then
|
|
printf '%s' "$_active"
|
|
return 0
|
|
fi
|
|
# If a different endpoint (different URL) shares this sha8, escalate.
|
|
# We only catch this when the config has another endpoint recorded.
|
|
_matching=$(grep -E "^(brain_trust_policy|user_slug_at)@${_active}" "$CONFIG_FILE" 2>/dev/null | head -1 || true)
|
|
_claude_json="$HOME/.claude.json"
|
|
if [ -n "$_matching" ] && [ -f "$_claude_json" ] && command -v jq >/dev/null 2>&1; then
|
|
_url=$(jq -r '.mcpServers.gbrain.url // .mcpServers.gbrain.transport.url // empty' "$_claude_json" 2>/dev/null)
|
|
if command -v sha256sum >/dev/null 2>&1; then
|
|
_sha16=$(printf '%s' "$_url" | sha256sum | cut -c1-16)
|
|
else
|
|
_sha16=$(printf '%s' "$_url" | shasum -a 256 | cut -c1-16)
|
|
fi
|
|
# Look for any sha16-namespaced key that conflicts. If a stored sha16 exists
|
|
# and differs from current sha16, that's the collision evidence; emit sha16.
|
|
_stored16=$(grep -E "^(brain_trust_policy|user_slug_at)@${_sha16}" "$CONFIG_FILE" 2>/dev/null | head -1 || true)
|
|
if [ -n "$_stored16" ]; then
|
|
printf '%s' "$_sha16"
|
|
return 0
|
|
fi
|
|
fi
|
|
printf '%s' "$_active"
|
|
}
|
|
|
|
# Resolve the user-slug per D4 A3 chain:
|
|
# 1. mcp__gbrain__whoami.client_name (best effort via gbrain CLI shell-out)
|
|
# 2. $USER env
|
|
# 3. sha8($(git config user.email))
|
|
# 4. anonymous-<sha8(hostname)>
|
|
# Persists result via gstack-config set user_slug_at_<endpoint-hash> on first call.
|
|
resolve_user_slug() {
|
|
_hash=$(endpoint_hash_with_collision_check)
|
|
_stored=$(grep -E "^user_slug_at_${_hash}:" "$CONFIG_FILE" 2>/dev/null | tail -1 | awk '{print $2}' | tr -d '[:space:]' || true)
|
|
if [ -n "$_stored" ]; then
|
|
printf '%s' "$_stored"
|
|
return 0
|
|
fi
|
|
|
|
_slug=""
|
|
|
|
# Layer 1: gbrain whoami
|
|
if command -v gbrain >/dev/null 2>&1; then
|
|
_whoami=$(gbrain whoami --json 2>/dev/null || true)
|
|
if [ -n "$_whoami" ] && command -v jq >/dev/null 2>&1; then
|
|
_client_name=$(printf '%s' "$_whoami" | jq -r '.client_name // .token_name // empty' 2>/dev/null || true)
|
|
if [ -n "$_client_name" ] && [ "$_client_name" != "null" ]; then
|
|
_slug=$(printf '%s' "$_client_name" | tr '[:upper:] ' '[:lower:]-' | tr -dc '[:alnum:]-')
|
|
fi
|
|
fi
|
|
fi
|
|
|
|
# Layer 2: $USER
|
|
if [ -z "$_slug" ] && [ -n "${USER:-}" ]; then
|
|
_slug=$(printf '%s' "$USER" | tr '[:upper:] ' '[:lower:]-' | tr -dc '[:alnum:]-')
|
|
fi
|
|
|
|
# Layer 3: sha8 of git email
|
|
if [ -z "$_slug" ]; then
|
|
_email=$(git config user.email 2>/dev/null || true)
|
|
if [ -n "$_email" ]; then
|
|
_slug="email-$(sha8_of "$_email")"
|
|
fi
|
|
fi
|
|
|
|
# Layer 4: anonymous-<sha8(hostname)>
|
|
if [ -z "$_slug" ]; then
|
|
_slug="anonymous-$(sha8_of "$(hostname 2>/dev/null || echo unknown)")"
|
|
fi
|
|
|
|
# Persist via direct file write (avoid recursion into gstack-config set)
|
|
mkdir -p "$STATE_DIR"
|
|
if [ ! -f "$CONFIG_FILE" ]; then
|
|
printf '%s' "$CONFIG_HEADER" > "$CONFIG_FILE"
|
|
fi
|
|
if ! grep -qE "^user_slug_at_${_hash}:" "$CONFIG_FILE" 2>/dev/null; then
|
|
echo "user_slug_at_${_hash}: ${_slug}" >> "$CONFIG_FILE"
|
|
fi
|
|
|
|
printf '%s' "$_slug"
|
|
}
|
|
|
|
read_config_value() {
|
|
local key="$1"
|
|
if [ ! -f "$CONFIG_FILE" ]; then
|
|
return 0
|
|
fi
|
|
grep -E "^${key}:" "$CONFIG_FILE" 2>/dev/null \
|
|
| tail -1 \
|
|
| sed -E "s/^${key}:[[:space:]]*//; s/[[:space:]]+$//"
|
|
}
|
|
|
|
case "${1:-}" in
|
|
get)
|
|
KEY="${2:?Usage: gstack-config get <key>}"
|
|
# Validate key (alphanumeric + underscore + optional @<endpoint-id> suffix for
|
|
# endpoint-namespaced keys introduced by the brain-aware planning layer).
|
|
# Endpoint ids are sha8/sha16 hex for remote MCP URLs, or the literal
|
|
# "local" for stdio/PGLite engines (see endpoint_hash).
|
|
if ! printf '%s' "$KEY" | LC_ALL=C grep -qE '^[a-zA-Z0-9_]+(@[a-zA-Z0-9]+)?$'; then
|
|
echo "Error: key must contain only alphanumeric characters, underscores, and an optional @<endpoint-id> suffix" >&2
|
|
exit 1
|
|
fi
|
|
VALUE=$(read_config_value "$KEY" || true)
|
|
if [ -z "$VALUE" ]; then
|
|
# lookup_default exits non-zero for a key it does not know. Propagate
|
|
# that, so the caller's `|| echo "<default>"` can fire. A known key whose
|
|
# default is empty still exits 0 and prints "".
|
|
if ! VALUE=$(lookup_default "$KEY"); then
|
|
exit 1
|
|
fi
|
|
fi
|
|
printf '%s' "$VALUE"
|
|
;;
|
|
has)
|
|
KEY="${2:?Usage: gstack-config has <key>}"
|
|
if ! printf '%s' "$KEY" | LC_ALL=C grep -qE '^[a-zA-Z0-9_]+(@[a-zA-Z0-9]+)?$'; then
|
|
echo "Error: key must contain only alphanumeric characters, underscores, and an optional @<endpoint-id> suffix" >&2
|
|
exit 1
|
|
fi
|
|
grep -qE "^${KEY}:" "$CONFIG_FILE" 2>/dev/null
|
|
;;
|
|
set)
|
|
KEY="${2:?Usage: gstack-config set <key> <value>}"
|
|
VALUE="${3:?Usage: gstack-config set <key> <value>}"
|
|
# Validate key (alphanumeric + underscore + optional @<endpoint-id> suffix).
|
|
# Accepts hex hashes and the literal "local" from endpoint_hash.
|
|
if ! printf '%s' "$KEY" | LC_ALL=C grep -qE '^[a-zA-Z0-9_]+(@[a-zA-Z0-9]+)?$'; then
|
|
echo "Error: key must contain only alphanumeric characters, underscores, and an optional @<endpoint-id> suffix" >&2
|
|
exit 1
|
|
fi
|
|
# Validate brain_trust_policy value domain (D4 / D11)
|
|
if printf '%s' "$KEY" | grep -qE '^brain_trust_policy(@|$)' && \
|
|
[ "$VALUE" != "personal" ] && [ "$VALUE" != "shared" ] && [ "$VALUE" != "unset" ]; then
|
|
echo "Warning: brain_trust_policy '$VALUE' not recognized. Valid values: personal, shared, unset. Using unset." >&2
|
|
VALUE="unset"
|
|
fi
|
|
# V1: whitelist values for keys with closed value domains. Unknown values warn + default.
|
|
if [ "$KEY" = "explain_level" ] && [ "$VALUE" != "default" ] && [ "$VALUE" != "terse" ]; then
|
|
echo "Warning: explain_level '$VALUE' not recognized. Valid values: default, terse. Using default." >&2
|
|
VALUE="default"
|
|
fi
|
|
if [ "$KEY" = "artifacts_sync_mode" ] && [ "$VALUE" != "off" ] && [ "$VALUE" != "artifacts-only" ] && [ "$VALUE" != "full" ]; then
|
|
echo "Warning: artifacts_sync_mode '$VALUE' not recognized. Valid values: off, artifacts-only, full. Using off." >&2
|
|
VALUE="off"
|
|
fi
|
|
# redact_repo_visibility: a LOCAL override for repos gh/glab can't read (e.g.
|
|
# self-hosted GitLab). It lives in ~/.gstack/config.yaml (never committed), so
|
|
# it can't be used to weaken the gate repo-wide for other contributors.
|
|
if [ "$KEY" = "redact_repo_visibility" ] && [ "$VALUE" != "public" ] && [ "$VALUE" != "private" ] && [ "$VALUE" != "unknown" ]; then
|
|
echo "Warning: redact_repo_visibility '$VALUE' not recognized. Valid values: public, private, unknown. Using unknown." >&2
|
|
VALUE="unknown"
|
|
fi
|
|
if [ "$KEY" = "redact_prepush_hook" ] && [ "$VALUE" != "true" ] && [ "$VALUE" != "false" ]; then
|
|
echo "Warning: redact_prepush_hook '$VALUE' not recognized. Valid values: true, false. Using false." >&2
|
|
VALUE="false"
|
|
fi
|
|
if [ "$KEY" = "pair_agent" ] && [ "$VALUE" != "on" ] && [ "$VALUE" != "off" ]; then
|
|
echo "Warning: pair_agent '$VALUE' not recognized. Valid values: on, off. Using off." >&2
|
|
VALUE="off"
|
|
fi
|
|
if [ "$KEY" = "founder_resources" ] && [ "$VALUE" != "true" ] && [ "$VALUE" != "false" ]; then
|
|
echo "Warning: founder_resources '$VALUE' not recognized. Valid values: true, false. Using true." >&2
|
|
VALUE="true"
|
|
fi
|
|
if [ "$KEY" = "plan_tune_hooks" ] && [ "$VALUE" != "prompt" ] && [ "$VALUE" != "yes" ] && [ "$VALUE" != "no" ]; then
|
|
echo "Warning: plan_tune_hooks '$VALUE' not recognized. Valid values: prompt, yes, no. Using prompt." >&2
|
|
VALUE="prompt"
|
|
fi
|
|
if [ "$KEY" = "timeline_stop_hook" ] && [ "$VALUE" != "yes" ] && [ "$VALUE" != "no" ]; then
|
|
echo "Warning: timeline_stop_hook '$VALUE' not recognized. Valid values: yes, no. Using yes." >&2
|
|
VALUE="yes"
|
|
fi
|
|
# codex_reviews controls PAID Codex calls. Unlike the warn-and-default keys above,
|
|
# an invalid value is REJECTED and the existing setting is left unchanged — a typo
|
|
# must never silently flip the switch and turn paid Codex calls on or off.
|
|
if [ "$KEY" = "codex_reviews" ] && [ "$VALUE" != "enabled" ] && [ "$VALUE" != "disabled" ]; then
|
|
echo "Error: codex_reviews '$VALUE' not recognized. Valid values: enabled, disabled. Existing value left unchanged." >&2
|
|
exit 1
|
|
fi
|
|
# cross_project_learnings: empty get is the first-run prompt sentinel.
|
|
# Skills enable only on the literal "true". A typo must not persist — that
|
|
# keeps the feature off and suppresses the prompt. Reject, like
|
|
# codex_reviews; do not coerce (a stored default still kills the sentinel).
|
|
if [ "$KEY" = "cross_project_learnings" ] && [ "$VALUE" != "true" ] && [ "$VALUE" != "false" ]; then
|
|
echo "Error: cross_project_learnings '$VALUE' not recognized. Valid values: true, false. Existing value left unchanged." >&2
|
|
exit 1
|
|
fi
|
|
# memorable_recall is a CONSENT key: `on` lets a Claude Code hook hand every
|
|
# prompt to a third-party binary. Reject like codex_reviews -- a typo must
|
|
# never flip consent in either direction, so nothing is coerced or stored.
|
|
if [ "$KEY" = "memorable_recall" ] && [ "$VALUE" != "on" ] && [ "$VALUE" != "off" ]; then
|
|
echo "Error: memorable_recall '$VALUE' not recognized. Valid values: on, off. Existing value left unchanged." >&2
|
|
exit 1
|
|
fi
|
|
mkdir -p "$STATE_DIR"
|
|
# Write annotated header on first creation
|
|
if [ ! -f "$CONFIG_FILE" ]; then
|
|
printf '%s' "$CONFIG_HEADER" > "$CONFIG_FILE"
|
|
fi
|
|
# Drop embedded newlines, then escape sed replacement metacharacters.
|
|
SAFE_VALUE="$(printf '%s' "$VALUE" | head -1)"
|
|
ESC_VALUE="$(printf '%s' "$SAFE_VALUE" | sed 's/[&/\]/\\&/g')"
|
|
if grep -qE "^${KEY}:" "$CONFIG_FILE" 2>/dev/null; then
|
|
# Portable in-place edit (BSD sed uses -i '', GNU sed uses -i without arg)
|
|
_tmpfile="$(mktemp "${CONFIG_FILE}.XXXXXX")"
|
|
sed "/^${KEY}:/s/.*/${KEY}: ${ESC_VALUE}/" "$CONFIG_FILE" > "$_tmpfile" && mv "$_tmpfile" "$CONFIG_FILE"
|
|
else
|
|
echo "${KEY}: ${SAFE_VALUE}" >> "$CONFIG_FILE"
|
|
fi
|
|
# Auto-relink skills when prefix setting changes (skip during setup to avoid recursive call)
|
|
if [ "$KEY" = "skill_prefix" ] && [ -z "${GSTACK_SETUP_RUNNING:-}" ]; then
|
|
GSTACK_RELINK="$(dirname "$0")/gstack-relink"
|
|
[ -x "$GSTACK_RELINK" ] && "$GSTACK_RELINK" || true
|
|
fi
|
|
;;
|
|
list)
|
|
if [ -f "$CONFIG_FILE" ]; then
|
|
cat "$CONFIG_FILE"
|
|
fi
|
|
echo ""
|
|
echo "# ─── Active values (including defaults for unset keys) ───"
|
|
for KEY in proactive routing_declined telemetry auto_upgrade update_check \
|
|
skill_prefix checkpoint_mode checkpoint_push explain_level \
|
|
codex_reviews gstack_contributor skip_eng_review workspace_root \
|
|
artifacts_sync_mode artifacts_sync_mode_prompted plan_tune_hooks \
|
|
timeline_stop_hook memorable_recall; do
|
|
VALUE=$(read_config_value "$KEY" || true)
|
|
SOURCE="default"
|
|
if [ -n "$VALUE" ]; then
|
|
SOURCE="set"
|
|
else
|
|
VALUE=$(lookup_default "$KEY")
|
|
fi
|
|
printf ' %-24s %s (%s)\n' "$KEY:" "$VALUE" "$SOURCE"
|
|
done
|
|
;;
|
|
defaults)
|
|
echo "# gstack-config defaults"
|
|
for KEY in proactive routing_declined telemetry auto_upgrade update_check \
|
|
skill_prefix checkpoint_mode checkpoint_push explain_level \
|
|
codex_reviews gstack_contributor skip_eng_review workspace_root \
|
|
artifacts_sync_mode artifacts_sync_mode_prompted plan_tune_hooks \
|
|
timeline_stop_hook memorable_recall; do
|
|
printf ' %-24s %s\n' "$KEY:" "$(lookup_default "$KEY")"
|
|
done
|
|
;;
|
|
endpoint-hash)
|
|
# Brain integration helper (T10): print active brain endpoint sha8
|
|
endpoint_hash_with_collision_check
|
|
;;
|
|
resolve-user-slug)
|
|
# Brain integration helper (T16 / D4 A3): resolve + persist user-slug
|
|
resolve_user_slug
|
|
;;
|
|
gbrain-refresh)
|
|
# Brain integration helper: re-detect gbrain installation state and
|
|
# persist to ~/.gstack/gbrain-detection.json. gen-skill-docs reads this
|
|
# file (when invoked with --respect-detection) to decide whether to
|
|
# render GBRAIN_CONTEXT_LOAD and GBRAIN_SAVE_RESULTS blocks in
|
|
# generated SKILL.md files.
|
|
#
|
|
# Run this after installing or uninstalling gbrain so your locally
|
|
# generated SKILL.md files match your installation state.
|
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
|
DETECT_BIN="$SCRIPT_DIR/gstack-gbrain-detect"
|
|
DETECTION_FILE="$STATE_DIR/gbrain-detection.json"
|
|
mkdir -p "$STATE_DIR"
|
|
if [ ! -x "$DETECT_BIN" ]; then
|
|
echo "gstack-gbrain-detect not found at $DETECT_BIN" >&2
|
|
exit 1
|
|
fi
|
|
if ! "$DETECT_BIN" > "$DETECTION_FILE.tmp" 2>/dev/null; then
|
|
printf '{"gbrain_on_path":false,"gbrain_local_status":"no-cli"}\n' > "$DETECTION_FILE.tmp"
|
|
fi
|
|
mv "$DETECTION_FILE.tmp" "$DETECTION_FILE"
|
|
|
|
# Summarize for the user. Use python (already required elsewhere) to
|
|
# parse the JSON portably; fall back to grep if python is unavailable.
|
|
PYTHON_CMD=$(command -v python3 || command -v python || true)
|
|
if [ -n "$PYTHON_CMD" ]; then
|
|
STATUS=$("$PYTHON_CMD" -c "import json,sys; d=json.load(open('$DETECTION_FILE')); print(d.get('gbrain_local_status','unknown'))" 2>/dev/null || echo unknown)
|
|
VERSION=$("$PYTHON_CMD" -c "import json,sys; d=json.load(open('$DETECTION_FILE')); print(d.get('gbrain_version') or 'unknown')" 2>/dev/null || echo unknown)
|
|
else
|
|
STATUS=$(grep -o '"gbrain_local_status":[[:space:]]*"[^"]*"' "$DETECTION_FILE" | sed 's/.*"\([^"]*\)"$/\1/')
|
|
VERSION=$(grep -o '"gbrain_version":[[:space:]]*"[^"]*"' "$DETECTION_FILE" | sed 's/.*"\([^"]*\)"$/\1/')
|
|
[ -z "$STATUS" ] && STATUS=unknown
|
|
[ -z "$VERSION" ] && VERSION=unknown
|
|
fi
|
|
|
|
case "$STATUS" in
|
|
ok|timeout|thin-client|engine-locked)
|
|
# "timeout" = slow-but-healthy engine (#1964); "thin-client" =
|
|
# remote-HTTP MCP brain, no local engine by design (#2051);
|
|
# "engine-locked" = same class (#2456): PGLite is single-writer, so a
|
|
# live `gbrain serve` (typically an MCP server) holds the embedded DB.
|
|
# gbrain is installed and healthy; a transient lock must not strip
|
|
# brain blocks out of every SKILL.md. All get the same treatment as
|
|
# "ok", matching gstack-gbrain-detect --is-ok and gen-skill-docs.
|
|
echo "Detected gbrain v$VERSION (local-status: $STATUS)."
|
|
# Render brain-aware blocks into an UNTRACKED out-dir (#2569) and
|
|
# repoint the installed skills at it — the old in-place render wrote
|
|
# into TRACKED files of the global install checkout, so the checkout
|
|
# stayed permanently dirty and every upgrade grew a redundant stash.
|
|
# Guards (never mutate an arbitrary directory): the install must
|
|
# exist, not be a symlink (a symlinked install points at a dev
|
|
# worktree — bin/dev-setup owns that flow), and look like a real
|
|
# gstack clone.
|
|
INSTALL_DIR="$HOME/.claude/skills/gstack"
|
|
RENDER_DIR="${GSTACK_USER_RENDER_DIR:-${GSTACK_HOME:-$HOME/.gstack}/render/claude}"
|
|
if [ ! -d "$INSTALL_DIR" ]; then
|
|
echo "No global install at $INSTALL_DIR — nothing to render. (Dev workspaces get blocks via bin/dev-setup.)"
|
|
elif [ -L "$INSTALL_DIR" ]; then
|
|
echo "Skip: $INSTALL_DIR is a symlink (likely a dev worktree). Run bin/dev-setup in that worktree instead."
|
|
elif [ ! -f "$INSTALL_DIR/VERSION" ] || [ ! -f "$INSTALL_DIR/package.json" ]; then
|
|
echo "Skip: $INSTALL_DIR doesn't look like a gstack clone (missing VERSION/package.json) — refusing to modify it."
|
|
elif ! command -v bun >/dev/null 2>&1; then
|
|
echo "Skip: bun not on PATH — can't render. Install bun, then re-run 'gstack-config gbrain-refresh'."
|
|
else
|
|
# Render into a tmp dir and swap it in only on SUCCESS. Installed
|
|
# skills SYMLINK into $RENDER_DIR (gstack-relink prefers it), so
|
|
# wiping it before the render meant one transient failure (bun
|
|
# error, disk full, broken template) left every brain-aware
|
|
# SKILL.md link dangling — the whole skill set vanished from
|
|
# Claude Code until a successful re-render. A failed render now
|
|
# leaves the previous render fully intact.
|
|
RENDER_TMP="$RENDER_DIR.tmp.$$"
|
|
rm -rf "$RENDER_TMP"
|
|
if ( cd "$INSTALL_DIR" && bun run gen:skill-docs:user --host claude --out-dir "$RENDER_TMP" --link-root "$RENDER_DIR" >/dev/null 2>&1 ); then
|
|
_swap_in_render "$RENDER_DIR" "$RENDER_TMP"
|
|
# Repoint installed skills at the render — gstack-relink prefers
|
|
# the render dir when present.
|
|
"$INSTALL_DIR/bin/gstack-relink" >/dev/null 2>&1 || true
|
|
echo "Rendered brain-aware blocks into $RENDER_DIR — now live across all your projects' Claude sessions."
|
|
echo "The install checkout stays clean: upgrades no longer stash generated render dirt (#2569)."
|
|
else
|
|
rm -rf "$RENDER_TMP"
|
|
echo "Warning: render failed — previous render (if any) left in place, links stay valid."
|
|
echo "Run 'cd $INSTALL_DIR && bun run gen:skill-docs:user --host claude --out-dir $RENDER_DIR' manually to see the error."
|
|
fi
|
|
fi
|
|
;;
|
|
*)
|
|
echo "gbrain not detected (local-status: $STATUS) → brain-aware blocks will be suppressed in planning-skill SKILL.md files."
|
|
echo "Install gbrain (see /setup-gbrain) and re-run 'gstack-config gbrain-refresh' once it's configured."
|
|
;;
|
|
esac
|
|
;;
|
|
*)
|
|
echo "Usage: gstack-config {get|set|list|defaults|endpoint-hash|resolve-user-slug|gbrain-refresh} [key] [value]"
|
|
exit 1
|
|
;;
|
|
esac
|