mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-05 19:07:12 +02:00
* refactor(resolvers): split review.ts into MECE resolver modules (pure move) Move every function from scripts/resolvers/review.ts, unchanged, into: - review-dashboard.ts: review dashboard, plan-file review report - plan-gates.ts: approval check, exit-plan-mode gate, plan-file discovery, plan-completion audit/gate (ship + review), plan verification exec - spec-review.ts: both spec review loops, benefits-from, anti-shortcut clause - outside-voice-steps.ts: Codex second opinion, adversarial step, Codex plan review, Codex doc review, disabled-outside record - review-scope.ts: scope drift, cross-review dedup, shared-code reuse review.ts is deleted; index.ts imports the new modules. gen-skill-docs output is byte-identical for every host (--host all). Test imports and source-path references are re-pointed; the two source-text report/gate tests in gen-skill-docs.test.ts become behavioral renders across every consuming skill and host. All 46 touchfile entries that named review.ts now name all five modules, guarded by a recorded selection golden. * test(browse): black-box auth matrix for every server route and both surfaces Drives buildFetchHandler fetchLocal/fetchTunnel with no token, wrong token, root token, scoped token and the SSE cookie for all 33 routes, plus unmatched paths and wrong methods. Denials assert today's exact status, body and content type; allowed credentials assert the handler was reached. Written against the unchanged if-chain server so the W3 route-table refactor must keep it green. * refactor(shard-engine): move scripts/test-strict-output.ts to scripts/lib/shard-engine.ts The shared shard engine grows from the existing strict-output module (runShardChild, killProcessGroup, signal forwarding, strict classifier). scripts/test-strict-output.ts stays as a re-export so existing importers, mock.module paths and the strict-output/run-shard-child tests are unchanged. The engine inherits the global touchfile entry; the free runner's CLI-routing fixture copies the new module. * refactor(resolvers): decompose the three >150-line review resolvers (output-neutral) Split generateAdversarialStep, generateCodexPlanReview and generatePlanCompletionAuditInner into per-section helpers whose template literals are copied verbatim, so every function in the new modules is at or under 150 lines. gen-skill-docs output is byte-identical for every host (--host all, compared against96764e80with a fixed --link-root). * refactor(resolvers): one outside-voice failure policy (deliberate prose unification) outsideVoiceFailurePolicy(ctx, opts) in outside-voice.ts now renders the auth / timeout / empty-response bullets for all four call sites that hand-typed them (Codex second opinion, adversarial step, Codex plan review, design outside voices). Options are explicit per site (timeoutMinutes, onTimeout, stderrOnEmpty, fallback, escape) with no defaults. Deliberate generated-prose changes (every host): - office-hours: 'Fall back to <native> subagent.' becomes 'Fall back to the <native> subagent below.' - plan-devex-review: the plain 'Auth failure (stderr contains ...)' bullets become the canonical bold bullets; auth also triggers on 'API key'; 'auth failed' becomes 'authentication failed'. - review/ship adversarial: 'exceeded 9 minutes and was terminated' becomes 'timed out after 9 minutes and was terminated'; the timeout is still MISSING COVERAGE. - design outside voices: unchanged. Adds ratchet (d) (test/outside-voice-failure-policy.test.ts) with a reasoned allowlist for /codex's own CLI errors, the MISSING COVERAGE retention test, refreshed codex/factory ship goldens, and outside-voice.ts in every touchfile entry of review.ts and design.ts (selection golden extended). * test(pty): fake PTY session driver with an injectable clock through the runner launch seam The three plan-skill runners take an optional PtyDriver (launch, now, monotonic, sleep); omitted, they use the real launcher and clocks exactly as before. test/helpers/pty/fake-session.ts feeds scripted frames through that seam, and claude-pty-runner.runners.unit.test.ts runs observation, counting and floor for success, deadline timeout, permission prompt and plan-ready outcomes with no CLI or real timers. These cases must stay green unchanged through the W4 split and the runPtySession extraction. Touchfiles: every entry that lists claude-pty-runner.ts or pty-screen.ts now also lists test/helpers/pty/**. * refactor(shard-engine): run both lanes on the shared engine; lane policy injected Engine (scripts/lib/shard-engine.ts) gains the W2 primitives: per-shard tmp/Chromium sandbox + async cleanup backstop, log-path allocation and full-stream log capture, one duration-seed reader/writer with a lane predicate, LanePolicy (seed predicate + zero-execution verdict), strictShardStatus, and the shared CLI flag loop. runShardChild takes an optional companion (signal/settle) and waits a bounded 250ms to reap a wall-killed child. Free lane stops spawning shards itself: runFreeShard uses runShardChild with trackShardBrowser as the companion (win32 path unchanged: no process group, no negative-pid kill). Its sync state-dir removal stays lane policy. Paid lane uses the sandbox, log, seed, verdict and flag primitives; the hollow-shard guard applies PAID_LANE_POLICY. Lane outcomes are unchanged (free keeps >= 0 seeds and file-count zero-exec rule; paid keeps > 0 seeds, warning under selection and passed-empty under EVALS_ALL). paid-free-boundary's closure assertion now names the engine module, where the strict classifier lives. * test(shard-engine): engine unit tests, fixture-corpus equivalence, per-lane CLI parity - test/shard-engine.test.ts: failing/unhandled/module-load output fails both lanes, per-lane zero-execution and seed rules, whole-group kill on a wall timeout (both lanes), mocked-win32 path with no negative-pid kill, companion settle order, log capture, sandbox isolation, flag loop. - test/shard-engine-equivalence.test.ts + test/fixtures/shard-equivalence: seven outcome fixtures plus one real shard, run through both lanes and compared with classifications recorded from the base runners (96764e80). - test/shard-cli-parity.test.ts + test/fixtures/shard-cli-parity: flag set, defaults, validation errors and the Unknown argument error per lane match the base runners. * refactor(shard-engine): decompose runFreeShard and runPaidShard to <= 150 lines Output-neutral extraction under the fixture-corpus equivalence and runner tests: captureFreeStream, explainFreeVerdict and logFreeRecovery (free); paidShardCommand, settleShardSpool, settleBootstrapRetention and printLogTail (paid). The bootstrap scope-creation block that bootstrap-retention.test.ts evaluates stays verbatim. * refactor(pty): split claude-pty-runner.ts into test/helpers/pty/* behind a barrel Pure move: every line of the former 5,047-line runner lands verbatim in one module (four private helpers gain `export` for cross-module use): binary, screen (absorbs test/helpers/pty-screen.ts, which now re-exports it), launch, session (PtyDriver), judge, classify, auq, plan-native, boundaries, runners/{observation,counting,floor}. claude-pty-runner.ts re-exports the original public surface by name; pty/ modules import siblings directly. Tests that read the runner's source text: - rewritten as behavioral: the unit test's model-pin tripwire (fake CLI argv: fallback chain, --model before extraArgs, hermetic --strict-mcp-config), pty-skill-seeding-wiring (runners through the fake driver; launcher through a fake CLI reporting CLAUDE_CONFIG_DIR). The "three wrappers forward model" grep is replaced by the runners' fake-driver launch assertions. - pty-screen-session / pty-screen-supervision: stop copying runner source; they mock.module the real pty/screen.ts (and the fixture cleanup) instead. - re-pointed to the owning module (they execute a sliced runner body with injected boundaries; no seam exists for those boundaries yet): eng-seeded-completion-ai, plan-floor-permission, plan-create-prepublication, plan-count-completion; hermetic-wiring's source guard now reads pty/launch.ts and scans every pty/ module for raw process.env spreads. - plan-count-timeout and pty-output-wake mock the viewport at pty/screen.ts. * test(ratchet-c): enforcing module/function size ratchet and moved-code touchfile coverage Ratchet (c) ships enforcing: test/helpers/module-size.ts counts file and top-level function lengths by brace matching over masked source (strings, comments, regex literals and template text masked; ${} expressions kept), covering function declarations, arrow functions assigned to consts and route-table handler properties, with no parser dependency. Its self-test uses template literals and code-fence braces copied from scripts/resolvers/review.ts and design.ts. test/fixtures/module-size-ratchet.json binds scripts/lib/shard-engine.ts (<= 800 lines, <= 150 per function) and records the residual runner sizes (free 2352, paid 1921) as non-growth caps; allowlist entries are keyed on file plus matched text and need a reason. Failure output lists file:line, the rule, Fix: and the allowlist path. touchfiles.test.ts gains the moved-code superset check over test/fixtures/touchfile-move-goldens/ (W2 golden recorded at96764e80: test-strict-output.ts and test-paid-shards.ts global, test-free-shards.ts none). * refactor(browse): declared route table replaces the buildFetchHandler if-chain The ~1,300-line if-chain in buildFetchHandler becomes a route table: each entry declares method, path, auth kind and surfaces, and one auth gate in browse/src/routes/table.ts returns the per-kind denial (root-bearer, scoped, root-or-sse-cookie: 401 Unauthorized; root-token: 403 Root token required; extension-origin: 403 Forbidden). Unmatched requests take the declared fallthrough (root-bearer check, then plain-text 404). Handlers move to browse/src/routes/{core,pairing,pty,tokens,tunnel,activity,commands,files, inspector}.ts and receive a RouteContext with auth checks as functions instead of closing over factory locals. Dispatch order is unchanged: tunnel filter, beforeRoute overlay, gate, handler. TUNNEL_PATHS stays a literal in server.ts. Behavior-preserving: the black-box auth matrix from the previous commit passes unchanged. /memory and /inspector/events are declared root-bearer because the blanket check always ran before their SSE-cookie branch. Source-text route tests are rewritten as behavioral tests through buildFetchHandler or a route's real handler with a stub RouteContext (browse/test/route-test-harness.ts). Checks with no runtime seam are re-pointed to the route modules: Surface type, /inspector/events SSE helper, sanitizeReplacer imports, /pty-inject-scan sidecar-client import, and the ngrok config lookup and startTunnel wiring that stay in server.ts. * test(browse): stubbed-handler auth matrix and route inventory for the route table Every ROUTES entry runs through the real dispatcher and gate with stub handlers on each declared surface and six credentials; denials assert the exact status and body each auth kind returned at96764e8, admitted credentials assert the handler ran (with the gate's TokenInfo for scoped routes). Also pins the reviewed route inventory (method, path, auth kind, surfaces), that every entry declares auth and surfaces, that the table's tunnel paths equal the TUNNEL_PATHS literal with GET /connect admitted, the unmatched fallthrough, and that the root token is rejected on every tunnel route through buildFetchHandler. * test(browse): ratchet (b) keeps route dispatch inside the route table Scans browse/src/server.ts and browse/src/routes/*.ts for pathname comparisons; only the table matcher and the tunnel-surface filter are allowed, listed with reasons in browse/test/fixtures/route-dispatch-allowlist.json (keyed on file plus line text). Also checks every entry declares auth and surfaces and that gstack registers no beforeRoute overlay itself. Self-tests plant a violation and assert the file:line, Fix: and allowlist path in the message, that a shifted line stays allowlisted, and that a reasonless entry is rejected. * test: touchfile superset check for modules moved out of browse/src/server.ts Records the paid evals selected by touching browse/src/server.ts at96764e80(17 E2E, 1 LLM judge) and asserts every browse/src/routes/*.ts module selects a superset. The test reads every golden in test/fixtures/moved-module-selection/ so other moved-code goldens can sit beside it. * test(shard-engine): give non-timeout corpus fixtures CI headroom; keep the POSIX golden off the Windows lane Only the wall-timeout fixture keeps a 3s wall; the rest get 60s so a loaded host cannot turn a pass into a timeout. Base and branch runners still agree on every classification under the new walls. The Windows exclusion entry moves the free runner's ratchet (c) residual cap to 2356 lines. * refactor(pty): one runPtySession loop drives observation, counting and floor test/helpers/pty/session.ts owns launch -> start -> (poll -> tick)* -> timeout and the failure contract the three runners each hand-rolled: the run's own error wins over capture and close errors, close always runs, owned fixture cleanup runs last (also when launch fails). Each runner now supplies a PtySessionPlan: its boot/command step, poll cadence (2s observation/floor sleep; counting's output wake + 250ms coalesce), tick policy (permission handling, native identity, terminal rules stay per runner because they differ) and capture hooks. The runner bodies are decomposed into top-level steps so no function exceeds 150 lines; behavior is unchanged and the fake-driver cases from the first W4 commit pass unmodified. The counting capture step and the native completion-summary predicate are now named functions (countingCapture, isNativeCompletionSummary), so plan-create-prepublication and plan-count-completion call them directly instead of executing sliced source. The two harnesses that still execute a sliced runner body with injected boundaries (eng-seeded-completion-ai, plan-floor-permission) pass the PtyDriver seam instead of overriding Date/Bun.sleep. * test(ratchet-c): register route modules, review resolver modules and server.ts residual cap * refactor(pty): decompose launchClaudePty and engNumberedFindingAUQ under 150 lines launchClaudePty (349 lines) becomes launch preparation (args, hermetic child env, owned state roots), recorder creation, spawn, the trust-dialog watcher, close, and the session handle over one PtyProcess state object. The failure order is unchanged: abort the viewport, dispose any recorders created so far, dispose the viewport, rethrow. The --model / --strict-mcp-config ordering and seedSkills wiring stay pinned by the behavioral fake-CLI tests. engNumberedFindingAUQ (345 lines) keeps its guards and dispatch; each self-contained issue family (declared cache, library retry hooks, cache owner, injected singleton, shared writers, injected export) moves verbatim into its own function. Every pty/ module is now <= 800 lines and every top-level function <= 150 lines. * test(pty): split claude-pty-runner.unit.test.ts along the pty/ module seams The 188 unit tests move verbatim into claude-pty-runner.{screen,classify, auq,launch,plan-native,boundaries}.unit.test.ts (test names unchanged; each file imports only what it uses from the barrel). The five files that no longer read a SKILL.md template join the test-of-test ratchet baseline with a reason. * test(touchfiles): moved PTY modules keep their paid-eval selection test/fixtures/touchfile-selection/w4-pty.json records, at96764e8, the paid evals selected by touching test/helpers/claude-pty-runner.ts (20) and test/helpers/pty-screen.ts (20). touchfiles.test.ts now asserts every .ts file under test/helpers/pty/ (and pty/screen.ts for both sources) selects a superset, reading every golden in that directory so later moves can add one; a planted-violation case pins the report and its Fix line. * fix(browse): unexchanged pair setup keys no longer authenticate bearer requests validateToken accepted a gsk_setup_ key as a bearer on /command, /batch and /file (found while building the W3 auth matrix). A setup key now only authenticates the /connect exchange. * W1: one state-root owner (lib/state-root.ts + bin/gstack-state-root.sh), gstack-paths --explain and fail-stop, parity tests * W1: guarded migration of every executable state-root site; uninstall deletes only ~/.gstack Bins, careful/freeze hooks, setup, upgrade migrations, browse/src, design, ios-qa daemon, lib and scripts resolve the state root through bin/gstack-state-root.sh (bash) or lib/state-root.ts (TS). Bins source the twin and stop with a reinstall message when it is missing; hooks source it and never spawn gstack-paths. browse/src/config.ts and lib/cso/state.ts delegate to resolveStateRoot. Analytics writers and readers move together so the usage log stays one file. gstack-uninstall deletes state only at ~/.gstack, refuses (exit 2) when it resolves to /, $HOME or an ancestor, the checkout or the git root, and leaves any other resolved root in place with the removal command. Fixtures that copy single bins now copy the twin. * W1: privacy keys and trust-policy deny tiers merge across state roots; gstack-config reporting; test hermeticity readConfigKey / gstack_read_config_key return the most restrictive telemetry, memorable_recall, codex_reviews and update_check across the resolved root and ~/.gstack; other keys read the resolved root only. gstack-config set reports an overriding root with the exact override command, list shows the winning root and a root-variable disagreement line. gstack-gbrain-repo-policy get merges deny/read-only tiers. gstack-egress reads through readConfigKey. test-setup.ts strips inherited GSTACK_STATE_ROOT/GSTACK_STATE_DIR and redirects the legacy root. * W1: shared hook logging helper (hosts/claude/hooks/hook-log.ts) One hook-errors.log writer: root from resolveStateRoot, 0600 on every append, opt-in rate limit used only by memorable-user-prompt. The five hooks route through it. * W1: docs/state-root.md and README troubleshooting pointer Precedence table, a real --explain example, the move-your-state recipe, merged privacy keys, the uninstall rule, the resolver-failure fix, and the plugin-mode note (evidence gate: no official plugin distribution). * W1b: template and resolver prose resolve state through guarded gstack-paths; ratchet (a) Every gstack-paths eval in templates and resolvers carries the fail-stop guard; executable ~/.gstack paths in bash blocks (context recovery preamble, eureka log, analytics, project artifacts, upgrade snooze, setup-gbrain lock, retro snapshots, ship consent marker) use $GSTACK_STATE_ROOT, and the writer prose that pairs with them points at the printed PROJECT_DIR / RETRO_FILE. ship drops export GSTACK_STATE_ROOT. SKILL.md regenerated (claude + codex), ship goldens re-pinned, parity and context-budget caps raised to the measured sizes with notes. test/state-root-ratchet.test.ts enforces the rule with a reasoned allowlist; W1 touchfile entries plus a superset golden. * refactor: apply W1 state-root edits in W2/W3/W5-owned files; one moved-code touchfile golden for all workstreams * test: fold the moved-code touchfile golden into touchfiles.test.ts; fix integration fixture closure and caps * v1.91.11.0: CHANGELOG, TODOS, docs and conventions for the refactor wave * test: re-measure plan-ceo/design-consultation caps and ship goldens after the guarded plan-discovery and spec-review blocks; add the state-root twin to the workflow-boundaries fixture * fix(windows): migrations resolve their directory with either path separator; state-root parity compares under the HOME Git Bash actually sees * fix(review,ship): state plan-check timing after smoke expiry and test_stub Skip semantics (review workflow judge clarity) * test(qa-eval): webhook fix eval asks for the fix loop's post-repair probes; eight-scenario coverage stays in the report-only case and the harness recheck * test(qa-eval): re-pin the webhook prompt contract to the fix-loop stage; R29 coverage omissions stay bound by the report-only case * fix(review,ship): plan checks publish a checkpoint before each probe; only the smoke expiry stop is skipped * fix(qa): carry #2999's checkpoint receipt link, report-template line and full-revision placeholder (identical hunks) * test(qa-callers): disable git auto maintenance in the caller fixture Git 2.47+ runs auto maintenance detached after commit; on the CI runner's git 2.55 it rewrote .git/objects fan-out directories while the write observer was running, which surfaced as unauthorized mutations. Same gc.auto=0 / maintenance.auto=false guard the shared-libs fixture already uses. * test(plan-mode-no-op): require prose evidence for the prose-fallback members so a spinner-frame judge verdict cannot end the run as asked * test(ship-docsync): carry #2999's seeded-attempt docsync harness (identical files) The doc-sync fault cases replayed attempt 1 before reaching their gate and ran out of their 285s budget. The fixture now seeds attempt 1 and the parent starts at the gate under test. Taken byte-identical from origin/capy/audit-fix-wave (fb526898,e6ac813d,6ce10ff7,d0c53577,77cce3be). Local: stale-before, recovery and late-result 6/6 PASS (97-164s); the whole file 12/12 PASS.
566 lines
27 KiB
TypeScript
566 lines
27 KiB
TypeScript
#!/usr/bin/env bun
|
|
/**
|
|
* memorable-user-prompt-hook — gstack-mediated bridge from Claude Code's
|
|
* UserPromptSubmit event to the third-party `memorable` CLI (memorable.sh).
|
|
*
|
|
* The vendor's own installer registers `memorable hook user-prompt` directly.
|
|
* Registering it THROUGH gstack instead buys the user what gstack gives every
|
|
* other off-machine sink: an explicit consent key, a receipt per attempted
|
|
* send, a secret pre-scan, a trust envelope around what comes back, healing
|
|
* and clean removal. This file is that mediation.
|
|
*
|
|
* stdin JSON -> cap 1 MiB -> parse -> MEMORABLE=0? -> gate memorable_recall == on?
|
|
* -> win32? -> trust policy (deny / read-only veto, by session cwd; fail-closed)
|
|
* -> HIGH-tier secret scan (raw bytes AND decoded string leaves, each admitted by the clock)
|
|
* -> resolve vendor -> budget >= 500 ms? -> gate re-check
|
|
* -> receipt (fail-closed: no receipt, no send)
|
|
* -> VENDOR SPAWN (own process group, allowlisted env, group-killed on timeout)
|
|
* -> parse vendor JSON -> additionalContext only -> control-strip
|
|
* -> 8 KiB cap (UTF-8 boundary) -> trust envelope -> stdout (awaited)
|
|
* -> outcome (bounded by the same clock) -> exit 0
|
|
* every REFUSAL above is: one rate-limited line in hook-errors.log, empty stdout, exit 0
|
|
* (gate off, MEMORABLE=0, empty or non-object stdin are silent: nothing was refused).
|
|
*
|
|
* CONTRACT
|
|
* - ALWAYS exits 0 with either one hookSpecificOutput JSON or nothing. The
|
|
* vendor can never block a prompt or speak as gstack: only a string
|
|
* `hookSpecificOutput.additionalContext` is accepted from its output.
|
|
* - One deadline clock (BUDGET_MS) undercuts Claude Code's 5 s hook kill;
|
|
* every stage, the two ledger writes and the secret scans included, gets
|
|
* min(cap, remaining). A receipt with no outcome means the host killed us
|
|
* or the clock ran out (reported as `unknown`), never success.
|
|
* - Fail-closed on the receipt: if the ledger cannot be written, recall is
|
|
* skipped for that prompt. What the receipt attests is the bytes handed to
|
|
* a LOCAL binary running with the user's privileges (host `local:<path>`);
|
|
* what that binary sends is the vendor's claim.
|
|
* - The vendor sees an allowlisted environment (PATH, HOME, locale, TMP,
|
|
* the standard proxy/TLS/XDG variables, MEMORABLE*), never Claude Code's
|
|
* full env (which can carry API keys).
|
|
* - The vendor's stderr reaches hook-errors.log only when the redaction
|
|
* engine finds no HIGH- or MEDIUM-tier shape in it (a CLI that echoes its
|
|
* input on a parse error would otherwise copy the prompt into the log).
|
|
* The log is chmod 0600 on every append (sibling hooks share the file).
|
|
* - If the host terminates the hook mid-flight (SIGTERM/SIGINT/SIGHUP,
|
|
* forwarded by the bash shim), the vendor's process group is killed on
|
|
* the way out; the receipt then stands with outcome `unknown`.
|
|
* - Windows is refused here (no process groups to contain the vendor);
|
|
* bin/gstack-memorable enable refuses there too. TODOS.md: Windows support (D21).
|
|
*
|
|
* Pure helpers are exported for unit tests; main() runs only under import.meta.main.
|
|
*/
|
|
import * as fs from 'fs';
|
|
import * as os from 'os';
|
|
import * as path from 'path';
|
|
import { runBin, runExternal } from './spawn-bin';
|
|
import {
|
|
LEDGER_WARN_BYTES, egressLedgerPath, ledgerSizeWarning, resolveEgressHome, sha256Hex, writeOutcome, writeReceipt,
|
|
} from '../../../lib/egress-receipt';
|
|
import { wrapUntrustedTrackerContent } from '../../../lib/tracker-guard';
|
|
import { scan } from '../../../lib/redact-engine';
|
|
import { hasRepoPolicyStore, repoPolicyTier } from '../../../lib/gbrain-repo-policy-client';
|
|
import { LOG_RATE_LIMIT_MS, logHookError as sharedLogHookError } from './hook-log';
|
|
|
|
export { LOG_RATE_LIMIT_MS };
|
|
|
|
export const BUDGET_MS = 4500;
|
|
export const STDIN_CAP_BYTES = 1024 * 1024;
|
|
export const OUTPUT_CAP_BYTES = 8192;
|
|
/** Left on the clock for post-processing, the stdout write and one ledger append after the vendor. */
|
|
export const RESERVE_MS = 300;
|
|
/** Below this many ms left before the spawn, the vendor is not started at all. */
|
|
export const MIN_SPAWN_MS = 500;
|
|
/** Cap for each pre-spawn subprocess stage (stdin read, gate, git, policy); always min(cap, remaining). */
|
|
export const STAGE_CAP_MS = 1000;
|
|
/** Cap for the pre-spawn gate re-check. */
|
|
export const RECHECK_CAP_MS = 500;
|
|
/** Below this many ms left, the outcome append is skipped (the receipt stands, outcome reads as unknown). */
|
|
export const OUTCOME_MIN_MS = 80;
|
|
/** Kept back from the clock when an outcome append is given the rest of it. */
|
|
export const OUTCOME_RESERVE_MS = 50;
|
|
export const ENVELOPE_SOURCE = 'memorable recall (third-party)';
|
|
export const SINK = 'memorable-recall';
|
|
export const CONSENT = 'memorable_recall=on';
|
|
export const RESOLUTION_ORDER = 'GSTACK_MEMORABLE_BIN, MEMORABLE_BIN, ~/.memorable/bin/memorable, PATH';
|
|
/** Receipt payload class: a stable token (the prose lives in docs/memorable-workflow-memory.md), so a per-prompt sink does not repeat a sentence per line. */
|
|
export const PAYLOAD_CLASS = 'claude-user-prompt-json->local-vendor-cli';
|
|
const HOOK_NAME = 'memorable-user-prompt-hook';
|
|
/** Per-KiB allowance added to the scan admission check: ~1.5x the measured worst case of scan(). */
|
|
const SCAN_MS_PER_KIB = 1;
|
|
/** Candidate objects tried by the tolerant stdout parser before giving up (bounds a hostile brace soup). */
|
|
const JSON_CANDIDATES = 64;
|
|
const GIT_MAX_BUFFER = 64 * 1024;
|
|
const TRUNCATION_MARKER = `[truncated by gstack at ${OUTPUT_CAP_BYTES / 1024} KiB]`;
|
|
|
|
/** Milliseconds left on a deadline that started at startMs. Pure; unit-tested. */
|
|
export function budgetFor(startMs: number, nowMs: number, cap: number = BUDGET_MS): number {
|
|
return Math.max(0, startMs + cap - nowMs);
|
|
}
|
|
|
|
/** The deadline: BUDGET_MS, or a test-only override that can only shorten it. */
|
|
export function budgetMs(env: Record<string, string | undefined> = process.env): number {
|
|
const raw = env.GSTACK_MEMORABLE_TEST_BUDGET_MS;
|
|
const n = raw ? Number(raw) : NaN;
|
|
return Number.isFinite(n) && n > 0 ? Math.min(n, BUDGET_MS) : BUDGET_MS;
|
|
}
|
|
|
|
/** Truncate to maxBytes of UTF-8 without splitting a multibyte character. */
|
|
export function capUtf8(text: string, maxBytes: number): { text: string; truncated: boolean } {
|
|
const buf = Buffer.from(text, 'utf8');
|
|
if (buf.length <= maxBytes) return { text, truncated: false };
|
|
let end = maxBytes;
|
|
while (end > 0 && (buf[end] & 0xc0) === 0x80) end--; // back off to a UTF-8 boundary
|
|
return { text: buf.subarray(0, end).toString('utf8'), truncated: true };
|
|
}
|
|
|
|
// C0 controls minus tab (9) and newline (10), plus DEL. Carriage return (13)
|
|
// is stripped too: a CR can visually overwrite earlier text in a rendering of
|
|
// the injected context while staying one line for the envelope. Built from
|
|
// char codes so the source file itself carries no control bytes.
|
|
const cc = (n: number): string => String.fromCharCode(n);
|
|
const CONTROL_RE = new RegExp(`[${cc(0)}-${cc(8)}${cc(11)}-${cc(31)}${cc(127)}]`, 'g');
|
|
// Unicode format characters (bidi overrides, zero-width spaces, soft hyphens)
|
|
// hide text from a reader while the model still sees it; the envelope detects
|
|
// them but emits the original, so this sink strips them at egress. The
|
|
// zero-width joiner stays: emoji sequences need it.
|
|
const FORMAT_RE = /(?!\u200D)\p{Cf}/gu;
|
|
|
|
/** Strip control and format characters except newline, tab and ZWJ (the envelope handles the rest). */
|
|
export function stripControl(text: string): string {
|
|
return text.replace(CONTROL_RE, '').replace(FORMAT_RE, '');
|
|
}
|
|
|
|
/**
|
|
* Every string leaf of a parsed JSON value, bounded so a hostile payload
|
|
* cannot monopolize the clock. `exhausted` is true when the bound cut the
|
|
* walk short: the caller must then treat the payload as unscanned (and refuse
|
|
* the hand-off), never as clean.
|
|
*/
|
|
export function stringLeavesBounded(value: unknown, maxNodes = 10_000, maxDepth = 32): { leaves: string[]; exhausted: boolean } {
|
|
const leaves: string[] = [];
|
|
let nodes = 0;
|
|
let exhausted = false;
|
|
const walk = (v: unknown, depth: number): void => {
|
|
if (nodes++ > maxNodes || depth > maxDepth) { exhausted = true; return; }
|
|
if (typeof v === 'string') { leaves.push(v); return; }
|
|
if (Array.isArray(v)) { for (const item of v) walk(item, depth + 1); return; }
|
|
if (v && typeof v === 'object') {
|
|
// keys are forwarded bytes too; a credential can sit in one
|
|
for (const [k, item] of Object.entries(v as Record<string, unknown>)) { leaves.push(k); walk(item, depth + 1); }
|
|
}
|
|
};
|
|
walk(value, 0);
|
|
return { leaves, exhausted };
|
|
}
|
|
|
|
/** The leaves alone (see stringLeavesBounded). */
|
|
export function stringLeaves(value: unknown, maxNodes = 10_000, maxDepth = 32): string[] {
|
|
return stringLeavesBounded(value, maxNodes, maxDepth).leaves;
|
|
}
|
|
|
|
// Identity, locale and temp; the standard proxy, TLS and XDG knobs the vendor
|
|
// needs to reach its own service through the user's proxy or private CA (it
|
|
// already gets them from the user's shell); plus MEMORABLE* (its own knobs,
|
|
// matched by prefix below). Never API keys, never GSTACK_* or CLAUDE_*.
|
|
const ENV_ALLOW = new Set([
|
|
'PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'LANG', 'TERM', 'TMPDIR', 'TEMP', 'TMP',
|
|
'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'no_proxy',
|
|
'SSL_CERT_FILE', 'SSL_CERT_DIR', 'NODE_EXTRA_CA_CERTS',
|
|
'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME', 'XDG_STATE_HOME',
|
|
]);
|
|
|
|
/** The vendor's environment: an allowlist, never Claude Code's full env. */
|
|
export function vendorEnv(env: Record<string, string | undefined>): Record<string, string> {
|
|
const out: Record<string, string> = {};
|
|
for (const [k, v] of Object.entries(env)) {
|
|
if (v == null) continue;
|
|
if (ENV_ALLOW.has(k) || k.startsWith('LC_') || k.startsWith('MEMORABLE')) out[k] = v;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** Index of the `}` closing the object that opens at `start`, or -1 when it never closes. */
|
|
function balancedObjectEnd(raw: string, start: number): number {
|
|
let depth = 0;
|
|
let inString = false;
|
|
let escaped = false;
|
|
for (let i = start; i < raw.length; i++) {
|
|
const ch = raw[i];
|
|
if (inString) {
|
|
if (escaped) escaped = false;
|
|
else if (ch === '\\') escaped = true;
|
|
else if (ch === '"') inString = false;
|
|
continue;
|
|
}
|
|
if (ch === '"') inString = true;
|
|
else if (ch === '{') depth++;
|
|
else if (ch === '}' && --depth === 0) return i;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
/**
|
|
* Every complete top-level JSON object in `raw`, in order (at most
|
|
* JSON_CANDIDATES attempts). A vendor whose background helper logs a line to
|
|
* the inherited stdout after the answer, or prints a banner before it (even
|
|
* one with braces in it), must not cost the user the answer. Whole-input JSON
|
|
* is the normal case and is yielded alone.
|
|
*/
|
|
export function* jsonObjects(raw: string): Generator<unknown> {
|
|
try { yield JSON.parse(raw); return; } catch { /* fall through to the scan */ }
|
|
let start = raw.indexOf('{');
|
|
for (let tries = 0; start >= 0 && tries < JSON_CANDIDATES; tries++) {
|
|
const end = balancedObjectEnd(raw, start);
|
|
let parsed: unknown;
|
|
let ok = false;
|
|
// An unbalanced candidate (a lone brace in a banner) is skipped like an
|
|
// unparsable one: the complete object after it must still be found.
|
|
if (end >= 0) { try { parsed = JSON.parse(raw.slice(start, end + 1)); ok = true; } catch { /* a brace in prose */ } }
|
|
if (ok) { yield parsed; start = raw.indexOf('{', end + 1); }
|
|
else start = raw.indexOf('{', start + 1);
|
|
}
|
|
}
|
|
|
|
/** The first complete top-level JSON object in `raw`, or null. */
|
|
export function firstJsonObject(raw: string): unknown {
|
|
for (const obj of jsonObjects(raw)) return obj;
|
|
return null;
|
|
}
|
|
|
|
/** Only a string hookSpecificOutput.additionalContext survives; decision/continue/systemMessage are dropped. */
|
|
export function pickAdditionalContext(raw: string): string | null {
|
|
for (const parsed of jsonObjects(raw)) {
|
|
const hso = (parsed as { hookSpecificOutput?: { additionalContext?: unknown } } | null)?.hookSpecificOutput;
|
|
const ctx = hso?.additionalContext;
|
|
if (typeof ctx === 'string' && ctx.length > 0) return ctx;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** Cap + envelope: the text Claude will see. */
|
|
export function renderContext(vendorText: string): string {
|
|
const { text, truncated } = capUtf8(stripControl(vendorText), OUTPUT_CAP_BYTES);
|
|
const body = truncated ? `${text}\n${TRUNCATION_MARKER}` : text;
|
|
return wrapUntrustedTrackerContent(body, ENVELOPE_SOURCE);
|
|
}
|
|
|
|
/**
|
|
* The vendor's stderr tail as it may appear in hook-errors.log: control-stripped,
|
|
* whitespace-collapsed, last 300 chars, and WITHHELD when the redaction engine
|
|
* finds a HIGH or MEDIUM shape in it (a CLI that echoes its input on a parse
|
|
* error would otherwise copy prompt text into a log the pre-scan only cleared
|
|
* of HIGH-tier shapes).
|
|
*/
|
|
export function safeStderrTail(tail: string): string {
|
|
// Scan everything runExternal kept, THEN crop for the log: cropping first
|
|
// could cut a credential's identifying prefix off and log its secret half.
|
|
const whole = stripControl(tail).replace(/\s+/g, ' ').trim();
|
|
if (!whole) return '';
|
|
const r = scan(whole, { repoVisibility: 'unknown' });
|
|
const n = r.counts.HIGH + r.counts.MEDIUM;
|
|
return r.oversize || n > 0 ? `[stderr withheld: ${n} redaction finding(s)]` : whole.slice(-300);
|
|
}
|
|
|
|
function stripQuotes(v: string): string {
|
|
return v.trim().replace(/^"(.*)"$/, '$1');
|
|
}
|
|
|
|
function executable(p: string): boolean {
|
|
try {
|
|
const st = fs.statSync(p);
|
|
if (!st.isFile()) return false;
|
|
if (process.platform !== 'win32') fs.accessSync(p, fs.constants.X_OK);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function isDirectory(p: string): boolean {
|
|
try { return fs.statSync(p).isDirectory(); } catch { return false; }
|
|
}
|
|
|
|
/**
|
|
* GSTACK_MEMORABLE_BIN -> MEMORABLE_BIN -> ~/.memorable/bin/memorable -> PATH.
|
|
* An explicit override that does not resolve is an error (null), never a
|
|
* fall-through to something else (lib/claude-bin.ts contract).
|
|
*/
|
|
export function resolveVendor(env: Record<string, string | undefined>, homeDir: string): string | null {
|
|
// Empty means unset, exactly as bash's ${GSTACK_MEMORABLE_BIN:-${MEMORABLE_BIN:-}} reads it
|
|
// in bin/gstack-memorable: the binary enable checked is the binary the hook runs.
|
|
const override = (env.GSTACK_MEMORABLE_BIN ?? '').trim() || (env.MEMORABLE_BIN ?? '').trim();
|
|
if (override) {
|
|
const o = stripQuotes(override);
|
|
const resolved = path.isAbsolute(o) ? o : (Bun.which(o) ?? null);
|
|
return resolved && executable(resolved) ? resolved : null;
|
|
}
|
|
const pinned = path.join(homeDir, '.memorable', 'bin', 'memorable');
|
|
if (executable(pinned)) return pinned;
|
|
const onPath = Bun.which('memorable');
|
|
return onPath && executable(onPath) ? onPath : null;
|
|
}
|
|
|
|
/**
|
|
* Best-effort, rate-limited (hook-log.ts): a message with the same `key`
|
|
* (default: the message itself) within LOG_RATE_LIMIT_MS is not re-logged, so
|
|
* a vendor that fails on every prompt with a different timestamp in its stderr
|
|
* still costs one line per ten minutes, and two alternating failures cost two.
|
|
* The log is 0600 on every append; it can name the session's cwd and vendor
|
|
* diagnostics.
|
|
*/
|
|
export function logHookError(msg: string, nowMs: number = Date.now(), key: string = msg): void {
|
|
sharedLogHookError(HOOK_NAME, msg, { rateLimit: { nowMs, key } });
|
|
}
|
|
|
|
function readStdin(maxBytes: number, timeoutMs: number): Promise<{ buf: Buffer; oversize: boolean; timedOut: boolean }> {
|
|
return new Promise((resolve) => {
|
|
const chunks: Buffer[] = [];
|
|
let total = 0;
|
|
let done = false;
|
|
let oversize = false;
|
|
const finish = (timedOut: boolean): void => {
|
|
if (done) return;
|
|
done = true;
|
|
clearTimeout(timer);
|
|
try { process.stdin.destroy(); } catch { /* already closed */ }
|
|
resolve({ buf: Buffer.concat(chunks), oversize, timedOut });
|
|
};
|
|
const timer = setTimeout(() => finish(true), Math.max(1, timeoutMs));
|
|
process.stdin.on('data', (d: Buffer | string) => {
|
|
if (done) return;
|
|
const chunk = typeof d === 'string' ? Buffer.from(d, 'utf8') : d;
|
|
total += chunk.length;
|
|
if (total > maxBytes) { oversize = true; finish(false); return; }
|
|
chunks.push(chunk);
|
|
});
|
|
process.stdin.on('end', () => finish(false));
|
|
process.stdin.on('error', () => finish(false));
|
|
});
|
|
}
|
|
|
|
function gateIsOn(timeoutMs: number): 'on' | 'off' | 'error' {
|
|
const r = runBin('gstack-config', ['get', 'memorable_recall'], { encoding: 'utf8', timeout: Math.max(1, timeoutMs), env: process.env });
|
|
if (r.status !== 0) return 'error';
|
|
return String(r.stdout ?? '').trim() === 'on' ? 'on' : 'off';
|
|
}
|
|
|
|
/**
|
|
* git exit 2 = no such remote; exit 128 whose message STARTS with this text
|
|
* (git is run with LC_ALL=C so the text is English) = not inside a repository.
|
|
* Anchored, never a substring test: other exit-128 messages echo the
|
|
* repository path, which a directory name could make carry the phrase.
|
|
*/
|
|
const GIT_NO_REMOTE = 2;
|
|
const GIT_FATAL = 128;
|
|
const NOT_A_REPO_RE = /^fatal: not a git repository\b/;
|
|
|
|
/** Kills the in-flight detached child (git for the policy lookup, then the vendor); read by the signal handlers. */
|
|
let killInflight: (() => void) | null = null;
|
|
|
|
/**
|
|
* git's environment for the policy lookup: English messages, and NO inherited
|
|
* GIT_* repository selectors (GIT_DIR, GIT_WORK_TREE, GIT_COMMON_DIR,
|
|
* GIT_CONFIG_*, ...): cwd does not override them, so an inherited GIT_DIR
|
|
* would make the veto inspect a different repository than the one the
|
|
* session works in. Exported for tests.
|
|
*/
|
|
export function gitEnv(env: Record<string, string | undefined>): Record<string, string> {
|
|
const out: Record<string, string> = {};
|
|
for (const [k, v] of Object.entries(env)) {
|
|
if (v == null || k.startsWith('GIT_')) continue;
|
|
out[k] = v;
|
|
}
|
|
out.LC_ALL = 'C'; out.LANGUAGE = ''; out.LC_MESSAGES = 'C';
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* Trust-policy veto by the session's repo (keyed by its origin remote).
|
|
* Every half fails CLOSED once a store exists: a git that could not run or
|
|
* answer in time, a git that could not read the repository (corrupt or
|
|
* unreadable config, dubious ownership: exit 128 without "not a git
|
|
* repository"), or a store that could not be read is a failed lookup
|
|
* (`error`), never "no remote". Only "no such remote" and "not a repository"
|
|
* mean nothing can be set for this directory.
|
|
*/
|
|
async function policyVeto(cwd: string, timeoutMs: number, remaining: () => number): Promise<'ok' | 'skip' | 'error'> {
|
|
if (!hasRepoPolicyStore()) return 'ok';
|
|
const git = await runExternal('git', ['remote', 'get-url', 'origin'], {
|
|
cwd, timeoutMs: Math.max(1, timeoutMs), maxBuffer: GIT_MAX_BUFFER, env: gitEnv(process.env),
|
|
onSpawn: (kill) => { killInflight = kill; }, // a host cancellation must not leak this git either
|
|
});
|
|
killInflight = null;
|
|
if (git.timedOut || git.error) return 'error';
|
|
if (git.status === GIT_NO_REMOTE) return 'ok';
|
|
if (git.status === GIT_FATAL && NOT_A_REPO_RE.test(git.stderrTail.trim())) return 'ok';
|
|
if (git.status !== 0) return 'error';
|
|
const url = git.stdout.toString('utf8').trim();
|
|
if (!url) return 'ok';
|
|
const res = repoPolicyTier(url, process.env, Math.max(1, Math.min(STAGE_CAP_MS, remaining())));
|
|
if (res.error) return 'error';
|
|
// `deny` and `read-only` are the tiers a user picks so a repo's content
|
|
// never lands in a shared store; a third-party memory service is one.
|
|
return res.tier === 'deny' || res.tier === 'read-only' ? 'skip' : 'ok';
|
|
}
|
|
|
|
function writeStdout(text: string): Promise<void> {
|
|
return new Promise((resolve) => { process.stdout.write(text, () => resolve()); });
|
|
}
|
|
|
|
|
|
/** Best-effort: the ledger's size warning goes to stderr, which the host discards for an exit-0 hook; log it where `status` looks. */
|
|
function noteLedgerSize(): void {
|
|
try {
|
|
const ledger = egressLedgerPath(resolveEgressHome());
|
|
const size = fs.statSync(ledger).size;
|
|
if (size > LEDGER_WARN_BYTES) logHookError(ledgerSizeWarning(ledger, size).replace(/\s+/g, ' ').trim(), Date.now(), 'ledger-size');
|
|
} catch { /* no ledger yet */ }
|
|
}
|
|
|
|
export async function main(): Promise<void> {
|
|
const start = Date.now();
|
|
const cap = budgetMs();
|
|
const remaining = (): number => budgetFor(start, Date.now(), cap);
|
|
|
|
const stdin = await readStdin(STDIN_CAP_BYTES, Math.min(STAGE_CAP_MS, remaining()));
|
|
if (stdin.oversize) { logHookError(`oversize: stdin exceeded ${STDIN_CAP_BYTES / (1024 * 1024)} MiB, recall skipped`); return; }
|
|
const raw = stdin.buf;
|
|
if (raw.length === 0) return;
|
|
const rawText = raw.toString('utf8');
|
|
let payload: unknown;
|
|
try { payload = JSON.parse(rawText); } catch {
|
|
logHookError(stdin.timedOut
|
|
? 'stdin was not closed within the read budget (incomplete JSON), recall skipped'
|
|
: 'stdin was not JSON, recall skipped');
|
|
return;
|
|
}
|
|
if (!payload || typeof payload !== 'object') return;
|
|
|
|
if (process.env.MEMORABLE === '0') return; // the vendor's own kill switch
|
|
|
|
const gate = gateIsOn(Math.min(STAGE_CAP_MS, remaining()));
|
|
if (gate === 'error') { logHookError('gstack-config get memorable_recall failed, recall skipped (fail-closed)'); return; }
|
|
if (gate !== 'on') return;
|
|
|
|
if (process.platform === 'win32') { logHookError('Windows is not supported by this bridge yet (TODOS.md D21), recall skipped'); return; }
|
|
|
|
const payloadCwd = (payload as { cwd?: unknown }).cwd;
|
|
const cwd = typeof payloadCwd === 'string' && isDirectory(payloadCwd) ? payloadCwd : process.cwd();
|
|
const veto = await policyVeto(cwd, Math.min(STAGE_CAP_MS, remaining()), remaining);
|
|
if (veto === 'skip') { logHookError(`trust policy for ${cwd} is deny or read-only, recall skipped`, Date.now(), 'trust policy skip'); return; }
|
|
if (veto === 'error') { logHookError('trust policy lookup failed (store or repository unreadable), recall skipped (fail-closed)'); return; }
|
|
|
|
// HIGH-tier pre-scan over the raw text and the decoded string leaves (a JSON
|
|
// escape must not hide a key). scan() is synchronous and uninterruptible and
|
|
// its cost is roughly linear in bytes, so each scan is admitted by the clock
|
|
// with a size-derived allowance: a scan we cannot afford skips recall
|
|
// instead of letting the host kill us mid-scan.
|
|
const walked = stringLeavesBounded(payload);
|
|
if (walked.exhausted) {
|
|
// A payload too deep or too wide to walk is unscanned, not clean.
|
|
logHookError('refused:payload-too-complex: the prompt JSON exceeded the scan walk bounds, nothing handed to the vendor');
|
|
return;
|
|
}
|
|
const leaves = walked.leaves.join('\n');
|
|
for (const text of [rawText, leaves]) {
|
|
const allowance = MIN_SPAWN_MS + Math.ceil(Buffer.byteLength(text, 'utf8') / 1024) * SCAN_MS_PER_KIB;
|
|
if (remaining() < allowance) { logHookError('budget-exhausted before the secret scan, recall skipped'); return; }
|
|
const result = scan(text, { repoVisibility: 'unknown' });
|
|
if (result.oversize || result.counts.HIGH > 0) {
|
|
logHookError('refused:redaction-high: the prompt carries a HIGH-tier credential shape, nothing handed to the vendor');
|
|
return;
|
|
}
|
|
}
|
|
|
|
const vendor = resolveVendor(process.env, os.homedir());
|
|
if (!vendor) { logHookError(`memorable CLI not found (checked ${RESOLUTION_ORDER}), recall skipped`); return; }
|
|
|
|
if (remaining() < MIN_SPAWN_MS) { logHookError('budget-exhausted before the vendor spawn, recall skipped'); return; }
|
|
const again = gateIsOn(Math.min(RECHECK_CAP_MS, remaining()));
|
|
if (again === 'error') { logHookError('gstack-config get memorable_recall failed on the pre-spawn re-check, recall skipped (fail-closed)'); return; }
|
|
if (again !== 'on') return; // a disable that landed while we worked wins
|
|
|
|
let receiptId: string;
|
|
try {
|
|
const { id } = writeReceipt({
|
|
sink: SINK,
|
|
host: `local:${vendor}`,
|
|
payloadClass: PAYLOAD_CLASS,
|
|
bytes: raw.length,
|
|
sha256: sha256Hex(raw),
|
|
consent: CONSENT,
|
|
lockBudgetMs: Math.max(0, remaining() - RESERVE_MS),
|
|
});
|
|
receiptId = id;
|
|
noteLedgerSize();
|
|
} catch (err) {
|
|
// fail-closed: no receipt, no send
|
|
const why = err instanceof Error ? err.message : String(err);
|
|
logHookError(`refused:receipt-unwritable: ${why}`);
|
|
process.stderr.write(`gstack: memorable recall skipped, the egress receipt could not be written (${why}). See gstack-egress.\n`);
|
|
return;
|
|
}
|
|
if (remaining() < MIN_SPAWN_MS) {
|
|
logHookError('budget-exhausted after the receipt, recall skipped');
|
|
try { writeOutcome({ receipt: receiptId, status: 'budget-exhausted', lockBudgetMs: Math.max(0, remaining() - OUTCOME_RESERVE_MS) }); } catch { /* bookkeeping */ }
|
|
return;
|
|
}
|
|
|
|
const gstackMs = Date.now() - start;
|
|
// VENDOR SPAWN: everything above is gstack's own boundary; from here the bytes are the vendor's.
|
|
const r = await runExternal(vendor, ['hook', 'user-prompt'], {
|
|
input: raw,
|
|
timeoutMs: Math.max(1, remaining() - RESERVE_MS),
|
|
maxBuffer: 1024 * 1024,
|
|
env: vendorEnv(process.env),
|
|
cwd,
|
|
onSpawn: (kill) => { killInflight = kill; },
|
|
});
|
|
killInflight = null;
|
|
|
|
let status: string;
|
|
let delivered = false;
|
|
if (r.timedOut) status = 'timeout';
|
|
else if (r.error) status = `spawn-error:${r.error}`;
|
|
else if (r.status !== 0) status = `exit:${r.status} injected=no`;
|
|
else {
|
|
const ctx = pickAdditionalContext(r.stdout.toString('utf8'));
|
|
if (!ctx) status = 'exit:0 injected=no';
|
|
else {
|
|
const rendered = renderContext(ctx);
|
|
const out = JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: rendered } });
|
|
await writeStdout(out);
|
|
delivered = true;
|
|
status = `exit:0 output-written bytes=${Buffer.byteLength(rendered, 'utf8')} gstack_ms=${gstackMs}`;
|
|
}
|
|
}
|
|
// A vendor that exited before reading its stdin (EPIPE) is advisory when it
|
|
// still answered; the outcome records it, the answer is kept.
|
|
if (r.stdinError) status += ` stdin=${r.stdinError}`;
|
|
if (!delivered && (r.timedOut || r.error || r.status !== 0)) {
|
|
// Logged whether or not the vendor said anything: a silently hanging
|
|
// vendor taxes every prompt and must show up in `gstack-memorable status`.
|
|
const tail = safeStderrTail(r.stderrTail);
|
|
logHookError(`vendor ${status}${tail ? `: ${tail}` : ''}`, Date.now(), `vendor ${status}`);
|
|
}
|
|
// The vendor's timeout already left RESERVE_MS on the clock for exactly
|
|
// this: the stdout write above and one bounded ledger append.
|
|
if (remaining() > OUTCOME_MIN_MS) {
|
|
try { writeOutcome({ receipt: receiptId, status, lockBudgetMs: Math.max(0, remaining() - OUTCOME_RESERVE_MS) }); } catch { /* the receipt is the invariant; the outcome is bookkeeping */ }
|
|
}
|
|
}
|
|
|
|
if (import.meta.main) {
|
|
for (const sig of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) {
|
|
process.on(sig, () => {
|
|
// The host is ending us (its 5 s hook kill, or a session teardown): the
|
|
// vendor must not outlive the hook that spawned it.
|
|
if (killInflight) { killInflight(); killInflight = null; }
|
|
logHookError(`terminated by ${sig} mid-flight; the vendor process group was killed, the receipt (if any) reads unknown`, Date.now(), 'terminated');
|
|
process.exit(0);
|
|
});
|
|
}
|
|
main()
|
|
.catch((err) => logHookError(`unexpected: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`))
|
|
.finally(() => { process.exitCode = 0; });
|
|
}
|