Files
gstack/test/timeline-stop-hook.test.ts
T
Garry TanandClaude Fable 5 9da6692930 v1.68.1.0 fix: phantom AskUserQuestion hooks — canonical-only registration + self-healing settings.json (#2631)
* fix(settings-hook): KNOWN_HOOKS identity healer — per-item ownership, mutation lock, fail-closed parse

Claude Code strips the unknown _gstack_source key when it rewrites
settings.json, so tag-based dedupe degraded to exact-command equality and
every Conductor worktree's setup appended a fresh hook entry; deleted
worktrees left dead hooks erroring on every AskUserQuestion fire.

- KNOWN_HOOKS identity table (shared JS prelude, single source of truth):
  ownership is intrinsic and PER HOOK ITEM — basename + relpath suffix +
  event (+ matcher where defined). Tags never claim foreign items.
- New `prune-stale [--repoint <root>] [--all]`: prune dead gstack items,
  re-point survivors at the stable install (tag restore from the table),
  exact-duplicate collapse, uninstall/no-team identity sweep. Explicit
  plan_tune_hooks:no is honored (dead pruned, live never re-pointed).
- add-event / remove-source become item-aware: replace/remove only the owned
  item; a user's co-located hook in the same entry is never collateral.
- Mutation safety: mkdir lock with owner token, ownership-checked release,
  atomic stale takeover; per-process-unique tmp + backup names;
  backup-on-change everywhere; fail-closed on parse failure (a corrupt
  settings.json is never overwritten — previously catch{} clobbered it);
  locked atomic rollback.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(gstack-config): `has <key>` — key-presence provenance through STATE_DIR resolution

`get` returns the DEFAULTS value for absent keys, so callers that need to
know whether the USER decided something (vs inherited a default) had no
correct primitive — setup's consent logic was about to grep a hardcoded
~/.gstack/config.yaml, which misclassifies under GSTACK_STATE_ROOT /
GSTACK_HOME / GSTACK_STATE_DIR overrides. `has` exits 0 iff the key is
literally present in the resolved config file, with the same C-locale key
validation as get/set.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(setup): canonical-only hook registration, heal-first, PT_EXPLICIT consent provenance

Three root causes of the phantom-AskUserQuestion-hooks class, all in the
registration path:

- Bug A: the Conductor auto-opt-in upgraded PT_DECISION "prompt" -> "yes"
  even when "prompt" was dev-setup's EXPLICIT --plan-tune-hooks=prompt pin,
  so every new Conductor workspace installed hooks. PT_EXPLICIT (flag/env/
  config-key-presence via `gstack-config has`) now gates the auto-opt-in to
  the true silent fall-through.
- Bug B: hook commands were baked from $SOURCE_GSTACK_DIR (`pwd -P` of the
  running tree — ephemeral for worktrees). Registration is now CANONICAL-ONLY
  via _hook_command_path (${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills/gstack);
  missing canonical hook = skip + log, never a baked tree path. SessionStart
  moves to schema-aware add-event under its identity source; whitespace paths
  are quoted.
- Bug C: nothing ever pruned, and dead tagged entries blocked the
  "already installed" guards forever. Setup now heals FIRST on every run
  (prune-stale --repoint at the stable install), surfaces a one-line summary
  only when something changed, surfaces the plan_tune_hooks:no-vs-live-hooks
  contradiction, and --no-team tears down all three sources plus an identity
  sweep for untagged strays.

dev-setup's no-mutation guarantee gains its stated repair exception (prune
dead / re-point existing, never ADD).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(uninstall): run hook cleanup BEFORE install-root deletion + full identity sweep

SETTINGS_HOOK resolves via $(dirname "$0") INSIDE the install root, but the
cleanup ran after `rm -rf ~/.claude/skills/gstack` — a real global uninstall
(running the installed copy) silently no-op'd and orphaned every hook entry.
Tests masked it by running the uninstaller from the repo checkout.

The relocated block also removes the auq-error-fallback source (registered by
setup, previously never torn down) and finishes with a prune-stale --all
identity sweep so untagged strays (Claude Code strips _gstack_source) go too.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test: phantom-hooks heal coverage — incident facsimile, per-item safety, lock, canonical tripwires

- gstack-settings-hook-schema-aware: 16 new cases — identity re-point (tag
  restore), foreign-basename rejection, mixed-entry per-item safety for
  add-event/remove-source/--all, prune-stale modes incl. bash-prefix +
  Windows-backslash + spaced-path idempotence, duplicate collapse preferring
  the tagged twin, plan_tune_hooks:no split, backup-on-change no-churn,
  fail-closed corrupt-JSON for every mutator, stale-lock takeover,
  fresh-foreign-lock skip, two-writer concurrency smoke, and an INCIDENT
  FACSIMILE replaying the exact 2026-08-17 production damage (6/3/2 entries,
  mixed tags, live-ephemeral Stop) healing to 2/1/1 canonical.
- NEW setup-hook-canonical-paths: static tripwires — canonical-only resolver
  (no $SOURCE_GSTACK_DIR anywhere in it), heal-before-guards ordering,
  unsuppressed heal output, ${VAR:-0} counter idiom, shared-prelude
  concatenation at every bun call site, KNOWN_HOOKS completeness vs setup's
  registrations, uninstall cleanup-before-deletion ordering, defect-class
  warning present.
- setup-plan-tune-hooks-noninteractive: PT_EXPLICIT pins + `gstack-config
  has` provenance + has-subcommand behavior (env-resolution, malformed keys).
- auq-error-fallback-hook: registration + both-teardown wiring (previously
  untested).
- uninstall: behavioral ordering test running the INSTALLED copy from inside
  the root it deletes.
- setup-windows-fallback / gstack-config-key-locale: pins updated for the new
  HOOK_CMD shape and the third C-locale validator.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(test): banner-tripwire exec used JSON.stringify as shell quoting — vacuous pass + stray artifact

JSON escaping is not shell escaping. Interpolating JSON.stringify(script)
into `bash -c ${...}` left every JSON "\n" as a literal backslash-n inside
shell double quotes, collapsing the extracted release-body tripwire block
onto one line: `then\n` parsed as the command word `thenn`, and
`>&2\nelse\n` parsed as the redirect `>&2nelsen` — so every full-suite run
littered a `2nelsen` file (containing "bash: thenn: command not found") in
the repo root, and the test's single not-contains assertion passed
VACUOUSLY because all output had been redirected into that file. The
"and it actually fires" functional check never verified anything.

Fix: pass the script as an argv element (spawnSync array form) and assert
both branches for real — ABORT case must print the leak message to stderr,
clean case must print "banner tripwire clean" to stdout.

Verified: `bun test test/binding-template-drift.test.ts` previously created
the artifact deterministically; the full free suite now runs artifact-free.
The other shell-interpolation sites (evidence, schema-aware concurrency,
empty-find-fallthrough, branch-slug-hygiene) already use correct quoting.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test: regression pin for legacy remove mixed-entry filtering + ownership negatives

Coverage-audit iron rule: the rewritten legacy `remove` action filters
per-item (pre-v1.67.2 it dropped the whole entry, destroying a user's
co-located SessionStart hook) — modified existing behavior, previously
untested. Also pins two ownership negatives: an owned basename+relpath under
the WRONG matcher stays foreign, and prune-stale on an absent settings file
exits 0 with removed 0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: pre-landing review fixes — review-army findings hardened

Specialist review (testing, maintainability, security, performance,
data-migration) findings, each verified against code before fixing:

- legacy remove: preserve malformed/foreign entries (hooks absent, non-array,
  or pre-existing empty) — only entries THIS pass emptied are dropped
- add-event: never tag a mixed entry (old gstack versions in sibling
  worktrees treat tags as entry-level ownership and would destroy the user's
  co-located items); tag only single-item entries; prune-stale drops tags
  from mixed entries for the same reason
- prune-stale: within-entry twin collapse (two dead copies of one hook
  re-pointed to the same canonical command no longer double-fire); command
  quoting hardened via gsQuoteCmd (escapes \\ " $ backtick; gsStripWrap
  unescapes so identity round-trips); NUL bytes in the dedupe key replaced
  with a JSON.stringify key (bash silently dropped the NULs, degrading the
  separator; the file also read as binary to tooling)
- gsIsAlive: only provable absence (ENOENT/ENOTDIR) counts as dead —
  EACCES/EIO/unmounted volumes no longer prune (one-way-ratchet guard)
- gsWriteIfChanged: preserves the live settings.json mode across rewrites
  (a user-tightened 0600 carrying API keys was silently broadened to 0644);
  fresh files start 0600; backups rotate (keep 10)
- remove-source: command-less items default to foreign (gstack only writes
  type:command items); single-item stray claim requires a command
- rollback: pointer target must be a sibling settings.json.bak.* file
- uninstall + setup --no-team + SessionStart registration: stderr stays
  attached — a lock give-up or fail-closed parse during TEARDOWN must be
  visible ("the next setup retries" does not apply after uninstall)
- setup: team-mode banner no longer claims an auto-update hook when
  registration was skipped; heal log documents the rollback-pointer caveat;
  SESSION_UPDATE_CMD quoting mirrors gsQuoteCmd; lock constants named
- list-sources: corrupt settings.json reports to stderr instead of silently
  printing nothing (setup guards must not misread corrupt as no-hooks)
- tests: 10 new pins (malformed-entry preservation, mixed no-tag, twin
  collapse, 0600 mode, metachar escaping round-trip, backup rotation,
  rollback pointer refusal, held-lock uninstall warning, matcher-drift
  tripwire, ownership negatives)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: red-team findings — verify-gate identity, single quoting authority, Windows paths

Red-team pass over the hardened diff (several findings empirically verified
by the reviewer before reporting):

- KNOWN_HOOKS gains the sixth identity: gstack-verify-gate (README-documented
  opt-in Stop hook). A tag-stripped verify-gate entry previously survived
  prune-stale --all and errored at the end of EVERY turn after uninstall
  deleted the install root — the exact phantom-hook class this branch fixes.
  Uninstall also sweeps its tagged form.
- add-event is now the single quoting authority: every registered command is
  normalized through the same gsQuoteCmd/gsStripWrap round-trip the healer
  uses. Pre-fix, only SessionStart got caller-side quoting — a spaced/metachar
  canonical root registered broken plan-tune/AUQ/timeline hooks that the very
  next heal rewrote (the codebase disagreed with its own registrations).
- Windows: MSYS-form paths (/c/Users/...) are drive-translated for fs checks
  only (gsWinPath) — native bun resolved them drive-relative, so the heal
  judged every LIVE Windows hook dead and pruned it. The three AskUserQuestion
  hooks and the Stop hook now also get the mandatory 'bash ' prefix on
  Windows (previously only SessionStart did; extensionless bash shims
  otherwise hit the file-association dialog).
- CANONICAL_GSTACK_ROOT falls back to $HOME/.claude/skills/gstack when a
  CLAUDE_CONFIG_DIR-derived root was never installed (the installer hardcodes
  the home path — split-brain left such users permanently hookless).
- prune-stale preserves foreign entries that STARTED empty (they were
  silently deleted, uncounted, on every heal).
- The timeline Stop registration and its list-sources guard join the
  zero-silent-mutations contract (stderr attached).

Tests: verify-gate tag-stripped heal+sweep, started-empty preservation,
add-event quoting-authority round-trip.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump version and changelog (v1.68.1.0)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: update project documentation for v1.68.1.0

README: document canonical-only hook registration + the prune-stale
self-heal in the setup hooks section; expand the manual-uninstall note
to cover every gstack hook identity, not just timeline-stop-hook.
CONTRIBUTING: record PT_EXPLICIT provenance (Conductor auto-opt-in
fires only on the true silent fall-through) and the heal-first repair
exception in the dev-setup paragraph.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(settings-hook): fail-loud hardening — gsMain umbrella, lock exit 5, prototype-safe ownership

bun in -e mode swallows uncaught exceptions thrown after a require() and
exits 0 (verified on 1.3.13; uncaughtException handlers never fire either),
so any runtime throw in a mutator was a SILENT SUCCESS. Every script body
now runs inside a gsMain try/catch that prints "internal error ... refusing
to mutate" and exits 4.

Also: lock give-up now exits 5 instead of 0 (callers must not report a
skipped mutation as registered); basename lookup uses hasOwnProperty so a
foreign hook named "toString"/"constructor" can't resolve to an inherited
Object.prototype member and abort the sweep; ownership-checked release also
clears an empty/missing owner file; backup rotation sorts by mtime, not
name; Windows-only backslash normalization (a legal Unix path containing a
backslash is no longer rewritten); GSTACK_SWEEP_EXCLUDE_SOURCES lets a
sweep spare named sources; lock tradeoffs documented at the lock helper.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(setup): honest hook-registration reporting + verify-gate sweep exclusion

_install_plan_tune_hooks now propagates per-add-event failures (lock
contention exits 5, fail-closed settings errors exit 3) and both caller
sites branch on it: success logs the installed message, failure logs a
visible "NOT registered — re-run ./setup" warning instead of claiming
success for a mutation that never happened.

--no-team's identity sweep runs with GSTACK_SWEEP_EXCLUDE_SOURCES=
verify-gate: turning team mode off must not delete the user-registered
verify-gate opt-in whose binary still exists (uninstall still sweeps it,
correctly, because there the binary itself is being removed).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test: adversarial regression pins — wrong-shape fail-loud, prototype basename, sweep exclusion, lock exit 5

New pins for the fail-loud hardening: a wrong-shape hooks value (object
where an array belongs) exits 4 with "refusing to mutate" and leaves the
file byte-identical (pre-gsMain this was a silent exit-0 no-op); a foreign
hook whose basename collides with Object.prototype ("toString") survives
an --all sweep that still removes gstack rows; GSTACK_SWEEP_EXCLUDE_SOURCES
preserves the verify-gate row during --all; the fresh-foreign-lock test now
asserts the loud exit 5 instead of a quiet skip.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(verify-gate): allow the --no-team sweep exclusion, keep registration banned

setup now legitimately mentions verify-gate once: the --no-team identity
sweep excludes it via GSTACK_SWEEP_EXCLUDE_SOURCES so team-mode teardown
can't delete a user-registered gate. The opt-in pin tightens from a blanket
not-contains to: every mention must be a comment or that exclusion, and no
mention may sit on an add-event line.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(settings-hook): GNU-first stat in the lock stale check — Linux abort on held locks

On Linux, BSD-style `stat -f %m` prints a multi-line FILESYSTEM block to
stdout before exiting 1, so the BSD-first || chain captured that garbage
concatenated with the real `stat -c %Y` epoch. The non-numeric mtime made
`$(( now - mtime ))` a syntax error and set -e killed the binary with
exit 1 whenever a lock dir already existed — every contention path (stale
takeover, give-up, concurrent writers) broke on CI while staying green on
macOS, where BSD stat -f succeeds cleanly.

GNU `stat -c %Y` now goes first (BSD stat rejects -c with no stdout, so
macOS falls through cleanly), and a numeric guard blanks any residual
garbage so a future platform quirk degrades to the normal give-up path
instead of an arithmetic abort. Same defect class as gstack-repo-mode's
GNU-first ordering (#2195). Verified in an oven/bun Linux container:
the four CI-failing lock tests now pass (62/62 across both files).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(uninstall): 30s budgets for the two subprocess-heavy behavioral tests

Both tests spawn the copied uninstaller, which itself runs several
settings-hook bun -e children (the lock-contention one also waits out a
300ms give-up per call). On a loaded box those cold starts blow bun's
default 5s per-test timeout, and a timeout kill reports as a bare fail
with no assertion diff — observed at 5.6-8.5s under load avg 25+.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:53:19 -07:00

489 lines
20 KiB
TypeScript

/**
* Timeline Stop hook (#2553) — fail-open contract (F5).
*
* The preamble writes event:"started" at every skill start; the completion
* write is end-of-workflow prose and unenforceable, so interrupted sessions
* leaked started > completed forever. The Stop hook closes dangling entries.
*
* Contract under test: ALWAYS exits 0 (corrupt timeline, missing timeline,
* garbage stdin), append-only, and the normal path appends event:"completed"
* with outcome "unknown" + source "stop-hook" for every un-closed "started".
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { spawnSync } from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
const ROOT = path.resolve(import.meta.dir, '..');
const HOOK = path.join(ROOT, 'hosts', 'claude', 'hooks', 'timeline-stop-hook');
const SLUG = 'stop-hook-test-project';
let tmpHome: string;
let projectDir: string;
let timelinePath: string;
beforeEach(() => {
tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-stop-hook-home-'));
projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-stop-hook-proj-'));
fs.mkdirSync(path.join(tmpHome, 'projects', SLUG), { recursive: true });
timelinePath = path.join(tmpHome, 'projects', SLUG, 'timeline.jsonl');
});
afterEach(() => {
fs.rmSync(tmpHome, { recursive: true, force: true });
fs.rmSync(projectDir, { recursive: true, force: true });
});
function runHook(stdin: string): { exitCode: number; stdout: string; stderr: string } {
const r = spawnSync('bash', [HOOK], {
input: stdin,
encoding: 'utf-8',
env: {
...process.env,
GSTACK_HOME: tmpHome,
GSTACK_PROJECT_SLUG: SLUG, // deterministic slug, no git required
},
timeout: 15_000,
});
return { exitCode: r.status ?? 1, stdout: r.stdout, stderr: r.stderr };
}
function stopPayload(): string {
return JSON.stringify({
session_id: 'sess-abc',
hook_event_name: 'Stop',
cwd: projectDir,
});
}
function timelineEntries(): any[] {
if (!fs.existsSync(timelinePath)) return [];
return fs
.readFileSync(timelinePath, 'utf-8')
.split('\n')
.filter((l) => l.trim())
.map((l) => {
try {
return JSON.parse(l);
} catch {
return { __corrupt: l };
}
});
}
describe('timeline-stop-hook (#2553, F5 fail-open)', () => {
test('normal path: closes dangling started entries, leaves closed pairs alone', () => {
fs.writeFileSync(
timelinePath,
[
JSON.stringify({ skill: 'review', event: 'started', branch: 'main', session: '11-1' }),
JSON.stringify({ skill: 'ship', event: 'started', session: '22-2' }),
JSON.stringify({ skill: 'ship', event: 'completed', session: '22-2', outcome: 'success' }),
].join('\n') + '\n',
);
const r = runHook(stopPayload());
expect(r.exitCode).toBe(0);
const entries = timelineEntries();
// Append-only: the three originals survive verbatim in order.
expect(entries[0]).toMatchObject({ skill: 'review', event: 'started' });
expect(entries[2]).toMatchObject({ skill: 'ship', event: 'completed', outcome: 'success' });
const repairs = entries.filter((e) => e.source === 'stop-hook');
expect(repairs).toHaveLength(1);
expect(repairs[0]).toMatchObject({
skill: 'review',
event: 'completed',
outcome: 'unknown',
branch: 'main',
session: '11-1',
});
expect(typeof repairs[0].ts).toBe('string');
});
test('idempotent: a second Stop appends nothing new', () => {
fs.writeFileSync(
timelinePath,
JSON.stringify({ skill: 'qa', event: 'started', session: '33-3' }) + '\n',
);
expect(runHook(stopPayload()).exitCode).toBe(0);
const afterFirst = timelineEntries().length;
expect(runHook(stopPayload()).exitCode).toBe(0);
expect(timelineEntries().length).toBe(afterFirst);
});
test('count semantics: two runs under one key, one completed — the dangler is still repaired', () => {
// Legacy entries carry no session field, so both runs share the same
// skill+session key (same-second "$$-epoch" ids collide the same way).
// With set semantics the first run's completion masked the second run's
// dangler forever; counting closes the difference.
fs.writeFileSync(
timelinePath,
[
JSON.stringify({ skill: 'review', event: 'started' }),
JSON.stringify({ skill: 'review', event: 'completed', outcome: 'success' }),
JSON.stringify({ skill: 'review', event: 'started' }),
].join('\n') + '\n',
);
expect(runHook(stopPayload()).exitCode).toBe(0);
const repairs = timelineEntries().filter((e) => e.source === 'stop-hook');
expect(repairs).toHaveLength(1);
expect(repairs[0]).toMatchObject({ skill: 'review', event: 'completed', outcome: 'unknown' });
// Idempotent under count semantics too: started=2, completed=2 → no-op.
expect(runHook(stopPayload()).exitCode).toBe(0);
expect(timelineEntries().filter((e) => e.source === 'stop-hook')).toHaveLength(1);
});
test('exit 0 on missing timeline (nothing written, nothing created)', () => {
const r = runHook(stopPayload());
expect(r.exitCode).toBe(0);
expect(fs.existsSync(timelinePath)).toBe(false);
});
test('exit 0 on a corrupt timeline; corrupt lines are skipped, valid ones still repaired', () => {
fs.writeFileSync(
timelinePath,
[
'this is not json at all {{{',
JSON.stringify({ skill: 'qa', event: 'started', session: '44-4' }),
'{"half": "an object"',
].join('\n') + '\n',
);
const r = runHook(stopPayload());
expect(r.exitCode).toBe(0);
const repairs = timelineEntries().filter((e) => e.source === 'stop-hook');
expect(repairs).toHaveLength(1);
expect(repairs[0].skill).toBe('qa');
});
test('exit 0 on a FULLY corrupt timeline (no valid entries → no write)', () => {
const garbage = 'garbage\n{{{\n';
fs.writeFileSync(timelinePath, garbage);
const r = runHook(stopPayload());
expect(r.exitCode).toBe(0);
expect(fs.readFileSync(timelinePath, 'utf-8')).toBe(garbage);
});
test('exit 0 on garbage stdin', () => {
fs.writeFileSync(
timelinePath,
JSON.stringify({ skill: 'qa', event: 'started', session: '55-5' }) + '\n',
);
const r = runHook('not json');
expect(r.exitCode).toBe(0);
});
test('exit 0 on empty stdin', () => {
expect(runHook('').exitCode).toBe(0);
});
test('tail window (P3): a recent dangling entry in a >256KB timeline is still repaired', () => {
const lines: string[] = [];
// An old dangling entry that falls OUTSIDE the 256KB tail window —
// beyond repair interest by design (its session is long gone).
lines.push(JSON.stringify({ skill: 'review', event: 'started', session: 'old-1' }));
// >512KB of closed pairs pushes the old entry well past the window while
// proving windowed parsing still walks real entries.
let n = 0;
while (lines.length * 100 < 512 * 1024) {
lines.push(
JSON.stringify({ skill: 'qa', event: 'started', session: `pad-${n}`, pad: '#'.repeat(40) }),
);
lines.push(JSON.stringify({ skill: 'qa', event: 'completed', session: `pad-${n}`, outcome: 'success' }));
n++;
}
lines.push(JSON.stringify({ skill: 'ship', event: 'started', session: 'recent-9' }));
fs.writeFileSync(timelinePath, lines.join('\n') + '\n');
expect(fs.statSync(timelinePath).size).toBeGreaterThan(256 * 1024);
const r = runHook(stopPayload());
expect(r.exitCode).toBe(0);
const repairs = timelineEntries().filter((e) => e.source === 'stop-hook');
expect(repairs).toHaveLength(1);
expect(repairs[0]).toMatchObject({
skill: 'ship',
event: 'completed',
outcome: 'unknown',
session: 'recent-9',
});
});
test('oversized timeline is skipped, untouched, and still exits 0 (fail-open size cap)', () => {
const line = JSON.stringify({ skill: 'qa', event: 'started', session: '66-6' }) + '\n';
const filler = '#'.repeat(1024 * 1024);
fs.writeFileSync(timelinePath, line + filler.repeat(11));
const sizeBefore = fs.statSync(timelinePath).size;
const r = runHook(stopPayload());
expect(r.exitCode).toBe(0);
expect(fs.statSync(timelinePath).size).toBe(sizeBefore);
});
});
describe('timeline-stop-hook wiring', () => {
const SETTINGS_HOOK = path.join(ROOT, 'bin', 'gstack-settings-hook');
test('setup registers the Stop hook with its own source tag and tears it down on --no-team', () => {
const setup = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
expect(setup).toContain('--event Stop');
expect(setup).toContain('--source gstack-timeline-stop');
expect(setup).toContain('hosts/claude/hooks/timeline-stop-hook');
// --no-team teardown removes it alongside the plan-tune hooks.
const teardown = setup.slice(setup.indexOf('# Also tear down plan-tune'));
expect(teardown).toContain('remove-source --source gstack-timeline-stop');
});
test('setup surfaces a settings-hook refusal instead of swallowing it', () => {
// The hardened settings-hook refuses to rewrite a corrupt settings.json
// (exit 1). Both setup call sites (ALREADY_INSTALLED plan-tune re-point,
// timeline ensure-event) must stay non-fatal but PRINT the failure.
const setup = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
const warnings = setup.match(/settings hook update failed/g) || [];
expect(warnings.length).toBeGreaterThanOrEqual(2);
// The old swallow patterns are gone (the --no-team remove-source teardown
// legitimately keeps its 2>/dev/null; only the ensure-event registration
// must surface stderr).
expect(setup).not.toContain('_install_plan_tune_hooks >/dev/null 2>&1 || true');
expect(setup).not.toMatch(/ensure-event[\s\S]{0,220}--source gstack-timeline-stop[\s\S]{0,40}2>\/dev\/null/);
});
test('setup routes the Stop hook through ensure-event, not presence-only dedup', () => {
const setup = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
// ensure-event registers when missing AND re-points a stale path in place.
expect(setup).toMatch(/ensure-event[\s\S]{0,220}--source gstack-timeline-stop/);
// The old guard skipped registration whenever the source tag was merely
// PRESENT, so a stale absolute path (deleted dev worktree) was never
// re-pointed on a setup re-run.
expect(setup).not.toMatch(/list-sources 2>\/dev\/null \| grep -q "gstack-timeline-stop"/);
});
test('hook path resolution is canonical-only: global install or skip, never the worktree', () => {
// Drive setup's _hook_command_path directly: canonical install present →
// that path (survives deleting the worktree setup ran from). Absent →
// non-zero and NO output — registration is skipped with a log line; the
// running tree's path is NEVER baked into settings.json (the SOURCE
// fallback was the phantom-hooks defect and is deliberately gone).
const setup = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
const fn = setup.match(/_hook_command_path\(\) \{[\s\S]*?\n\}/);
expect(fn).not.toBeNull();
const fakeHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-hookpath-'));
try {
const canonicalRoot = path.join(fakeHome, '.claude', 'skills', 'gstack');
const globalHook = path.join(canonicalRoot, 'hosts', 'claude', 'hooks', 'timeline-stop-hook');
fs.mkdirSync(path.dirname(globalHook), { recursive: true });
fs.writeFileSync(globalHook, '#!/bin/sh\nexit 0\n', { mode: 0o755 });
const env = {
...process.env,
HOME: fakeHome,
SOURCE_GSTACK_DIR: '/some/dev/worktree',
CANONICAL_GSTACK_ROOT: canonicalRoot,
};
const withGlobal = spawnSync(
'bash',
['-c', `${fn![0]}\n_hook_command_path hosts/claude/hooks/timeline-stop-hook`],
{ env, encoding: 'utf-8', timeout: 10_000 },
);
expect(withGlobal.status).toBe(0);
expect(withGlobal.stdout.trim()).toBe(globalHook);
// No canonical install → the resolver FAILS (caller logs a visible
// skip); it never falls back to the setup-time tree.
fs.rmSync(globalHook);
const withoutGlobal = spawnSync(
'bash',
['-c', `${fn![0]}\n_hook_command_path hosts/claude/hooks/timeline-stop-hook`],
{ env, encoding: 'utf-8', timeout: 10_000 },
);
expect(withoutGlobal.status).not.toBe(0);
expect(withoutGlobal.stdout.trim()).toBe('');
} finally {
fs.rmSync(fakeHome, { recursive: true, force: true });
}
});
test('ensure-event re-points a stale absolute path and leaves exactly one registration', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ensure-'));
try {
const settingsFile = path.join(dir, 'settings.json');
fs.writeFileSync(settingsFile, JSON.stringify({
hooks: {
Stop: [{
_gstack_source: 'gstack-timeline-stop',
hooks: [{ type: 'command', command: '/deleted/worktree/hosts/claude/hooks/timeline-stop-hook', timeout: 5 }],
}],
},
}, null, 2) + '\n');
const r = spawnSync('bash', [
SETTINGS_HOOK, 'ensure-event',
'--event', 'Stop',
'--command', HOOK,
'--source', 'gstack-timeline-stop',
'--timeout', '5',
], { env: { ...process.env, GSTACK_SETTINGS_FILE: settingsFile }, encoding: 'utf-8', timeout: 15_000 });
expect(r.status).toBe(0);
expect(r.stdout).toContain('re-pointed');
const s = JSON.parse(fs.readFileSync(settingsFile, 'utf-8'));
expect(s.hooks.Stop).toHaveLength(1); // replaced in place — never two
expect(s.hooks.Stop[0].hooks[0].command).toBe(HOOK);
expect(s.hooks.Stop[0]._gstack_source).toBe('gstack-timeline-stop');
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('ensure-event is a true no-op when the registration already matches (no write, no backup churn)', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ensure-noop-'));
try {
const settingsFile = path.join(dir, 'settings.json');
const args = [
SETTINGS_HOOK, 'ensure-event',
'--event', 'Stop',
'--command', HOOK,
'--source', 'gstack-timeline-stop',
'--timeout', '5',
];
const env = { ...process.env, GSTACK_SETTINGS_FILE: settingsFile };
const first = spawnSync('bash', args, { env, encoding: 'utf-8', timeout: 15_000 });
expect(first.status).toBe(0);
const bytesAfterFirst = fs.readFileSync(settingsFile, 'utf-8');
const second = spawnSync('bash', args, { env, encoding: 'utf-8', timeout: 15_000 });
expect(second.status).toBe(0);
expect(second.stdout).toContain('unchanged');
expect(fs.readFileSync(settingsFile, 'utf-8')).toBe(bytesAfterFirst);
// Re-running ./setup must not accumulate settings.json.bak.<ts> files.
const baks = fs.readdirSync(dir).filter((f) => f.includes('.bak'));
expect(baks).toEqual([]);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('corrupt settings.json: ensure-event refuses (exit 3) and never rewrites the file', () => {
// The old catch{} folded an unparseable EXISTING settings.json into {}
// and the atomic write replaced the user's permissions/env/other hooks
// with just ours. Now: loud stderr error, fail-closed exit 3 (the
// settings-hook parse-refusal code), file byte-identical.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ensure-corrupt-'));
try {
const settingsFile = path.join(dir, 'settings.json');
const corrupt = '{ "permissions": { "allow": ["Bash(npm:*)"] }, INVALID';
fs.writeFileSync(settingsFile, corrupt);
const r = spawnSync('bash', [
SETTINGS_HOOK, 'ensure-event',
'--event', 'Stop',
'--command', HOOK,
'--source', 'gstack-timeline-stop',
'--timeout', '5',
], { env: { ...process.env, GSTACK_SETTINGS_FILE: settingsFile }, encoding: 'utf-8', timeout: 15_000 });
expect(r.status).toBe(3);
expect(r.stderr).toContain('not valid JSON');
// Never rewritten — the corrupt bytes (and whatever the user can still
// salvage from them) survive verbatim.
expect(fs.readFileSync(settingsFile, 'utf-8')).toBe(corrupt);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('a matcher change updates the tagged entry in place — still exactly one registration', () => {
// Identity key is (event, source): an existing gstack entry with a STALE
// matcher must be updated, never joined by a second entry (the old key
// included the matcher, so any future matcher change would duplicate).
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ensure-matcher-'));
try {
const settingsFile = path.join(dir, 'settings.json');
fs.writeFileSync(settingsFile, JSON.stringify({
hooks: {
PreToolUse: [{
_gstack_source: 'gstack-plan-tune',
matcher: 'OldMatcher',
hooks: [{ type: 'command', command: '/old/path/hook', timeout: 5 }],
}],
},
}, null, 2) + '\n');
const r = spawnSync('bash', [
SETTINGS_HOOK, 'ensure-event',
'--event', 'PreToolUse',
'--command', '/new/path/hook',
'--source', 'gstack-plan-tune',
'--matcher', 'NewMatcher',
'--timeout', '5',
], { env: { ...process.env, GSTACK_SETTINGS_FILE: settingsFile }, encoding: 'utf-8', timeout: 15_000 });
expect(r.status).toBe(0);
const s = JSON.parse(fs.readFileSync(settingsFile, 'utf-8'));
expect(s.hooks.PreToolUse).toHaveLength(1); // updated in place — never two
expect(s.hooks.PreToolUse[0].matcher).toBe('NewMatcher');
expect(s.hooks.PreToolUse[0].hooks[0].command).toBe('/new/path/hook');
expect(s.hooks.PreToolUse[0]._gstack_source).toBe('gstack-plan-tune');
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('a failed update leaves exactly one registration — never zero, never two', () => {
// Root can write through 0o555 directories, so the failure injection
// (read-only dir) does not bind there; the invariant is still covered by
// the atomic tmp+rename pinned in the re-point test above.
if (typeof process.getuid === 'function' && process.getuid() === 0) return;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ensure-fail-'));
try {
const settingsFile = path.join(dir, 'settings.json');
fs.writeFileSync(settingsFile, JSON.stringify({
hooks: {
Stop: [{
_gstack_source: 'gstack-timeline-stop',
hooks: [{ type: 'command', command: '/stale/path/timeline-stop-hook', timeout: 5 }],
}],
},
}, null, 2) + '\n');
fs.chmodSync(dir, 0o555); // every write path (backup, tmp, rename) fails
const r = spawnSync('bash', [
SETTINGS_HOOK, 'ensure-event',
'--event', 'Stop',
'--command', HOOK,
'--source', 'gstack-timeline-stop',
'--timeout', '5',
], { env: { ...process.env, GSTACK_SETTINGS_FILE: settingsFile }, encoding: 'utf-8', timeout: 15_000 });
fs.chmodSync(dir, 0o755);
expect(r.status).not.toBe(0); // the failure is loud, not swallowed
const s = JSON.parse(fs.readFileSync(settingsFile, 'utf-8'));
expect(s.hooks.Stop).toHaveLength(1); // old registration intact
expect(s.hooks.Stop[0].hooks[0].command).toBe('/stale/path/timeline-stop-hook');
} finally {
try { fs.chmodSync(dir, 0o755); } catch {}
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('gstack-uninstall removes the Stop hook registration', () => {
const uninstall = fs.readFileSync(path.join(ROOT, 'bin', 'gstack-uninstall'), 'utf-8');
expect(uninstall).toContain('remove-source --source gstack-timeline-stop');
});
test('the bash shim is fail-open: exits 0 even when bun is unavailable', () => {
const r = spawnSync('bash', [HOOK], {
input: '{}',
encoding: 'utf-8',
env: { HOME: tmpHome, PATH: '/usr/bin:/bin', GSTACK_HOME: tmpHome },
timeout: 15_000,
});
expect(r.status).toBe(0);
});
});