Files
gstack/bin/gstack-memorable
T
caba78fefa v1.83.0.0 feat: Memorable recall bridge, opt-in and receipted (supersedes #2831) (#2836)
* feat: add optional Memorable workflow memory

(cherry picked from commit 6bd5d477b2)

* 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 commit e0899afa8c)

* 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 commit 5c108cc0f7)

* 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>
2026-09-08 22:05:41 -07:00

412 lines
21 KiB
Bash
Executable File

#!/usr/bin/env bash
# gstack-memorable — enable | disable | status for the Memorable recall bridge
# (hosts/claude/hooks/memorable-user-prompt-hook, a Claude Code UserPromptSubmit
# hook that hands each prompt to the third-party `memorable` CLI under gstack's
# consent key, receipts and trust envelope).
#
# Two independent facts make up the bridge's state, and this CLI is the only
# writer of both:
#
# registration (settings.json) gate (config.yaml memorable_recall)
# NONE ──enable──▶ GSTACK ──┐ off ──enable──▶ on
# ▲ │ Claude Code strips ▲ │
# └──── disable ──────────┘ the tag: still └─── disable ────┘
# (identity) GSTACK by identity
# VENDOR-OWN: `memorable install-hooks` registered its own hook. enable
# refuses (two entries would run the hook twice per prompt).
# Mismatches are reported by `status`, never silently repaired:
# gate on + NONE -> "gate on, no hook" (enable to fix)
# gate off + GSTACK -> "hook is inert" (disable removes it)
#
# What each verb hands to the vendor binary: nothing. enable/disable/status
# never execute `memorable`; they only check that it exists. The vendor's
# own consent (`memorable enable` / `disable` / `forget`) is yours to run.
#
# Style: `set -uo pipefail` WITHOUT -e (like bin/gstack-verify-gate). Every
# external call is checked explicitly with `|| return N`, so a failure is
# reported where it happens and partial states are never reported as success.
#
# Exit codes: 0 ok · 1 refused / usage · 3 settings.json unparseable ·
# 4 unexpected settings shape · 5 could not acquire the lock
# (the hook manager's own codes, passed through).
# Heredoc delivery guard (see bin/gstack-settings-hook for the rationale).
BASH_COMPAT=50
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
GSTACK_CONFIG="$SCRIPT_DIR/gstack-config"
STATE_DIR="${GSTACK_STATE_ROOT:-${GSTACK_HOME:-${GSTACK_STATE_DIR:-$HOME/.gstack}}}"
SETTINGS_FILE="${GSTACK_SETTINGS_FILE:-${CLAUDE_CONFIG_DIR:-$HOME/.claude}/settings.json}"
HOOK_SOURCE="gstack-memorable"
CONFIG_KEY="memorable_recall"
SINK="memorable-recall"
HOOK_REL="hosts/claude/hooks/memorable-user-prompt-hook"
RESOLUTION_ORDER="GSTACK_MEMORABLE_BIN, MEMORABLE_BIN, ~/.memorable/bin/memorable, PATH"
# JavaScript RegExp (applied by gstack-settings-hook list-items to items no
# KNOWN_HOOKS row owns). Matches the vendor installer's own registration,
# verified against memorable-cli 0.5.18: "<HOME>/.memorable/bin/memorable" hook user-prompt
VENDOR_OWN_RE='[Mm]emorable.*hook\s+user-prompt'
# Canonical install root — the hook command MUST point at the stable install,
# never at the tree this CLI happens to run from (setup's phantom-hooks rule).
# Copied from setup:2481-2489; TODO D24 extracts a shared helper.
CANONICAL_GSTACK_ROOT="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills/gstack"
if [ ! -x "$CANONICAL_GSTACK_ROOT/bin/gstack-session-update" ] \
&& [ -x "$HOME/.claude/skills/gstack/bin/gstack-session-update" ]; then
CANONICAL_GSTACK_ROOT="$HOME/.claude/skills/gstack"
fi
HOOK_CMD_PATH="$CANONICAL_GSTACK_ROOT/$HOOK_REL"
# Mutations go through the CANONICAL hook manager so the code that registers
# is the code that will run. Every verb falls back to this tree's copy when the
# canonical one is missing (enable cannot get past compat_check then; disable
# and status must still work against a half-removed install).
SETTINGS_HOOK="$CANONICAL_GSTACK_ROOT/bin/gstack-settings-hook"
[ -x "$SETTINGS_HOOK" ] || SETTINGS_HOOK="$SCRIPT_DIR/gstack-settings-hook"
EGRESS_BIN="$CANONICAL_GSTACK_ROOT/bin/gstack-egress"
[ -x "$EGRESS_BIN" ] || EGRESS_BIN="$SCRIPT_DIR/gstack-egress"
# Platform detection copied from setup:76-79 (TODO D24). Windows support for
# this bridge is deferred whole (no process groups to contain the vendor).
IS_WINDOWS=0
case "${GSTACK_MEMORABLE_TEST_UNAME:-$(uname -s)}" in
MINGW*|MSYS*|CYGWIN*|Windows_NT) IS_WINDOWS=1 ;;
esac
usage() {
cat <<USAGE
Usage: gstack-memorable <enable|disable|status>
enable Register gstack's Memorable UserPromptSubmit hook (canonical path,
timeout 5) and set memorable_recall=on. Never runs \`memorable enable\`.
disable Set memorable_recall=off, remove gstack's hook entry (by identity,
tag or no tag), verify both. Never runs \`memorable disable\`.
status Read-only: vendor CLI, gate, registration, receipts, recent errors.
Vendor CLI resolution: $RESOLUTION_ORDER.
USAGE
}
_err() { printf 'gstack-memorable: %s\n' "$*" >&2; }
# ─── lock: one lifecycle transition at a time ────────────────────────────
LOCK_DIR="$STATE_DIR/locks/memorable-bridge.lock"
LOCK_STALE_S=30 # a holder older than this is a crashed writer
LOCK_TRIES=50 # x LOCK_SLEEP = the 5 s give-up
LOCK_SLEEP=0.1
LOCK_HELD=0
_lock_release() {
[ "$LOCK_HELD" -eq 1 ] || return 0
if [ "$(cat "$LOCK_DIR/owner" 2>/dev/null)" = "$$" ]; then rm -rf "$LOCK_DIR"; fi
LOCK_HELD=0
}
_lock_acquire() {
mkdir -p "$STATE_DIR/locks" 2>/dev/null || { _err "cannot create $STATE_DIR/locks (state directory not writable; nothing can be recorded there)"; return 5; }
local tries=0 mtime now stale judged moved owner_pid
while ! mkdir "$LOCK_DIR" 2>/dev/null; do
tries=$((tries + 1))
# Staleness from the directory's own mtime (set atomically by the holder's
# mkdir), never from a file written after it: a contender that looks in
# the gap between mkdir and bookkeeping must wait, not reclaim. GNU stat
# first, BSD stat second, garbage -> no takeover (same idiom as
# bin/gstack-settings-hook).
mtime="$(stat -c %Y "$LOCK_DIR" 2>/dev/null || stat -f %m "$LOCK_DIR" 2>/dev/null || echo "")"
case "$mtime" in *[!0-9]*|"") mtime="" ;; esac
now="$(date +%s)"
# A holder whose recorded pid is still alive is slow, not crashed: wait.
owner_pid="$(cat "$LOCK_DIR/owner" 2>/dev/null || echo "")"
case "$owner_pid" in *[!0-9]*|"") owner_pid="" ;; esac
if [ -n "$owner_pid" ] && kill -0 "$owner_pid" 2>/dev/null; then mtime=""; fi
if [ -n "$mtime" ] && [ $((now - mtime)) -gt "$LOCK_STALE_S" ]; then
# Atomic rename: exactly one contender reclaims a stale lock; the loser
# loops and re-contends against the winner's fresh mkdir. The inode
# check closes the gap between judging and renaming: a contender that
# judged the OLD directory stale must not carry off the FRESH one a
# faster contender just created in its place. A rename that fails
# (locks dir not writable by this user) falls through to the give-up
# counter below instead of spinning.
judged="$(stat -c %i "$LOCK_DIR" 2>/dev/null || stat -f %i "$LOCK_DIR" 2>/dev/null || echo "")"
stale="$LOCK_DIR.stale.$$-$RANDOM"
if mv "$LOCK_DIR" "$stale" 2>/dev/null; then
moved="$(stat -c %i "$stale" 2>/dev/null || stat -f %i "$stale" 2>/dev/null || echo "")"
if [ -n "$judged" ] && [ "$moved" = "$judged" ]; then
rm -rf "$stale" 2>/dev/null || true
else
# Not the directory we judged: a fresh holder's lock. Put it back.
mv "$stale" "$LOCK_DIR" 2>/dev/null || _err "lock bookkeeping: could not restore a fresh lock moved aside at $stale"
fi
continue
fi
fi
if [ "$tries" -ge "$LOCK_TRIES" ]; then _err "another gstack-memorable is running (lock $LOCK_DIR; stale but not reclaimable if older than ${LOCK_STALE_S}s); try again"; return 5; fi
sleep "$LOCK_SLEEP"
done
printf '%s\n' "$$" > "$LOCK_DIR/owner"
LOCK_HELD=1
trap _lock_release EXIT
}
# ─── probes (read-only) ──────────────────────────────────────────────────
resolve_memorable() {
local override="${GSTACK_MEMORABLE_BIN:-${MEMORABLE_BIN:-}}"
if [ -n "$override" ]; then
override="${override%\"}"; override="${override#\"}"
case "$override" in
/*) [ -f "$override" ] && [ -x "$override" ] && { printf '%s\n' "$override"; return 0; } ;;
*) command -v "$override" 2>/dev/null && return 0 ;;
esac
return 1 # an explicit override that does not resolve is an error, never a fall-through
fi
if [ -n "${HOME:-}" ] && [ -f "$HOME/.memorable/bin/memorable" ] && [ -x "$HOME/.memorable/bin/memorable" ]; then
printf '%s\n' "$HOME/.memorable/bin/memorable"; return 0
fi
command -v memorable 2>/dev/null
}
# Gate value or "unknown" (gstack-config missing/failed).
gate_value() {
local v
v="$("$GSTACK_CONFIG" get "$CONFIG_KEY" 2>/dev/null)" || { echo unknown; return 0; }
printf '%s\n' "${v:-off}"
}
# Registration state via the hook manager's identity view. Sets:
# REG_STATE none | gstack | vendor | both | unparseable | shape | unreadable
# REG_GSTACK newline-separated JSON string literals of gstack-owned commands
# REG_VENDOR newline-separated JSON string literals of the vendor's own commands
REG_STATE=""; REG_GSTACK=""; REG_VENDOR=""
registration_state() {
local rc
REG_GSTACK="$("$SETTINGS_HOOK" list-items --event UserPromptSubmit --owned-by "$HOOK_SOURCE" 2>/dev/null)"; rc=$?
case "$rc" in
0) ;;
3) REG_STATE="unparseable"; return 0 ;;
4) REG_STATE="shape"; return 0 ;;
*) REG_STATE="unreadable"; return 0 ;;
esac
REG_VENDOR="$("$SETTINGS_HOOK" list-items --event UserPromptSubmit --command-regex "$VENDOR_OWN_RE" 2>/dev/null)"; rc=$?
[ "$rc" -eq 0 ] || { REG_STATE="unreadable"; return 0; }
if [ -n "$REG_GSTACK" ] && [ -n "$REG_VENDOR" ]; then REG_STATE="both"
elif [ -n "$REG_GSTACK" ]; then REG_STATE="gstack"
elif [ -n "$REG_VENDOR" ]; then REG_STATE="vendor"
else REG_STATE="none"; fi
}
_reg_exit_code() {
case "$REG_STATE" in unparseable) echo 3 ;; shape) echo 4 ;; *) echo 1 ;; esac
}
_reg_problem_text() {
case "$REG_STATE" in
unparseable) echo "$SETTINGS_FILE is not valid JSON (fix or restore it; see gstack-settings-hook rollback)" ;;
shape) echo "$SETTINGS_FILE has an unexpected shape under hooks.UserPromptSubmit (not an array)" ;;
unreadable) echo "the hook manager could not read $SETTINGS_FILE" ;;
esac
}
# The canonical install must carry THIS bridge: a worktree CLI registering an
# older hook at the stable path would run code without the gate or receipts.
compat_check() {
[ -x "$HOOK_CMD_PATH" ] || { _err "no stable install carries the bridge hook at $HOOK_CMD_PATH; run ./setup (or /gstack-upgrade) first"; return 1; }
[ -f "$HOOK_CMD_PATH.ts" ] || { _err "the stable install at $CANONICAL_GSTACK_ROOT predates this bridge (no memorable-user-prompt-hook.ts); run ./setup first"; return 1; }
local here there
here="$(cat "$ROOT_DIR/VERSION" 2>/dev/null)"; there="$(cat "$CANONICAL_GSTACK_ROOT/VERSION" 2>/dev/null)"
if [ -n "$here" ] && [ "$here" != "$there" ]; then
_err "the stable install at $CANONICAL_GSTACK_ROOT is version '${there:-unknown}' but this tree is '$here'; run ./setup so the registered hook is the code that will run"
return 1
fi
# Captured, not piped: under pipefail the probe's own non-zero exit would
# mask a matching grep and let an old hook manager through.
local probe
probe="$("$SETTINGS_HOOK" list-items 2>&1)" || true
if printf '%s' "$probe" | grep -q "Unknown action"; then
_err "the stable install's hook manager does not know list-items; run ./setup first"; return 1
fi
return 0
}
# ─── enable ──────────────────────────────────────────────────────────────
enable_bridge() {
local vendor prior_gate ensure_out ensure_rc verb
_lock_acquire || return $?
[ -x "$SETTINGS_HOOK" ] || { _err "missing hook manager: $SETTINGS_HOOK"; return 1; }
[ -x "$GSTACK_CONFIG" ] || { _err "missing $GSTACK_CONFIG"; return 1; }
if [ "$IS_WINDOWS" -eq 1 ]; then
_err "Windows is not supported by the Memorable bridge yet (no way to contain the vendor process); tracked in TODOS.md: Windows support for the Memorable bridge (D21)"
return 1
fi
vendor="$(resolve_memorable)" || { _err "Memorable CLI not found (checked $RESOLUTION_ORDER). Install it yourself: npm i -g memorable-cli. gstack never installs it."; return 1; }
compat_check || return 1
prior_gate="$(gate_value)"
registration_state
case "$REG_STATE" in
unparseable|shape|unreadable) _err "cannot read the current registration: $(_reg_problem_text)"; return "$(_reg_exit_code)" ;;
vendor|both)
cat >&2 <<REFUSE
gstack-memorable: Memorable already registers this hook itself:
$(printf '%s\n' "$REG_VENDOR" | sed 's/^/ /')
Registering gstack's as well would run the hook twice on every prompt:
injected twice, and the session captured twice against your allowance.
Keep the one you have, or hand it to gstack: delete that entry from
$SETTINGS_FILE
and run this again. Memorable has no command that removes its own hook.
REFUSE
return 1 ;;
esac
ensure_out="$("$SETTINGS_HOOK" ensure-event --event UserPromptSubmit --command "$HOOK_CMD_PATH" --source "$HOOK_SOURCE" --timeout 5 2>&1)"; ensure_rc=$?
if [ "$ensure_rc" -ne 0 ]; then
_err "settings hook update failed: $(printf '%s\n' "$ensure_out" | head -1): run $SETTINGS_HOOK manually (nothing changed; the gate is still '$prior_gate')"
return "$ensure_rc"
fi
case "$ensure_out" in
*unchanged*) verb="unchanged" ;;
*re-pointed*) verb="re-pointed" ;;
*) verb="registered" ;;
esac
if ! "$GSTACK_CONFIG" set "$CONFIG_KEY" on >/dev/null 2>&1; then
# Restore the CAPTURED prior state, never an assumed one: a registration
# that predates this run stays; the gate goes back to what it was.
if [ "$verb" = "registered" ] && [ "$REG_STATE" = "none" ]; then
"$SETTINGS_HOOK" remove-source --source "$HOOK_SOURCE" >/dev/null 2>&1 || true
fi
case "$prior_gate" in on|off) "$GSTACK_CONFIG" set "$CONFIG_KEY" "$prior_gate" >/dev/null 2>&1 || true ;; esac
_err "could not record consent (gstack-config set $CONFIG_KEY on failed); a registration made by this run was removed, a pre-existing one was kept; gate is '$prior_gate'"
return 1
fi
cat <<DONE
gstack-memorable: enabled.
hook: $verb ($HOOK_CMD_PATH, timeout 5 s, source $HOOK_SOURCE)
consent: $CONFIG_KEY=on (gstack's gate; revoke: gstack-memorable disable)
vendor: $vendor
What gstack hands to that binary on every prompt: Claude Code's UserPromptSubmit
JSON (session_id, cwd, transcript_path, prompt), unless it carries a HIGH-tier
credential shape or the repo's trust policy is deny/read-only. The binary runs
with your privileges in an allowlisted environment and its own process group.
Each hand-off is receipted first: gstack-egress list --sink $SINK
What the binary then sends is Memorable's claim, not gstack's.
Claude Code picks up the new hook automatically within a few seconds; if it does
not fire, restart the session. Verify with: gstack-memorable status
Memorable's own capture consent is separate and yours to run or inspect:
memorable status | memorable enable | memorable disable | memorable forget
DONE
}
# ─── disable ─────────────────────────────────────────────────────────────
disable_bridge() {
local gate_rc=0 remove_rc=0 remove_out="" gate_after
_lock_acquire || return $?
# Gate first: the hook reads it on every prompt, so consent is revoked
# immediately even if the registration removal below fails. A missing
# gstack-config (half-removed install) is reported, and the removal still
# runs: the hook fails closed without gstack-config, the entry must still go.
if [ -x "$GSTACK_CONFIG" ]; then
"$GSTACK_CONFIG" set "$CONFIG_KEY" off >/dev/null 2>&1 || gate_rc=$?
else
_err "missing $GSTACK_CONFIG"; gate_rc=1
fi
if [ -x "$SETTINGS_HOOK" ]; then
remove_out="$("$SETTINGS_HOOK" remove-source --source "$HOOK_SOURCE" 2>&1)" || remove_rc=$?
else
_err "missing hook manager: $SETTINGS_HOOK"; remove_rc=1
fi
# Verify BOTH resulting states; report each, never a blended "done".
gate_after="$(gate_value)"
registration_state
local ok=0
if [ "$gate_rc" -eq 0 ] && [ "$gate_after" = "off" ]; then
echo "consent: $CONFIG_KEY=off"
else
_err "consent: could not set $CONFIG_KEY=off (gstack-config exit $gate_rc, value now '$gate_after')"; ok=1
fi
case "$REG_STATE" in
none|vendor)
if [ "$remove_rc" -eq 0 ]; then echo "hook: removed (${remove_out##*OK: })"
else echo "hook: no gstack entry remains (the hook manager exited $remove_rc: $(printf '%s\n' "$remove_out" | head -1))"; fi ;;
gstack|both)
_err "hook: a gstack-owned entry survived in $SETTINGS_FILE:"; printf '%s\n' "$REG_GSTACK" | sed 's/^/ /' >&2; ok=1 ;;
*) _err "hook: cannot verify removal: $(_reg_problem_text)"; ok=$(_reg_exit_code) ;;
esac
[ "$remove_rc" -eq 0 ] || { [ "$remove_rc" -ge 3 ] && ok=$remove_rc; }
if resolve_memorable >/dev/null 2>&1; then
echo "Memorable's own consent is unchanged; to stop or erase capture: memorable disable | memorable forget"
else
echo "Memorable CLI not found: nothing of the vendor's to revoke here (gstack's hook entry is gone)"
fi
echo "In-flight prompts that already passed the gate complete; the next prompt is off."
return "$ok"
}
# ─── status (read-only; never executes the vendor) ───────────────────────
status_bridge() {
local vendor gate n
if ! command -v bun >/dev/null 2>&1; then
echo "bun: missing (the hook manager and the hook itself need bun; install bun first)"
fi
if vendor="$(resolve_memorable)"; then
echo "Memorable CLI: available ($vendor); tested against the memorable-cli 0.5.18 hook contract"
else
echo "Memorable CLI: not found (checked $RESOLUTION_ORDER)"
fi
gate="$(gate_value)"
echo "memorable_recall: $gate"
registration_state
case "$REG_STATE" in
none) echo "Claude UserPromptSubmit hook: not registered" ;;
gstack) echo "Claude UserPromptSubmit hook: registered by gstack"; printf '%s\n' "$REG_GSTACK" | sed 's/^/ /' ;;
vendor) echo "Claude UserPromptSubmit hook: registered by Memorable itself"; printf '%s\n' "$REG_VENDOR" | sed 's/^/ /'
echo " gstack is not managing it; 'gstack-memorable enable' would refuse (it would double the hook)." ;;
both) echo "Claude UserPromptSubmit hook: registered by BOTH gstack and Memorable (the hook runs twice per prompt; remove one)"
printf '%s\n' "$REG_GSTACK" "$REG_VENDOR" | sed 's/^/ /' ;;
*) echo "Claude UserPromptSubmit hook: unknown ($(_reg_problem_text))" ;;
esac
if [ "$gate" = "on" ] && [ "$REG_STATE" = "none" ]; then echo "mismatch: gate on, no hook registered (run: gstack-memorable enable)"; fi
if [ "$gate" != "on" ] && { [ "$REG_STATE" = "gstack" ] || [ "$REG_STATE" = "both" ]; }; then echo "mismatch: hook registered but gate is '$gate' (hook is inert; run: gstack-memorable disable to remove it)"; fi
if [ "$IS_WINDOWS" -eq 1 ]; then echo "platform: Windows is not supported by this bridge yet (TODOS.md: Windows support for the Memorable bridge, D21)"; fi
if [ -x "$EGRESS_BIN" ] && command -v bun >/dev/null 2>&1; then
# Count the filtered array, not a formatting artefact of the pretty-printed
# JSON; a failed query is reported as unknown, never as an empty history.
local egress_json
if egress_json="$("$EGRESS_BIN" list --sink "$SINK" --json 2>/dev/null)"; then
n="$(printf '%s' "$egress_json" | bun -e 'const a=JSON.parse(require("fs").readFileSync(0,"utf8")||"[]");console.log(Array.isArray(a)?a.length:0)' 2>/dev/null)"
case "$n" in *[!0-9]*|"") n="unknown (could not parse gstack-egress output)" ;; esac
else
n="unknown (gstack-egress list failed; run it yourself)"
fi
echo "receipts: $n for sink $SINK (gstack-egress list --sink $SINK)"
# Same resolution as lib/egress-receipt.ts resolveEgressHome: GSTACK_HOME, GSTACK_STATE_DIR, ~/.gstack.
local ledger size
ledger="${GSTACK_HOME:-${GSTACK_STATE_DIR:-$HOME/.gstack}}/security/egress.jsonl"
if [ -f "$ledger" ]; then
size="$(wc -c < "$ledger" | tr -d ' ')"
if [ "${size:-0}" -gt 26214400 ]; then
echo "ledger: $ledger ($((size / 1048576)) MiB; above the 25 MiB warning, rotation is a filed TODO: this sink appends two lines per prompt)"
else
echo "ledger: $ledger ($(( (size + 1023) / 1024 )) KiB; this sink appends two lines per prompt)"
fi
fi
fi
if [ -f "$STATE_DIR/hook-errors.log" ]; then
n="$(grep -c 'memorable-user-prompt-hook' "$STATE_DIR/hook-errors.log" 2>/dev/null || true)"
if [ "${n:-0}" -gt 0 ]; then
echo "recent hook errors ($STATE_DIR/hook-errors.log):"
grep 'memorable-user-prompt-hook' "$STATE_DIR/hook-errors.log" | tail -3 | sed 's/^/ /'
fi
fi
return 0
}
case "${1:-}" in
enable) enable_bridge ;;
disable) disable_bridge ;;
status) status_bridge ;;
-h|--help|help) usage ;;
*) usage >&2; exit 1 ;;
esac