v1.43.2.0 fix wave: post-Daegu paper-cut — 18 fixes, 28 bisect commits (#1642)

* fix(gbrain-sync): --full produces an empty code index on first run of a new repo

`gbrain reindex-code` only RE-EMBEDS pages that already exist; it never walks
the filesystem. On a freshly-registered source (0 pages), a --full run that
called reindex-code alone found nothing ("No code pages to reindex"), finished
in ~1s, and left the code index permanently empty while still reporting OK.

Fix: --full now runs `sync --strategy code` FIRST to create pages via the file
walk, then runs `reindex-code` to honor the documented "full walk + reindex"
contract for both fresh and populated sources.

Contributed by @jetsetterfl via #1584.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(gbrain-local-status): classifier falsely reports broken-db inside repos with their own DATABASE_URL

The freshClassify probe ran `gbrain sources list --json` with the inherited
process env. When the probe ran from inside a repo with its own .env (an app
DATABASE_URL on a different port), Bun autoloaded the project's .env, gbrain
connected to the wrong database, and the classifier reported broken-db on
otherwise-healthy brains.

Fix: route the probe env through `buildGbrainEnv` from lib/gbrain-exec, the
same helper the sync orchestrator uses. DATABASE_URL is seeded from
~/.gbrain/config.json so the result is cwd-independent. The 60s cache can no
longer propagate a poisoned negative to clean directories.

Contributed by @jetsetterfl via #1583.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(retro): stale-base + bad-today-anchor pre-flight guard (#1624)

/retro silently produced confidently-wrong output when "today" drifted (model
session-context error) or when origin/<default> was materially behind the
actual remote — git log --since returned zero or near-zero commits and the
narrative was fabricated from nothing.

Adds Step 0.5 with four ordered pre-check branches before any window analysis:

  A. No 'origin' remote → skip with "base freshness not verified" note
  B. Detached HEAD → skip with "base freshness not verified" note
  C. `git fetch origin <default>` fails (offline) → warn, proceed against
     last-known origin/<default>
  D. Fetch succeeded → compare today vs latest origin/<default> commit; if
     gap > window-days, BLOCK with explicit citation of latest-commit date.

Skip paths still proceed to Step 1, but the disclosure is carried into the
retro narrative ("offline run, window not freshness-verified") so the output
is never silently confidently-wrong.

Atomic .tmpl + gen:skill-docs regen commit (T-Codex-3 pattern).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(retro): regression for #1624 stale-base pre-flight guard

13 static-invariant tests pinning the four ordered pre-check branches in
retro/SKILL.md.tmpl:Step 0.5:

  A. no-remote skip            — must check origin presence + set verdict
  B. detached-HEAD skip        — must gate behind prior verdict (ordering)
  C. fetch-fail warn           — must match `if !` or `||` shape, gate by verdict
  D. stale-base BLOCK          — must read latest-commit ISO date, cite remediation

Plus a disclosure-survives-to-narrative invariant: skip-path verdicts must be
named in prose so the retro output carries the cited reason rather than
silently misreporting.

Failing build if Step 0.5 is removed, branches re-ordered (no-remote no longer
wins), or the BLOCK message stops citing today/latest-commit/remediation
path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(gbrain-sync): configurable timeouts + resume from gbrain checkpoint (#1611)

The memory and code stages hardcoded a 35-min spawn timeout. On brains with
~2000+ staged files, /sync-gbrain --full reliably SIGTERM'd the child at
exactly 35 minutes with exit 143. gbrain left ~/.gbrain/import-checkpoint.json
pointing at the staging dir, but gstack-memory-ingest's SIGTERM handler
unconditionally cleaned the dir up — so the next run found a checkpoint
pointing at nothing and restaged from scratch, repeating the SIGTERM forever.

Three changes:

1. Configurable timeouts via env (bounds 60_000ms - 86_400_000ms, default
   2_100_000ms = 35min unchanged):
     GSTACK_SYNC_MEMORY_TIMEOUT_MS
     GSTACK_SYNC_CODE_TIMEOUT_MS
   Out-of-range or non-numeric values warn and fall back to the default.

2. SIGTERM in gstack-memory-ingest no longer always cleans up the staging
   dir. If gbrain has written ~/.gbrain/import-checkpoint.json pointing at
   the active staging dir, the dir is PRESERVED for next-run resume.
   Otherwise (no checkpoint pointing here, crash before gbrain ever
   touched it) it's cleaned up as before.

3. Next /sync-gbrain run detects gbrain's checkpoint via decideResume() in
   gstack-gbrain-sync.ts:
     - no checkpoint               → fresh ingest pass
     - checkpoint + staging ok     → set GSTACK_INGEST_RESUME_DIR; child
                                      reuses staging dir and skips
                                      writeStaged; gbrain import resumes
                                      from processedIndex+1
     - checkpoint + staging gone   → warn "previous checkpoint stale
                                      (staging dir gone), restaging from
                                      scratch" and proceed

Reuses gbrain's own checkpoint as the source of truth (D1 — no double-store
state). Detect-then-fallback semantics per C1.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(gbrain-sync): regression for #1611 timeouts + resume

19 tests across three surfaces:

  - resolveStageTimeoutMs (10 tests): undefined/empty → default; non-numeric,
    zero, negative, below-floor, above-ceiling → warn + default; at-floor,
    at-ceiling, valid mid-range → accepted as-is.

  - decideResume (6 tests): no checkpoint, corrupt JSON, checkpoint + staging
    ok, checkpoint + staging missing, checkpoint with no dir, checkpoint with
    empty dir.

  - SIGTERM staging preservation (3 static invariants): memory-ingest signal
    handler must check stagingDirIsCheckpointed BEFORE cleanup; preserve
    branch must come before cleanup branch (ordering); orchestrator must
    pass GSTACK_INGEST_RESUME_DIR to the grandchild on resume.

Also threads process.env.HOME through readGbrainCheckpoint and
stagingDirIsCheckpointed so tests can redirect home. os.homedir() caches
at process start and ignores later mutation, so the env override is the
only reliable test injection point.

Failing build if the timeout bounds are removed, the resume detection
short-circuits incorrectly, or the SIGTERM handler regresses to
unconditional cleanup.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(review): pre-emit verification gate kills Django-shape FP class (#1539)

External user filed 4/8 false positives on a /review run against a Django +
DRF + PostgreSQL repo (Sprint 2.5). Every FP class was the same shape:
"resolvable in <5 minutes by viewing the actual code or running a simple
grep" — fields that don't exist on the model, dict.get()-might-be-None on a
form that returns {}-initialized cleaned_data, standard ORM save behavior
called out as data loss.

Extends the Confidence Calibration resolver (consumed by review, cso,
plan-eng-review, ship) with a Pre-emit verification gate:

  Every finding MUST quote the specific code line that motivates it
  (file:line + verbatim text). If the reviewer cannot produce the quote,
  the finding is unverified — its confidence is forced to 4-5 so the
  existing "Suppress from main report" rule fires automatically. The
  finding still goes to the appendix for calibration audit, but the user
  does not see it in the critical-pass output.

Reuses the existing suppression mechanism — no new code path. The FP
classes the gate kills are enumerated in the resolver text so reviewers
see the named patterns.

Framework-meta nudge included for Django Meta, Rails associations,
SQLAlchemy relationships, TypeORM decorators, Sequelize init, Prisma
generated client — the reviewer must quote the meta-construct that
generates the symbol, not just grep for the literal name. Deeper
framework-aware ORM verification (model introspection, migration-history-
aware checks) is deliberately deferred to a future wave per T-Codex-2.

Atomic .tmpl-equivalent (resolver) edit + gen:skill-docs regen commit
per T-Codex-3.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(review): regression for #1539 pre-emit verification gate

12 tests pinning the gate behavior:

  - Resolver emits the gate header + #1539 reference
  - Gate requires quoting file:line + verbatim text
  - Unverified findings forced to confidence 4-5 (auto-suppress via
    existing <7-rule, no new mechanism)
  - Framework-meta nudge names Django, Rails, SQLAlchemy, TypeORM,
    Sequelize, Prisma
  - Deferred design doc reference present (1539-framework-aware-review.md)
  - Four named FP classes from #1539 enumerated:
      * field doesn't exist on model
      * dict.get() might be None
      * save() might lose fields
      * update_fields might miss X
  - All four downstream SKILL.md consumers (review, cso, plan-eng-review,
    ship) carry the gate text after gen:skill-docs
  - Existing confidence 9-10 'Show normally' + 3-4 'Suppress' rows
    unchanged (regression on existing behavior)

Failing build if the gate is removed, the suppression mechanism is
re-invented separately, the framework-meta nudge drops a framework, or
gen:skill-docs stops propagating the gate to consumers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(config): expose explain_level default

* fix(benchmark): parse positional prompt after flags

* fix(artifacts): reject malformed remote paths

* fix(learnings): preserve current entries in cross-project search

* fix(setup): register root gstack slash alias

* fix(memory): probe gitleaks without shell builtin

* fix(gbrain-lib): pin LC_ALL=C in varname validator (macOS locale guard)

In many macOS shells the default locale (e.g. en_US.UTF-8) makes bash
glob brackets like `[A-Z]` match lowercase letters too, so the existing
`case "$name" in [A-Z_][A-Z0-9_]*)` branch lets names like `lower-case`
through validation. The function then trips `printf -v "$varname"` and
`export "$varname"` with `not a valid identifier` errors that surface
mid-prompt, which is exactly what the validator was supposed to prevent.

Pinning `LC_ALL=C` inside the function gives ASCII-only bracket semantics
on both macOS and Linux, matching the documented `[A-Z_][A-Z0-9_]*`
contract. Declared `local` so it doesn't leak to the calling shell —
`gstack-gbrain-lib.sh` is documented as a sourced helper, so a bare
assignment would mutate the caller's locale for the rest of the process
(silently affecting downstream `sort`, `tr`, locale-aware globs in the
same shell, etc.).

The existing regression test
`test/gbrain-lib-verify.test.ts:'rejects invalid var names'`
already covers the macOS repro shape (passes `lower-case` and expects
the validator to reject + emit `invalid var name`). On Linux CI the
test silently passed because `LC_ALL=C` is the typical default; on
macOS dev boxes it fails.

Verified:
- `bun test test/gbrain-lib-verify.test.ts`: 22 pass, 0 fail (on macOS).
- `_gstack_gbrain_validate_varname lower-case; echo $?` → 2.
- `_gstack_gbrain_validate_varname FOO_BAR; echo $?` → 0.
- Caller's LC_ALL preserved across calls (confirmed via sourced bash).

* fix(land-and-deploy): detect merged PR after gh failure

After `gh pr merge` exits non-zero, the PR may already be MERGED server-side
(concurrent merge landed, or local cleanup phase failed AFTER the merge
succeeded). Calling `gh pr merge` a second time then errors with a confusing
"already merged" — and worse, the deploy workflow never runs because we
stopped on the first failure.

Adds a Post-failure PR-state check (§4a-postfail) that runs after ANY
non-zero exit from `gh pr merge`:

  - state == MERGED  → record MERGE_PATH=direct, OFFER (don't force)
                       stale-worktree cleanup on the base branch with
                       uncommitted-work guard, proceed to §4a CI watch
  - state == OPEN    → check autoMergeRequest; if non-null treat as
                       merge-queue wait; if null surface both errors and STOP
  - state == CLOSED  → STOP

Hard invariant: never retry `gh pr merge` after a non-zero exit. Server
state is authoritative.

Re-authored from PR #1620 into land-and-deploy/SKILL.md.tmpl (the source of
truth) instead of the generated SKILL.md, so the next gen:skill-docs run
preserves the change. Original diff by @davidfoy via #1620.

Related: cli/cli#3442, cli/cli#13380.

Contributed by @davidfoy via #1620.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: detect PgBouncer transaction-mode pooler and set GBRAIN_PREPARE=true (#1435)

When gbrain connects through a PgBouncer transaction-mode pooler (port
6543), it auto-disables prepared statements. This breaks `gbrain search`
silently — the /sync-gbrain capability check fails and the GBrain Search
Guidance block never gets written to CLAUDE.md.

Three-layer fix:

1. **lib/gbrain-exec.ts** — `buildGbrainEnv()` now detects port 6543 in
   the effective DATABASE_URL and sets `GBRAIN_PREPARE=true` in the env
   passed to every gbrain spawn. This is the single chokepoint — all
   gstack gbrain invocations inherit the fix. Caller can opt out with
   `GBRAIN_PREPARE=false`.

2. **sync-gbrain/SKILL.md{,.tmpl}** — capability check now exports
   `GBRAIN_PREPARE=true` explicitly and retries search up to 3x with 1s
   delay for async index propagation under connection pooling.

3. **bin/gstack-gbrain-detect** — surfaces `gbrain_pooler_mode` field
   ("transaction" | "session" | null) in the preamble probe JSON so
   /setup-gbrain and /sync-gbrain can advise users about pooler state.

Closes #1435

Built with [ClosedLoop.AI](https://closedloop.ai) | [GitHub](https://github.com/closedloop-ai/claude-plugins)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(supabase-provision): rewrite transaction/6543 -> session/5432 for new projects

- Single-object pooler API responses default to transaction-mode at 6543,
  but the shared pooler tenant on new projects only listens on session/5432
- Add a `pool_mode == transaction && db_port == 6543` rewrite + stderr note
- Escape hatch via `GSTACK_SUPABASE_TRUST_API_PORT=1` for forward-compat
- 5 new tests covering rewrite, no-op shapes, env opt-out, array path

Fixes #1301.

* fix(browse): GSTACK_CHROMIUM_NO_SANDBOX opt-out for Ubuntu/AppArmor (#1562)

Ubuntu/AppArmor configurations often block unprivileged Chromium sandboxing
for headless agent sessions even for normal users — /qa hangs without
--no-sandbox. The kernel policy denies the unprivileged user namespaces
Chromium needs.

Adds GSTACK_CHROMIUM_NO_SANDBOX=1 as an explicit user override that forces
the sandbox off without changing the default for everyone else. Re-authored
from PR #1562 onto v1.42.2.0's shouldEnableChromiumSandbox() helper —
purely additive, preserves the headed-launch sandbox-on-by-default behavior
that v1.42.2.0 shipped to kill the --no-sandbox yellow infobar.

Three new regression tests cover:
  - linux + override=1 → false (the named use case)
  - darwin + override=1 → false (env wins on any platform)
  - override=0 → does NOT trigger (must be exactly "1")

Original diff by @techcenter68 via #1562.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(browse): mirror isCustomChromium() guard in headless launch()

When BROWSE_EXTENSIONS_DIR is set alongside GSTACK_CHROMIUM_PATH pointing
at a baked-extension build (GBrowser / GStack Browser), the headless launch()
path was unconditionally adding --disable-extensions-except / --load-extension.
This causes the same ServiceWorkerState::SetWorkerId DCHECK crash that
launchHeaded() already guards against via isCustomChromium().

Mirror the existing guard: skip --load-extension flags when isCustomChromium()
returns true; always push the off-screen window geometry args.

* fix(browse): daemonize macOS/Linux server via setsid()

`Bun.spawn().unref()` only releases the child from Bun's event loop —
it does NOT call setsid(). The spawned bun server inherits the spawning
shell's process session. When the CLI runs inside a session-managed shell
that exits shortly after the CLI returns (Claude Code's per-command Bash
sandbox, Conductor, OpenClaw, CI step runners), the session leader's exit
sends SIGHUP to every PID in the session — killing the bun server and
its Chromium grandchildren within seconds of a successful `connect`.

Setting `BROWSE_PARENT_PID=0` (already done by the `connect` command and
pair-agent) disables the parent-process watchdog but does NOT save the
server here: SIGHUP from session teardown still reaps it.

Replace the macOS/Linux `Bun.spawn().unref()` with Node's
`child_process.spawn({ detached: true })`, which calls setsid() and
gives the server its own session leader role (PPID=1, STAT=Ss). This
mirrors the Windows path's rationale (PR #191 by @fqueiro) — same root
cause, different OS surface.

Verified on macOS in Conductor: pre-fix the server dies ~10–15s after
connect across separate Bash invocations; post-fix the same PID stays
alive (PPID=1, SESS=0, STAT=Ss) and responds to `status`/`goto`/
`snapshot` across many separate shell calls.

The `proc?.stderr` startup-error branch is removed since both platforms
now spawn with `stdio: 'ignore'`; both fall through to the on-disk
`browse-startup-error.log` written by `server.ts`'s start().catch.

* fix(design): bump image-gen timeout to 240s + pin gpt-image-2

The design binary calls /v1/responses (gpt-4o + image_generation tool,
quality:high, 1536x1024) but aborted the request after a hardcoded 120s.
That class of request consistently takes ~140-160s end-to-end, so every
generate/variants/evolve/iterate call aborted before the image returned.

In /design-shotgun this cascades: Step 3c launches N parallel agents,
each calling `$D generate`, each aborts at 120s and retries, all fail,
the comparison board never opens — the skill appears to hang indefinitely.

Reproduced the exact API call with a longer budget: HTTP 200, valid
image, 143.5s. A real /design-shotgun run after the patch generated 3
variants in parallel at 150.0s / 161.0s / 152.1s, all exit 0 — note the
161s case, which a naive 150s bump would still have failed.

- Bump AbortController timeout 120_000 -> 240_000 in generate.ts,
  variants.ts, evolve.ts, iterate.ts (both call sites)
- Pin the image_generation tool to model "gpt-image-2"

design/test/variants-retry-after.test.ts: 5 pass, 0 fail. The
feedback-roundtrip.test.ts failures are a pre-existing browse-module
breakage (session.clearLoadedHtml undefined), unrelated to this change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test: fill coverage gaps for PRs #1606, #1612, #1620

Three cherry-picked PRs in this wave landed without unit-test coverage for
the specific invariant they protect:

  #1606 (@andrey-esipov) — LC_ALL=C pin in _gstack_gbrain_validate_varname
    8 tests by sourcing bin/gstack-gbrain-lib.sh and calling the validator
    directly. Asserts uppercase/digit/underscore accepted, lowercase
    REJECTED (the macOS-locale regression case), mixed-case rejected,
    LC_ALL=C scoping is local (doesn't leak to caller).

  #1612 (@bharat2913) — setsid daemonize via Node child_process.spawn
    4 static-invariant tests on browse/src/cli.ts. The actual setsid
    syscall is hard to assert without a real spawn, so we pin the source
    shape: nodeSpawn imported from child_process; non-Windows branch uses
    nodeSpawn(...) with detached:true and .unref(); comment documents
    setsid/SIGHUP root cause; Bun.spawn() is NOT used on macOS/Linux.

  #1620 (@davidfoy, re-authored into .tmpl per A3) — §4a-postfail
    12 static invariants on land-and-deploy/SKILL.md.tmpl + generated
    SKILL.md. Pins all three state branches (MERGED/OPEN/CLOSED), the
    authoritative state query, the merge-SHA capture, non-destructive
    worktree cleanup with uncommitted-work guard, autoMergeRequest probe
    on OPEN, hard "never retry gh pr merge" rule, and atomic regen
    propagation.

Failing build if any of the three invariants regresses.

Note: gbrain-lib-validate-varname.test.ts also surfaces a pre-existing
glob-pattern overpermissiveness (hyphens + dots accepted) — not in
#1606's scope; documented inline as a separate cleanup target.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(learnings): align injection-prevention tests with PR #1619 tagged-line shape

PR #1619 (preserve current entries in cross-project search) refactored
gstack-learnings-search to tag rows inline (`current\t<json>` vs
`cross\t<json>`) instead of filtering inside the bun block via
process.env.GSTACK_SEARCH_SLUG. The bun block no longer reads SLUG or
CROSS env vars — it parses the per-line tag and sets a per-entry
_crossProject flag.

The pre-existing test/learnings-injection.test.ts still asserted on the
old SLUG + CROSS env var shape. Updates:

  - Remove the SLUG env var assertion (no longer set on bash command line)
  - Remove the bun-block CROSS env var assertion (block reads the tag now,
    not the env)
  - Add a new positive assertion that the bun block parses the tag
    (sourceTag | tabIndex | crossProject)
  - Keep the shell-interpolation safety assertion unchanged — that's
    independent of the SLUG refactor

The CROSS env var is still SET on the bash command line (it controls
whether the cross-project find runs at all), but the bun child no longer
reads it. The existing "env vars set on bash command line" test continues
to pin that.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(fixtures): regenerate ship-SKILL.md golden baselines

ship/SKILL.md consumes the Confidence Calibration resolver via the
preamble pipeline. This wave's #1539 pre-emit verification gate extends
the resolver text, which propagated to ship/SKILL.md via gen:skill-docs.
The golden fixtures in test/fixtures/golden/ matched the pre-#1539 shape
and failed the host-config regression check.

Refreshes claude-ship-SKILL.md, codex-ship-SKILL.md, and factory-ship-SKILL.md
to match the current generated output. Matches the Daegu wave's bisect
commit 23 ("test(fixtures): regenerate ship-SKILL.md golden baselines").

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(gbrain-detect): include gbrain_pooler_mode in schema regression (PR #1591)

PR #1591 (PgBouncer transaction-mode detection, @mikeangstadt) added
gbrain_pooler_mode to the gstack-gbrain-detect JSON output but did not
update the schema regression check in
test/gstack-gbrain-detect-mcp-mode.test.ts. Adding the key in alphabetical
order matching the rest of the schema array. Downstream sync-gbrain ignores
unknown keys, so this is forward-compat.

Without this, the test fails with a diff:
  + "gbrain_pooler_mode"
because keys is the actual set returned and the expected array was
pre-#1591.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(release): v1.43.0.0 — post-Daegu paper-cut wave

Bumps VERSION 1.42.2.0 → 1.43.0.0 (MINOR per scale-aware bump rules: new
env-var surface GSTACK_SYNC_*_TIMEOUT_MS + GSTACK_CHROMIUM_NO_SANDBOX,
behavior expansion in browse/src/browser-manager.ts headless launch,
three skill-template prompt changes affecting /retro, /review,
/sync-gbrain).

CHANGELOG entry leads with what stopped happening: /retro stops
fabricating retros against stale bases, /sync-gbrain stops SIGTERM-looping
35-min restarts on big brains, /review stops shipping framework FPs the
reviewer never grep'd.

18 fixes total — 15 community PRs + 3 self-filed silent-failure issues
(#1624, #1611, #1539) — in one bundled PR with 26 bisect commits and 7
new regression test files. Every wave-touched test file passes in
isolation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(release): bump v1.43.0.0 → v1.43.2.0 for queue collision

CI check-version-stale flagged v1.43.0.0 already claimed by PR #1574
(garrytan/colombo-v3). PR #1639 (garrytan/muscat-v3) claims v1.43.1.0.
Next available MINOR slot is v1.43.2.0.

Bump VERSION + package.json + CHANGELOG entry header. No behavior
changes — purely re-versioning to clear the queue collision.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Jayesh Betala <jayesh.betala7@gmail.com>
Co-authored-by: Andrey Esipov <andrey.esipov@outlook.com>
Co-authored-by: David Foy <davidfoy@users.noreply.github.com>
Co-authored-by: mikeangstadt <mike.angstadt@closedloop.ai>
Co-authored-by: 0xDevNinja <manmit0x@gmail.com>
Co-authored-by: techcenter68 <techcenter68@users.noreply.github.com>
Co-authored-by: shohu <shohu33@gmail.com>
Co-authored-by: Bharat <bharat@theysaid.io>
Co-authored-by: Matteo Hertel <info@matteohertel.com>
This commit is contained in:
Garry Tan
2026-05-21 21:21:07 -07:00
committed by GitHub
parent 65972f6a15
commit 66f3a180d3
55 changed files with 2316 additions and 131 deletions
+27
View File
@@ -163,6 +163,33 @@ describe('gstack-model-benchmark prompt resolution', () => {
}
});
test('positional file still works when value flags come first', () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bench-prompt-'));
const promptFile = path.join(tmp, 'prompt.txt');
fs.writeFileSync(promptFile, 'hello after flags');
try {
const r = run(['--models', 'claude', '--output', 'json', promptFile, '--dry-run']);
expect(r.status).toBe(0);
expect(r.stdout).toContain('hello after flags');
expect(r.stdout).not.toContain('EISDIR');
} finally {
fs.rmSync(tmp, { recursive: true, force: true });
}
});
test('positional file still works after equals-form value flags', () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bench-prompt-'));
const promptFile = path.join(tmp, 'prompt.txt');
fs.writeFileSync(promptFile, 'hello after equals flags');
try {
const r = run(['--models=claude', '--output=markdown', promptFile, '--dry-run']);
expect(r.status).toBe(0);
expect(r.stdout).toContain('hello after equals flags');
} finally {
fs.rmSync(tmp, { recursive: true, force: true });
}
});
test('positional non-file arg is treated as inline prompt', () => {
const r = run(['treat-me-as-inline', '--dry-run']);
expect(r.status).toBe(0);
+71 -1
View File
@@ -15,7 +15,7 @@ import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { buildGbrainEnv } from "../lib/gbrain-exec";
import { buildGbrainEnv, isTransactionModePooler } from "../lib/gbrain-exec";
describe("buildGbrainEnv", () => {
let home: string;
@@ -117,4 +117,74 @@ describe("buildGbrainEnv", () => {
const result = buildGbrainEnv({ baseEnv });
expect(result.DATABASE_URL).toBe("postgresql://gbrain/db");
});
// --- GBRAIN_PREPARE auto-detection (#1435) ---
it("sets GBRAIN_PREPARE=true when DATABASE_URL targets port 6543 (transaction-mode pooler)", () => {
const poolerUrl = "postgresql://postgres.abc:pw@aws-0-us-east-1.pooler.supabase.com:6543/postgres";
writeFileSync(join(gbrainHome, "config.json"), JSON.stringify({ database_url: poolerUrl }));
const baseEnv = { HOME: home };
const result = buildGbrainEnv({ baseEnv });
expect(result.DATABASE_URL).toBe(poolerUrl);
expect(result.GBRAIN_PREPARE).toBe("true");
});
it("does not set GBRAIN_PREPARE when DATABASE_URL targets port 5432 (session-mode pooler)", () => {
const sessionUrl = "postgresql://postgres.abc:pw@aws-0-us-east-1.pooler.supabase.com:5432/postgres";
writeFileSync(join(gbrainHome, "config.json"), JSON.stringify({ database_url: sessionUrl }));
const baseEnv = { HOME: home };
const result = buildGbrainEnv({ baseEnv });
expect(result.GBRAIN_PREPARE).toBeUndefined();
});
it("does not set GBRAIN_PREPARE for pglite (no port in URL)", () => {
writeFileSync(join(gbrainHome, "config.json"), JSON.stringify({ database_url: "postgresql://gbrain/db" }));
const baseEnv = { HOME: home };
const result = buildGbrainEnv({ baseEnv });
expect(result.GBRAIN_PREPARE).toBeUndefined();
});
it("respects caller's explicit GBRAIN_PREPARE=false (opt-out)", () => {
const poolerUrl = "postgresql://postgres.abc:pw@aws-0-us-east-1.pooler.supabase.com:6543/postgres";
writeFileSync(join(gbrainHome, "config.json"), JSON.stringify({ database_url: poolerUrl }));
const baseEnv = { HOME: home, GBRAIN_PREPARE: "false" };
const result = buildGbrainEnv({ baseEnv });
expect(result.GBRAIN_PREPARE).toBe("false");
});
it("sets GBRAIN_PREPARE even when caller DATABASE_URL already matches config on port 6543", () => {
const poolerUrl = "postgresql://postgres.abc:pw@aws-0-us-east-1.pooler.supabase.com:6543/postgres";
writeFileSync(join(gbrainHome, "config.json"), JSON.stringify({ database_url: poolerUrl }));
const baseEnv = { HOME: home, DATABASE_URL: poolerUrl };
const result = buildGbrainEnv({ baseEnv });
expect(result.GBRAIN_PREPARE).toBe("true");
});
});
describe("isTransactionModePooler", () => {
it("returns true for Supabase transaction-mode pooler URL (port 6543)", () => {
expect(isTransactionModePooler(
"postgresql://postgres.abc:pw@aws-0-us-east-1.pooler.supabase.com:6543/postgres"
)).toBe(true);
});
it("returns false for session-mode pooler URL (port 5432)", () => {
expect(isTransactionModePooler(
"postgresql://postgres.abc:pw@aws-0-us-east-1.pooler.supabase.com:5432/postgres"
)).toBe(false);
});
it("returns false for pglite-style URL (no port)", () => {
expect(isTransactionModePooler("postgresql://gbrain/db")).toBe(false);
});
it("returns false for unparseable URL", () => {
expect(isTransactionModePooler("not-a-url")).toBe(false);
});
it("handles postgres:// scheme (without 'ql')", () => {
expect(isTransactionModePooler(
"postgres://postgres.abc:pw@host:6543/postgres"
)).toBe(true);
});
});
+30 -5
View File
@@ -46,6 +46,14 @@ function scanDocsForConfigKeys(): { docPath: string; key: string; line: number }
return hits;
}
function runConfig(args: string[], tmpHome: string) {
return spawnSync(CONFIG_BIN, args, {
encoding: 'utf-8',
env: { ...process.env, HOME: tmpHome, GSTACK_HOME: tmpHome },
timeout: 5000,
});
}
describe('docs ↔ gstack-config key drift guard', () => {
test('docs/ references at least one config key (smoke)', () => {
const hits = scanDocsForConfigKeys();
@@ -65,15 +73,32 @@ describe('docs ↔ gstack-config key drift guard', () => {
// without a Git Bash interpreter shim. Skip on Windows — the deprecated-key
// denylist test above already pins the v1.27.0.0 rename behavior at the
// doc layer, which is the actual invariant this wave defends.
test.skipIf(process.platform === 'win32')('`explain_level` is exposed as a documented default', () => {
const tmpHome = fs.mkdtempSync(path.join(require('os').tmpdir(), 'gstack-cfg-'));
try {
const get = runConfig(['get', 'explain_level'], tmpHome);
expect(get.status).toBe(0);
expect(get.stdout.trim()).toBe('default');
const defaults = runConfig(['defaults'], tmpHome);
expect(defaults.status).toBe(0);
expect(defaults.stdout).toContain('explain_level:');
expect(defaults.stdout).toContain('default');
const list = runConfig(['list'], tmpHome);
expect(list.status).toBe(0);
expect(list.stdout).toContain('explain_level:');
expect(list.stdout).toContain('default');
} finally {
fs.rmSync(tmpHome, { recursive: true, force: true });
}
});
test.skipIf(process.platform === 'win32')('`gstack-config get artifacts_sync_mode` returns a value (the rename landed)', () => {
// Run from a clean HOME so the user's local config doesn't pollute.
const tmpHome = fs.mkdtempSync(path.join(require('os').tmpdir(), 'gstack-cfg-'));
try {
const result = spawnSync(CONFIG_BIN, ['get', 'artifacts_sync_mode'], {
encoding: 'utf-8',
env: { ...process.env, HOME: tmpHome, GSTACK_HOME: tmpHome },
timeout: 5000,
});
const result = runConfig(['get', 'artifacts_sync_mode'], tmpHome);
expect(result.status).toBe(0);
// A known key returns its default value, not the "unknown key" error string.
expect(result.stderr).not.toContain('not recognized');
+37
View File
@@ -1921,6 +1921,43 @@ Example:
\`[P1] (confidence: 9/10) app/models/user.rb:42 — SQL injection via string interpolation in where clause\`
\`[P2] (confidence: 5/10) app/controllers/api/v1/users_controller.rb:18 — Possible N+1 query, verify with production logs\`
### Pre-emit verification gate (#1539 — kills the "field doesn't exist" FP class)
Before any finding is promoted to the report, the gate requires:
1. **Quote the specific code line that motivates the finding** — file:line plus
the verbatim text of the line(s) that triggered it. If the finding is "field
X doesn't exist on model Y", quote the lines of class Y where the field
would live. If "dict.get() might return None", quote the dict initialization.
If "race condition between A and B", quote both A and B.
2. **If you cannot quote the motivating line(s), the finding is unverified.**
Force its confidence to 4-5 (suppressed from the main report). It still goes
into the appendix so reviewers can audit calibration, but the user does NOT
see it in the critical-pass output. Do not work around this by inventing
speculative confidence 7+ — that defeats the gate.
**Framework-meta nudge:** When the symbol is generated by a framework
metaclass, descriptor, ORM Meta inner-class, or migration history (Django
`Meta`, Rails `has_many`/`scope`, SQLAlchemy `relationship`/`Column`,
TypeORM decorators, Sequelize `init`/`belongsTo`, Prisma generated client),
quote the meta-construct (the `Meta` block, the migration, the decorator,
the schema file) instead of expecting the literal name in the class body.
The verification is "I read the source that creates this symbol", not "I
grep'd for the name and didn't find it." Deeper framework-aware verification
(model introspection, migration-history-aware checks, ORM dialect detection)
is deliberately out of scope for the lighter gate — see the deferred
`~/.gstack-dev/plans/1539-framework-aware-review.md` design doc.
The FP classes the gate kills (measured against Django Sprint 2.5 #1539):
| FP class | Why the gate catches it |
|---|---|
| "field doesn't exist on model" | Requires quoting the model class body or Meta; the field's absence becomes obvious |
| "dict.get() might be None" | Requires quoting the dict initialization (e.g. Django form's `cleaned_data` is `{}`-initialized) |
| "save() might lose fields" | Requires quoting the ORM signature or model definition |
| "update_fields might miss X" | Requires quoting the field set; if X doesn't exist, the FP is self-evident |
**Calibration learning:** If you report a finding with confidence < 7 and the user
confirms it IS a real issue, that is a calibration event. Your initial confidence was
too low. Log the corrected pattern as a learning so future reviews catch it with
+37
View File
@@ -1883,6 +1883,43 @@ Example:
\`[P1] (confidence: 9/10) app/models/user.rb:42 — SQL injection via string interpolation in where clause\`
\`[P2] (confidence: 5/10) app/controllers/api/v1/users_controller.rb:18 — Possible N+1 query, verify with production logs\`
### Pre-emit verification gate (#1539 — kills the "field doesn't exist" FP class)
Before any finding is promoted to the report, the gate requires:
1. **Quote the specific code line that motivates the finding** — file:line plus
the verbatim text of the line(s) that triggered it. If the finding is "field
X doesn't exist on model Y", quote the lines of class Y where the field
would live. If "dict.get() might return None", quote the dict initialization.
If "race condition between A and B", quote both A and B.
2. **If you cannot quote the motivating line(s), the finding is unverified.**
Force its confidence to 4-5 (suppressed from the main report). It still goes
into the appendix so reviewers can audit calibration, but the user does NOT
see it in the critical-pass output. Do not work around this by inventing
speculative confidence 7+ — that defeats the gate.
**Framework-meta nudge:** When the symbol is generated by a framework
metaclass, descriptor, ORM Meta inner-class, or migration history (Django
`Meta`, Rails `has_many`/`scope`, SQLAlchemy `relationship`/`Column`,
TypeORM decorators, Sequelize `init`/`belongsTo`, Prisma generated client),
quote the meta-construct (the `Meta` block, the migration, the decorator,
the schema file) instead of expecting the literal name in the class body.
The verification is "I read the source that creates this symbol", not "I
grep'd for the name and didn't find it." Deeper framework-aware verification
(model introspection, migration-history-aware checks, ORM dialect detection)
is deliberately out of scope for the lighter gate — see the deferred
`~/.gstack-dev/plans/1539-framework-aware-review.md` design doc.
The FP classes the gate kills (measured against Django Sprint 2.5 #1539):
| FP class | Why the gate catches it |
|---|---|
| "field doesn't exist on model" | Requires quoting the model class body or Meta; the field's absence becomes obvious |
| "dict.get() might be None" | Requires quoting the dict initialization (e.g. Django form's `cleaned_data` is `{}`-initialized) |
| "save() might lose fields" | Requires quoting the ORM signature or model definition |
| "update_fields might miss X" | Requires quoting the field set; if X doesn't exist, the FP is self-evident |
**Calibration learning:** If you report a finding with confidence < 7 and the user
confirms it IS a real issue, that is a calibration event. Your initial confidence was
too low. Log the corrected pattern as a learning so future reviews catch it with
+37
View File
@@ -1912,6 +1912,43 @@ Example:
\`[P1] (confidence: 9/10) app/models/user.rb:42 — SQL injection via string interpolation in where clause\`
\`[P2] (confidence: 5/10) app/controllers/api/v1/users_controller.rb:18 — Possible N+1 query, verify with production logs\`
### Pre-emit verification gate (#1539 — kills the "field doesn't exist" FP class)
Before any finding is promoted to the report, the gate requires:
1. **Quote the specific code line that motivates the finding** — file:line plus
the verbatim text of the line(s) that triggered it. If the finding is "field
X doesn't exist on model Y", quote the lines of class Y where the field
would live. If "dict.get() might return None", quote the dict initialization.
If "race condition between A and B", quote both A and B.
2. **If you cannot quote the motivating line(s), the finding is unverified.**
Force its confidence to 4-5 (suppressed from the main report). It still goes
into the appendix so reviewers can audit calibration, but the user does NOT
see it in the critical-pass output. Do not work around this by inventing
speculative confidence 7+ — that defeats the gate.
**Framework-meta nudge:** When the symbol is generated by a framework
metaclass, descriptor, ORM Meta inner-class, or migration history (Django
`Meta`, Rails `has_many`/`scope`, SQLAlchemy `relationship`/`Column`,
TypeORM decorators, Sequelize `init`/`belongsTo`, Prisma generated client),
quote the meta-construct (the `Meta` block, the migration, the decorator,
the schema file) instead of expecting the literal name in the class body.
The verification is "I read the source that creates this symbol", not "I
grep'd for the name and didn't find it." Deeper framework-aware verification
(model introspection, migration-history-aware checks, ORM dialect detection)
is deliberately out of scope for the lighter gate — see the deferred
`~/.gstack-dev/plans/1539-framework-aware-review.md` design doc.
The FP classes the gate kills (measured against Django Sprint 2.5 #1539):
| FP class | Why the gate catches it |
|---|---|
| "field doesn't exist on model" | Requires quoting the model class body or Meta; the field's absence becomes obvious |
| "dict.get() might be None" | Requires quoting the dict initialization (e.g. Django form's `cleaned_data` is `{}`-initialized) |
| "save() might lose fields" | Requires quoting the ORM signature or model definition |
| "update_fields might miss X" | Requires quoting the field set; if X doesn't exist, the FP is self-evident |
**Calibration learning:** If you report a finding with confidence < 7 and the user
confirms it IS a real issue, that is a calibration event. Your initial confidence was
too low. Log the corrected pattern as a learning so future reviews catch it with
+98
View File
@@ -0,0 +1,98 @@
/**
* Coverage for #1606 `_gstack_gbrain_validate_varname` LC_ALL=C pin.
*
* Without the `local LC_ALL=C`, macOS default locale (en_US.UTF-8) makes
* `case "$name" in [A-Z_][A-Z0-9_]*)` match lowercase letters too
* lower-case identifiers pass validation and then trip `printf -v "$varname"`
* with "not a valid identifier" the caller can't distinguish from other
* failures.
*
* Tests exercise the validator by sourcing bin/gstack-gbrain-lib.sh and
* calling _gstack_gbrain_validate_varname directly. Asserts:
* - Valid uppercase identifiers accepted (return 0)
* - Lowercase identifiers REJECTED (return 2) pre-#1606 regression case
* - Mixed-case rejected
* - Empty name rejected
* - Names starting with digit rejected
* - Underscore prefix accepted
* - LC_ALL=C does not leak to caller (local scope preserved)
*/
import { describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import * as path from "node:path";
const ROOT = path.resolve(import.meta.dir, "..");
const LIB = path.join(ROOT, "bin", "gstack-gbrain-lib.sh");
function runValidator(name: string): { status: number | null } {
// Source the lib then run the validator against the input. Use bash -c with
// single-quoted body to avoid double interpolation. LANG=en_US.UTF-8 set
// explicitly so the test catches the macOS locale FP case even when CI's
// default locale would mask it.
const result = spawnSync(
"bash",
["-c", `. "${LIB}"; _gstack_gbrain_validate_varname "$1"`, "bash", name],
{
encoding: "utf-8",
timeout: 5000,
env: { ...process.env, LANG: "en_US.UTF-8", LC_ALL: "en_US.UTF-8" },
},
);
return { status: result.status };
}
describe("#1606 _gstack_gbrain_validate_varname — LC_ALL=C pin", () => {
test("ACCEPTS uppercase identifier (canonical happy path)", () => {
expect(runValidator("DATABASE_URL").status).toBe(0);
});
test("ACCEPTS uppercase + digits + underscores", () => {
expect(runValidator("GBRAIN_DB_URL_v2".toUpperCase()).status).toBe(0);
expect(runValidator("X1_2_3").status).toBe(0);
});
test("ACCEPTS underscore-prefixed identifier", () => {
expect(runValidator("_PRIVATE_VAR").status).toBe(0);
});
test("REJECTS lowercase identifier (#1606 regression — would pass on macOS without LC_ALL=C)", () => {
expect(runValidator("lower_case").status).toBe(2);
});
test("REJECTS mixed-case identifier", () => {
expect(runValidator("MixedCase").status).toBe(2);
expect(runValidator("camelCase").status).toBe(2);
});
test("REJECTS name starting with digit", () => {
expect(runValidator("1ABC").status).toBe(2);
});
test("REJECTS empty name", () => {
expect(runValidator("").status).toBe(2);
});
// Note: hyphen/dot acceptance is a pre-existing overpermissiveness in the
// glob pattern `[A-Z_][A-Z0-9_]*` — `*` matches any chars after the bracket
// class. NOT in scope for #1606; tracked separately for a future cleanup
// wave. Tests intentionally do not assert hyphen/dot rejection so this
// file doesn't regress when that future fix lands.
test("LC_ALL=C is local to the validator (does not leak to caller)", () => {
// After sourcing + calling the validator, $LC_ALL in the caller scope
// must remain whatever LANG/LC_ALL the caller set. We seed LC_ALL with a
// distinctive value, call the validator, then print $LC_ALL — the
// distinctive value must survive.
const result = spawnSync(
"bash",
["-c", `. "${LIB}"; LC_ALL=fr_FR.UTF-8; _gstack_gbrain_validate_varname FOO; echo "$LC_ALL"`],
{
encoding: "utf-8",
timeout: 5000,
env: { ...process.env, LANG: "en_US.UTF-8" },
},
);
expect(result.status).toBe(0);
expect(result.stdout.trim()).toBe("fr_FR.UTF-8");
});
});
+83
View File
@@ -410,6 +410,89 @@ describe('pooler-url', () => {
expect(r.status).toBe(2);
expect(r.stderr).toContain('DB_PASS env var is required');
});
// --- Issue #1301: New Supabase projects' API returns transaction/6543 but
// the shared pooler tenant only listens on session/5432. Rewrite that
// single combination, leave every other shape alone. ---
test('rewrites single transaction/6543 response to session/5432 (issue #1301)', async () => {
mock = startMock({
[`GET /v1/projects/${REF}/config/database/pooler`]: () =>
jsonResp({ ...POOLER_OK, pool_mode: 'transaction', db_port: 6543 }),
});
const r = await runBin(['pooler-url', REF, '--json'], {
SUPABASE_ACCESS_TOKEN: 'sbp_test',
DB_PASS: 'pw',
SUPABASE_API_BASE: mock.url,
});
expect(r.status).toBe(0);
expect(JSON.parse(r.stdout).pooler_url).toContain(':5432/postgres');
expect(r.stderr).toContain('rewriting');
});
test('leaves session/6543 alone (some regions genuinely serve session on 6543)', async () => {
mock = startMock({
[`GET /v1/projects/${REF}/config/database/pooler`]: () =>
jsonResp({ ...POOLER_OK, pool_mode: 'session', db_port: 6543 }),
});
const r = await runBin(['pooler-url', REF, '--json'], {
SUPABASE_ACCESS_TOKEN: 'sbp_test',
DB_PASS: 'pw',
SUPABASE_API_BASE: mock.url,
});
expect(r.status).toBe(0);
expect(JSON.parse(r.stdout).pooler_url).toContain(':6543/postgres');
expect(r.stderr).not.toContain('rewriting');
});
test('leaves transaction/5432 alone (only the 6543 case is the known footgun)', async () => {
mock = startMock({
[`GET /v1/projects/${REF}/config/database/pooler`]: () =>
jsonResp({ ...POOLER_OK, pool_mode: 'transaction', db_port: 5432 }),
});
const r = await runBin(['pooler-url', REF, '--json'], {
SUPABASE_ACCESS_TOKEN: 'sbp_test',
DB_PASS: 'pw',
SUPABASE_API_BASE: mock.url,
});
expect(r.status).toBe(0);
expect(JSON.parse(r.stdout).pooler_url).toContain(':5432/postgres');
expect(r.stderr).not.toContain('rewriting');
});
test('GSTACK_SUPABASE_TRUST_API_PORT=1 disables the rewrite', async () => {
mock = startMock({
[`GET /v1/projects/${REF}/config/database/pooler`]: () =>
jsonResp({ ...POOLER_OK, pool_mode: 'transaction', db_port: 6543 }),
});
const r = await runBin(['pooler-url', REF, '--json'], {
SUPABASE_ACCESS_TOKEN: 'sbp_test',
DB_PASS: 'pw',
SUPABASE_API_BASE: mock.url,
GSTACK_SUPABASE_TRUST_API_PORT: '1',
});
expect(r.status).toBe(0);
expect(JSON.parse(r.stdout).pooler_url).toContain(':6543/postgres');
expect(r.stderr).not.toContain('rewriting');
});
test('array response with explicit session entry on 5432 is unaffected (existing behavior)', async () => {
mock = startMock({
[`GET /v1/projects/${REF}/config/database/pooler`]: () =>
jsonResp([
{ ...POOLER_OK, pool_mode: 'transaction', db_port: 6543 },
{ ...POOLER_OK, pool_mode: 'session', db_port: 5432 },
]),
});
const r = await runBin(['pooler-url', REF, '--json'], {
SUPABASE_ACCESS_TOKEN: 'sbp_test',
DB_PASS: 'pw',
SUPABASE_API_BASE: mock.url,
});
expect(r.status).toBe(0);
expect(JSON.parse(r.stdout).pooler_url).toContain(':5432/postgres');
expect(r.stderr).not.toContain('rewriting');
});
});
describe('list-orphans (D20)', () => {
+14
View File
@@ -2273,6 +2273,20 @@ describe('setup script validation', () => {
expect(fnBody).toContain('rm -f "$target"');
});
test('setup links root gstack skill through a thin Claude wrapper alias', () => {
const fnStart = setupContent.indexOf('link_claude_root_skill_alias()');
const fnEnd = setupContent.indexOf('# ─── Helper: remove old unprefixed Claude skill entries', fnStart);
const fnBody = setupContent.slice(fnStart, fnEnd);
expect(fnBody).toContain('_gstack-command');
expect(fnBody).toContain('_link_or_copy "$gstack_dir/SKILL.md" "$target/SKILL.md"');
const claudeSection = setupContent.slice(
setupContent.indexOf('# 4. Install for Claude'),
setupContent.indexOf('# 5. Install for Codex')
);
expect(claudeSection).toContain('link_claude_root_skill_alias "$SOURCE_GSTACK_DIR" "$INSTALL_SKILLS_DIR"');
});
test('setup supports --host auto|claude|codex|kiro|opencode', () => {
expect(setupContent).toContain('--host');
expect(setupContent).toContain('claude|codex|kiro|factory|opencode|auto');
+18
View File
@@ -67,6 +67,24 @@ describe('gstack-artifacts-url', () => {
expect(r.stderr).toContain('unrecognized URL form');
});
test('rejects remotes without both owner and repo path segments', () => {
const malformed = [
'https://github.com',
'https://github.com/owner',
'https://github.com/owner/',
'https://github.com/owner//repo',
'git@github.com:owner',
'ssh://git@github.com',
'ssh://git@github.com/owner',
];
for (const url of malformed) {
const r = run(['--to', 'ssh', url]);
expect(r.code, url).toBe(3);
expect(r.stderr, url).toContain('failed to parse host/owner');
}
});
test('rejects missing args with exit 2', () => {
expect(run([]).code).toBe(2);
expect(run(['--to']).code).toBe(2);
@@ -267,6 +267,10 @@ describe('schema regression', () => {
'gbrain_local_status',
'gbrain_mcp_mode',
'gbrain_on_path',
// PR #1591 added gbrain_pooler_mode for PgBouncer transaction-mode
// detection. Keep alphabetized; downstream sync-gbrain ignores unknown
// keys so adding here is forward-compat.
'gbrain_pooler_mode',
'gbrain_version',
'gstack_artifacts_remote',
'gstack_brain_git',
+25 -3
View File
@@ -12,6 +12,7 @@ const tmpCwd = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-search-cwd-'));
// gstack-slug derives slug from git remote (none here) → falls back to basename of cwd.
const slug = path.basename(tmpCwd).replace(/[^a-zA-Z0-9._-]/g, '');
const projDir = path.join(tmpHome, 'projects', slug);
const otherProjDir = path.join(tmpHome, 'projects', 'other-project');
function run(args: string[]): string {
return execFileSync(BIN, args, {
@@ -23,12 +24,18 @@ function run(args: string[]): string {
beforeAll(() => {
fs.mkdirSync(projDir, { recursive: true });
fs.mkdirSync(otherProjDir, { recursive: true });
const entries = [
{ ts: '2026-05-01T00:00:00Z', skill: 'test', type: 'pattern', key: 'foo-pattern', insight: 'A foo-related insight', confidence: 8, source: 'observed', files: [] },
{ ts: '2026-05-02T00:00:00Z', skill: 'test', type: 'pitfall', key: 'bar-pitfall', insight: 'A bar-related insight', confidence: 8, source: 'observed', files: [] },
{ ts: '2026-05-03T00:00:00Z', skill: 'test', type: 'pattern', key: 'baz-pattern', insight: 'A baz-related insight', confidence: 8, source: 'observed', files: [] },
{ ts: '2026-05-01T00:00:00Z', skill: 'test', type: 'pattern', key: 'foo-pattern', insight: 'A foo-related insight', confidence: 8, source: 'observed', trusted: false, files: [] },
{ ts: '2026-05-02T00:00:00Z', skill: 'test', type: 'pitfall', key: 'bar-pitfall', insight: 'A bar-related insight', confidence: 8, source: 'observed', trusted: false, files: [] },
{ ts: '2026-05-03T00:00:00Z', skill: 'test', type: 'pattern', key: 'baz-pattern', insight: 'A baz-related insight', confidence: 8, source: 'observed', trusted: false, files: [] },
];
const otherEntries = [
{ ts: '2026-05-04T00:00:00Z', skill: 'test', type: 'pattern', key: 'foreign-observed', insight: 'A foreign observed insight', confidence: 8, source: 'observed', trusted: false, files: [] },
{ ts: '2026-05-05T00:00:00Z', skill: 'test', type: 'pattern', key: 'foreign-user', insight: 'A foreign user-stated insight', confidence: 8, source: 'user-stated', trusted: true, files: [] },
];
fs.writeFileSync(path.join(projDir, 'learnings.jsonl'), entries.map(e => JSON.stringify(e)).join('\n') + '\n');
fs.writeFileSync(path.join(otherProjDir, 'learnings.jsonl'), otherEntries.map(e => JSON.stringify(e)).join('\n') + '\n');
});
afterAll(() => {
@@ -58,3 +65,18 @@ describe('gstack-learnings-search token-OR query semantics', () => {
expect(out).toContain('baz-pattern');
});
});
describe('gstack-learnings-search cross-project trust gating', () => {
test('cross-project mode still includes observed entries from the current project', () => {
const out = run(['--cross-project', '--query', 'foo']);
expect(out).toContain('foo-pattern');
expect(out).not.toContain('[cross-project]');
});
test('cross-project mode only imports trusted entries from other projects', () => {
const out = run(['--cross-project', '--query', 'foreign']);
expect(out).toContain('foreign-user');
expect(out).toContain('[cross-project]');
expect(out).not.toContain('foreign-observed');
});
});
+42 -1
View File
@@ -12,7 +12,7 @@
*/
import { describe, it, expect, beforeEach, afterAll } from "bun:test";
import { mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, mkdirSync } from "fs";
import { mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, mkdirSync, chmodSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
@@ -96,6 +96,47 @@ describe("secretScanFile", () => {
}
rmSync(dir, { recursive: true, force: true });
});
it("probes the gitleaks executable directly before scanning", () => {
const dir = mkdtempSync(join(tmpdir(), "gstack-test-"));
const binDir = join(dir, "bin");
const log = join(dir, "gitleaks-calls.log");
const file = join(dir, "clean.txt");
mkdirSync(binDir, { recursive: true });
writeFileSync(file, "no secrets here\n");
writeFileSync(
join(binDir, "gitleaks"),
`#!/bin/sh
printf '%s\\n' "$*" >> "${log}"
if [ "$1" = "version" ]; then
exit 0
fi
if [ "$1" = "detect" ]; then
echo '[]'
exit 0
fi
exit 2
`,
"utf-8",
);
chmodSync(join(binDir, "gitleaks"), 0o755);
const oldPath = process.env.PATH;
process.env.PATH = `${binDir}:${oldPath || ""}`;
try {
_resetGitleaksAvailabilityCache();
const result = secretScanFile(file);
expect(result.scanner).toBe("gitleaks");
expect(result.findings).toEqual([]);
const calls = readFileSync(log, "utf-8").trim().split("\n");
expect(calls[0]).toBe("version");
expect(calls[1]).toContain("detect --no-git --source");
} finally {
if (oldPath === undefined) delete process.env.PATH;
else process.env.PATH = oldPath;
rmSync(dir, { recursive: true, force: true });
}
});
});
// ── parseSkillManifest ─────────────────────────────────────────────────────
+111
View File
@@ -0,0 +1,111 @@
/**
* Coverage for PR #1620 Post-failure PR-state check after `gh pr merge`
* non-zero exit.
*
* The fix lives in land-and-deploy/SKILL.md.tmpl as Step §4a-postfail.
* After ANY non-zero `gh pr merge`, the skill must query authoritative PR
* state via `gh pr view --json state,mergeCommit,mergedAt,mergedBy` and
* branch on the result instead of retrying `gh pr merge` (cli/cli#3442,
* cli/cli#13380).
*
* Static invariants pin:
* - §4a-postfail header present
* - Universal invariant text + reference to upstream gh bugs
* - All three state branches (MERGED, OPEN, CLOSED) named explicitly
* - MERGED branch: capture merge SHA via mergeCommit.oid
* - MERGED branch: non-destructive worktree cleanup with uncommitted-work guard
* - MERGED branch: continues to §4a CI watch
* - OPEN branch: checks autoMergeRequest before treating as failure
* - CLOSED branch: STOPs
* - Hard rule: never retry `gh pr merge`
* - .tmpl edit propagated to generated SKILL.md (atomic per T-Codex-3)
*/
import { describe, expect, test } from "bun:test";
import * as fs from "node:fs";
import * as path from "node:path";
const ROOT = path.resolve(import.meta.dir, "..");
const TMPL = path.join(ROOT, "land-and-deploy", "SKILL.md.tmpl");
const MD = path.join(ROOT, "land-and-deploy", "SKILL.md");
function readTmpl(): string {
return fs.readFileSync(TMPL, "utf-8");
}
function readMd(): string {
return fs.readFileSync(MD, "utf-8");
}
describe("PR #1620 §4a-postfail in land-and-deploy template", () => {
test("§4a-postfail header present in template", () => {
expect(readTmpl()).toMatch(/### 4a-postfail: Post-failure PR-state check/);
});
test("§4a-postfail comes before §4a (Merge queue detection)", () => {
const body = readTmpl();
const postfail = body.indexOf("### 4a-postfail:");
const queue = body.indexOf("### 4a: Merge queue detection");
expect(postfail).toBeGreaterThan(-1);
expect(queue).toBeGreaterThan(-1);
expect(postfail).toBeLessThan(queue);
});
test("Universal invariant + upstream gh bug references", () => {
const body = readTmpl();
expect(body).toMatch(/Universal invariant/);
expect(body).toMatch(/non-zero exit from `gh pr merge`/);
expect(body).toMatch(/cli\/cli#3442/);
expect(body).toMatch(/cli\/cli#13380/);
});
test("Authoritative state query uses gh pr view --json", () => {
const body = readTmpl();
expect(body).toMatch(/gh pr view --json state,mergeCommit,mergedAt,mergedBy/);
});
test("All three state branches named: MERGED, OPEN, CLOSED", () => {
const body = readTmpl();
expect(body).toMatch(/state == "MERGED"/);
expect(body).toMatch(/state == "OPEN"/);
expect(body).toMatch(/state == "CLOSED"/);
});
test("MERGED branch captures merge SHA via mergeCommit.oid", () => {
const body = readTmpl();
expect(body).toMatch(/gh pr view --json mergeCommit -q \.mergeCommit\.oid/);
});
test("MERGED worktree cleanup is non-destructive (uncommitted-work guard)", () => {
const body = readTmpl();
expect(body).toMatch(/uncommitted work/);
expect(body).toMatch(/STOP worktree cleanup without removing/);
expect(body).toMatch(/Do NOT use `--force`/);
expect(body).toMatch(/Do NOT remove the user's primary working tree/);
});
test("MERGED branch continues to §4a CI auto-deploy detection", () => {
const body = readTmpl();
expect(body).toMatch(/continue to §4a/);
});
test("OPEN branch checks autoMergeRequest before treating as failure", () => {
const body = readTmpl();
expect(body).toMatch(/gh pr view --json autoMergeRequest/);
expect(body).toMatch(/auto-merge is enabled or merge queue is in use/);
});
test("CLOSED branch STOPs", () => {
const body = readTmpl();
expect(body).toMatch(/state == "CLOSED".*[\s\S]{0,200}STOP/);
});
test("Hard rule: never retry gh pr merge after non-zero exit", () => {
const body = readTmpl();
expect(body).toMatch(/never call `gh pr merge` a second time/);
});
test("Generated SKILL.md carries the §4a-postfail section (atomic regen per T-Codex-3)", () => {
const md = readMd();
expect(md).toMatch(/### 4a-postfail: Post-failure PR-state check/);
expect(md).toMatch(/state == "MERGED"/);
});
});
+19 -5
View File
@@ -29,20 +29,34 @@ describe("gstack-learnings-search injection prevention", () => {
test("uses process.env for all user-controlled values", () => {
const bunBlock = script.slice(script.indexOf('bun -e "'));
// Must use process.env for TYPE, QUERY, LIMIT, SLUG, CROSS_PROJECT
// Must use process.env for TYPE, QUERY, LIMIT.
// SLUG and CROSS are no longer threaded as env vars inside the bun
// block since PR #1619 — current vs cross-project rows are now
// distinguished by inline tags in the piped input (`current\t<line>`
// vs `cross\t<line>`), removing the need for env-var filters inside
// the bun block. CROSS is still set on the bash command line (it
// controls whether the cross-project find runs at all), but the bun
// block reads the tag, not the env var.
expect(bunBlock).toContain("process.env.GSTACK_SEARCH_TYPE");
expect(bunBlock).toContain("process.env.GSTACK_SEARCH_QUERY");
expect(bunBlock).toContain("process.env.GSTACK_SEARCH_LIMIT");
expect(bunBlock).toContain("process.env.GSTACK_SEARCH_SLUG");
expect(bunBlock).toContain("process.env.GSTACK_SEARCH_CROSS");
});
test("env vars are set on the bun command line", () => {
// The env vars must be passed to bun, not just set in the shell
// The env vars must be passed to bun, not just set in the shell.
// SLUG removed by PR #1619 — see above.
expect(script).toContain("GSTACK_SEARCH_TYPE=");
expect(script).toContain("GSTACK_SEARCH_QUERY=");
expect(script).toContain("GSTACK_SEARCH_LIMIT=");
expect(script).toContain("GSTACK_SEARCH_SLUG=");
expect(script).toContain("GSTACK_SEARCH_CROSS=");
});
test("current vs cross-project rows distinguished by inline tags, not SLUG env (#1619)", () => {
const bunBlock = script.slice(script.indexOf('bun -e "'));
// The bun block must inspect the per-line tag to mark cross-project rows.
// The current shape emits `current\t<json>` or `cross\t<json>` from the
// upstream pipe (via emit_tagged_file). Inside the bun block, the script
// parses out the leading tag and sets a per-entry flag.
expect(bunBlock).toMatch(/sourceTag|tabIndex|crossProject/);
});
});
@@ -0,0 +1,105 @@
/**
* Regression tests for #1539 /review false positive rate on mature
* frameworks (Django, 4/8 FPs).
*
* The fix extends the Confidence Calibration resolver with a Pre-emit
* verification gate: every finding must quote the specific code line that
* motivates it; unverified findings are forced to confidence 4-5 so the
* existing suppression rule auto-fires.
*
* Tests pin:
* - The resolver emits the gate text
* - The regenerated SKILL.md files for all consumers carry the gate
* - The framework-meta nudge is present
* - The deferred-design-doc reference is present (T-Codex-2 split)
* - Each named FP class from the issue has an explicit row in the gate
*
* No paid eval. The static invariants are the durable guarantees that the
* FP-killing mechanism doesn't regress the LLM behavior under it is
* separately measured via E2E review evals when this branch is run with
* EVALS=1.
*/
import { describe, expect, test } from "bun:test";
import * as fs from "node:fs";
import * as path from "node:path";
import { generateConfidenceCalibration } from "../scripts/resolvers/confidence";
const ROOT = path.resolve(import.meta.dir, "..");
describe("#1539 confidence resolver — pre-emit verification gate present", () => {
test("resolver text includes the gate header", () => {
const out = generateConfidenceCalibration({} as never);
expect(out).toMatch(/Pre-emit verification gate/);
expect(out).toMatch(/#1539/);
});
test("gate requires quoted code snippet (file:line + verbatim text)", () => {
const out = generateConfidenceCalibration({} as never);
expect(out).toMatch(/Quote the specific code line/);
expect(out).toMatch(/file:line/);
expect(out).toMatch(/verbatim text/);
});
test("unverified findings auto-suppressed via existing confidence rule", () => {
const out = generateConfidenceCalibration({} as never);
// The gate must hook the existing "<7 -> suppress" rule rather than
// invent new mechanism. Look for both forcing-to-4-5 AND a reference
// to suppression.
expect(out).toMatch(/Force its confidence to 4-5/);
expect(out).toMatch(/suppress/i);
});
test("framework-meta nudge present for Django/Rails/SQLAlchemy/TypeORM/Sequelize/Prisma", () => {
const out = generateConfidenceCalibration({} as never);
expect(out).toMatch(/Framework-meta nudge/);
expect(out).toMatch(/Django/);
expect(out).toMatch(/Rails/);
expect(out).toMatch(/SQLAlchemy/);
expect(out).toMatch(/TypeORM/);
expect(out).toMatch(/Sequelize/);
expect(out).toMatch(/Prisma/);
});
test("references the deferred design doc for framework-aware verification (T-Codex-2)", () => {
const out = generateConfidenceCalibration({} as never);
expect(out).toMatch(/1539-framework-aware-review\.md/);
});
test("enumerates the four FP classes the gate kills (#1539 named cases)", () => {
const out = generateConfidenceCalibration({} as never);
expect(out).toMatch(/field doesn't exist on model/);
expect(out).toMatch(/dict\.get\(\) might be None/);
expect(out).toMatch(/save\(\) might lose fields/);
expect(out).toMatch(/update_fields might miss/);
});
});
describe("#1539 generated SKILL.md files — gate propagated to all consumers", () => {
const consumers = [
"review/SKILL.md",
"cso/SKILL.md",
"plan-eng-review/SKILL.md",
"ship/SKILL.md",
];
for (const rel of consumers) {
test(`${rel} carries the Pre-emit verification gate`, () => {
const body = fs.readFileSync(path.join(ROOT, rel), "utf-8");
expect(body).toMatch(/Pre-emit verification gate/);
expect(body).toMatch(/Quote the specific code line/);
});
}
});
describe("#1539 confidence suppression rule unchanged (regression on existing behavior)", () => {
test("confidence 3-4 row still says 'Suppress from main report'", () => {
const out = generateConfidenceCalibration({} as never);
expect(out).toMatch(/3-4[\s\S]{0,200}Suppress from main report/);
});
test("confidence 9-10 row preserves 'Show normally' behavior", () => {
const out = generateConfidenceCalibration({} as never);
expect(out).toMatch(/9-10[\s\S]{0,200}Show normally/);
});
});
@@ -0,0 +1,227 @@
/**
* Regression tests for #1611 /sync-gbrain --full SIGTERM at hardcoded 35min,
* no resume from gbrain's import-checkpoint.
*
* Tests cover three surfaces:
* - resolveStageTimeoutMs (gstack-gbrain-sync.ts) env parsing + bounds
* - decideResume (gstack-gbrain-sync.ts) checkpoint+staging detection
* - SIGTERM staging preservation invariants in gstack-memory-ingest.ts
*
* The resolveStageTimeoutMs + decideResume helpers are exported from the
* source file so we can call them directly. The SIGTERM behavior is pinned
* via static-invariant checks against the source body the signal handler
* is hard to exercise in a unit test without forking, and the static check
* is the durable guarantee.
*
* Branches under test (9 total):
* 1. parseTimeoutEnv default (env unset 2_100_000)
* 2. parseTimeoutEnv non-numeric warn + default
* 3. parseTimeoutEnv below floor (<60_000) warn + default
* 4. parseTimeoutEnv above ceiling (>86_400_000) warn + default
* 5. parseTimeoutEnv valid mid-range returns value
* 6. decideResume: no checkpoint no-checkpoint verdict
* 7. decideResume: checkpoint + staging exists resume verdict
* 8. decideResume: checkpoint + staging missing stale-staging-missing
* 9. SIGTERM preserves staging dir when gbrain checkpoint points at it
* (static invariant on memory-ingest source)
*/
import { describe, expect, test, beforeEach, afterEach } from "bun:test";
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
import {
resolveStageTimeoutMs,
readGbrainCheckpoint,
decideResume,
} from "../bin/gstack-gbrain-sync";
const ROOT = path.resolve(import.meta.dir, "..");
const DEFAULT_MS = 35 * 60 * 1000;
const MIN_MS = 60_000;
const MAX_MS = 86_400_000;
describe("#1611 resolveStageTimeoutMs — env parsing + bounds", () => {
test("undefined env → default 2_100_000ms (unchanged from prior behavior)", () => {
expect(resolveStageTimeoutMs(undefined, "GSTACK_SYNC_MEMORY_TIMEOUT_MS")).toBe(DEFAULT_MS);
});
test("empty string env → default", () => {
expect(resolveStageTimeoutMs("", "GSTACK_SYNC_MEMORY_TIMEOUT_MS")).toBe(DEFAULT_MS);
});
test("non-numeric env → warn + default", () => {
expect(resolveStageTimeoutMs("not-a-number", "GSTACK_SYNC_CODE_TIMEOUT_MS")).toBe(DEFAULT_MS);
});
test("zero env → warn + default (not positive)", () => {
expect(resolveStageTimeoutMs("0", "GSTACK_SYNC_MEMORY_TIMEOUT_MS")).toBe(DEFAULT_MS);
});
test("negative env → warn + default", () => {
expect(resolveStageTimeoutMs("-1000", "GSTACK_SYNC_MEMORY_TIMEOUT_MS")).toBe(DEFAULT_MS);
});
test("below 60_000ms floor (1min) → warn + default", () => {
expect(resolveStageTimeoutMs("30000", "GSTACK_SYNC_MEMORY_TIMEOUT_MS")).toBe(DEFAULT_MS);
expect(resolveStageTimeoutMs(`${MIN_MS - 1}`, "GSTACK_SYNC_MEMORY_TIMEOUT_MS")).toBe(DEFAULT_MS);
});
test("above 86_400_000ms ceiling (24h) → warn + default", () => {
expect(resolveStageTimeoutMs(`${MAX_MS + 1}`, "GSTACK_SYNC_MEMORY_TIMEOUT_MS")).toBe(DEFAULT_MS);
expect(resolveStageTimeoutMs("999999999999", "GSTACK_SYNC_CODE_TIMEOUT_MS")).toBe(DEFAULT_MS);
});
test("at floor (60_000ms exactly) → accepted", () => {
expect(resolveStageTimeoutMs(`${MIN_MS}`, "GSTACK_SYNC_MEMORY_TIMEOUT_MS")).toBe(MIN_MS);
});
test("at ceiling (86_400_000ms exactly) → accepted", () => {
expect(resolveStageTimeoutMs(`${MAX_MS}`, "GSTACK_SYNC_MEMORY_TIMEOUT_MS")).toBe(MAX_MS);
});
test("valid mid-range (2h = 7_200_000ms) → returns value", () => {
expect(resolveStageTimeoutMs("7200000", "GSTACK_SYNC_MEMORY_TIMEOUT_MS")).toBe(7_200_000);
});
});
// decideResume + readGbrainCheckpoint exercise ~/.gbrain/import-checkpoint.json
// and the staging dir on disk. We point HOME at a tmp dir, write fake state,
// and assert verdicts.
describe("#1611 decideResume — checkpoint + staging detection", () => {
let tmpHome: string;
let origHome: string | undefined;
let cpDir: string;
let cpPath: string;
let stagingDir: string;
beforeEach(() => {
tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "gstack-1611-"));
origHome = process.env.HOME;
process.env.HOME = tmpHome;
cpDir = path.join(tmpHome, ".gbrain");
cpPath = path.join(cpDir, "import-checkpoint.json");
stagingDir = path.join(tmpHome, ".staging-ingest-99-99");
fs.mkdirSync(cpDir, { recursive: true });
});
afterEach(() => {
if (origHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = origHome;
}
try {
fs.rmSync(tmpHome, { recursive: true, force: true });
} catch {
// best-effort
}
});
test("no checkpoint file → no-checkpoint verdict", () => {
// cpPath does not exist
expect(fs.existsSync(cpPath)).toBe(false);
expect(readGbrainCheckpoint()).toBeNull();
expect(decideResume().kind).toBe("no-checkpoint");
});
test("corrupt JSON checkpoint → no-checkpoint verdict", () => {
fs.writeFileSync(cpPath, "{not valid json", "utf-8");
expect(readGbrainCheckpoint()).toBeNull();
expect(decideResume().kind).toBe("no-checkpoint");
});
test("checkpoint + staging dir exists → resume verdict", () => {
fs.mkdirSync(stagingDir, { recursive: true });
fs.writeFileSync(stagingDir + "/page1.md", "content", "utf-8");
fs.writeFileSync(cpPath, JSON.stringify({
dir: stagingDir,
totalFiles: 1989,
processedIndex: 1000,
completedFiles: 1000,
timestamp: "2026-05-19T19:30:05.008Z",
}), "utf-8");
const v = decideResume();
expect(v.kind).toBe("resume");
if (v.kind === "resume") {
expect(v.stagingDir).toBe(stagingDir);
expect(v.processedIndex).toBe(1000);
expect(v.totalFiles).toBe(1989);
}
});
test("checkpoint references missing staging dir → stale-staging-missing", () => {
// Note: stagingDir is NOT created on disk for this test
fs.writeFileSync(cpPath, JSON.stringify({
dir: stagingDir,
totalFiles: 1989,
processedIndex: 1000,
}), "utf-8");
const v = decideResume();
expect(v.kind).toBe("stale-staging-missing");
if (v.kind === "stale-staging-missing") {
expect(v.stagingDir).toBe(stagingDir);
}
});
test("checkpoint with no dir field → no-checkpoint verdict", () => {
fs.writeFileSync(cpPath, JSON.stringify({
totalFiles: 1989,
processedIndex: 1000,
}), "utf-8");
expect(decideResume().kind).toBe("no-checkpoint");
});
test("checkpoint with empty dir string → no-checkpoint verdict", () => {
fs.writeFileSync(cpPath, JSON.stringify({
dir: "",
}), "utf-8");
expect(decideResume().kind).toBe("no-checkpoint");
});
});
describe("#1611 SIGTERM staging preservation — static invariants", () => {
test("memory-ingest signal handler checks stagingDirIsCheckpointed before cleanup", () => {
const body = fs.readFileSync(
path.join(ROOT, "bin", "gstack-memory-ingest.ts"),
"utf-8",
);
// The forward handler must read the checkpoint before deciding whether
// to clean up. Locks in the "preserve when checkpointed" branch.
expect(body).toMatch(/stagingDirIsCheckpointed/);
expect(body).toMatch(/preserving staging dir for resume/);
// The branch order must be: checkpointed → preserve, else → cleanup
const handlerStart = body.indexOf("if (_activeStagingDir)");
expect(handlerStart).toBeGreaterThan(-1);
const handlerSlice = body.slice(handlerStart, handlerStart + 1000);
const preserveAt = handlerSlice.indexOf("preserving staging dir for resume");
const cleanupAt = handlerSlice.indexOf("cleanupStagingDir");
expect(preserveAt).toBeGreaterThan(-1);
expect(cleanupAt).toBeGreaterThan(-1);
expect(preserveAt).toBeLessThan(cleanupAt);
});
test("memory-ingest reads GSTACK_INGEST_RESUME_DIR env to reuse staging dir", () => {
const body = fs.readFileSync(
path.join(ROOT, "bin", "gstack-memory-ingest.ts"),
"utf-8",
);
expect(body).toMatch(/process\.env\.GSTACK_INGEST_RESUME_DIR/);
expect(body).toMatch(/skipping prepare phase/);
});
test("gbrain-sync orchestrator passes GSTACK_INGEST_RESUME_DIR to grandchild on resume", () => {
const body = fs.readFileSync(
path.join(ROOT, "bin", "gstack-gbrain-sync.ts"),
"utf-8",
);
expect(body).toMatch(/GSTACK_INGEST_RESUME_DIR/);
expect(body).toMatch(/resuming from gbrain checkpoint/);
expect(body).toMatch(/previous checkpoint stale.*staging dir.*gone.*restaging from scratch/);
});
});
@@ -0,0 +1,146 @@
/**
* Regression tests for #1624 /retro silently produced empty/misleading
* output when "today" anchor was wrong or origin/<default> was stale.
*
* The fix is Step 0.5 in retro/SKILL.md.tmpl: four ordered pre-check
* branches before any window analysis. These tests are static invariants
* against the template body they fail the build if the guard is removed,
* weakened, or its ordering broken.
*
* Branches under test:
* 1. no-remote skip git remote returns empty
* 2. detached-HEAD skip git symbolic-ref --quiet HEAD returns empty
* 3. fetch-fail warn git fetch origin <default> exits non-zero
* 4. stale-base BLOCK fetch ok, latest commit older than window
*
* Each branch must short-circuit further checks (only one verdict wins) and
* must surface a disclosure line on stderr so the narrative carries the
* reason rather than silently misreporting.
*/
import { describe, expect, test } from "bun:test";
import * as fs from "node:fs";
import * as path from "node:path";
const ROOT = path.resolve(import.meta.dir, "..");
const RETRO_TMPL = path.join(ROOT, "retro", "SKILL.md.tmpl");
const RETRO_MD = path.join(ROOT, "retro", "SKILL.md");
function readTmpl(): string {
return fs.readFileSync(RETRO_TMPL, "utf-8");
}
function readMd(): string {
return fs.readFileSync(RETRO_MD, "utf-8");
}
describe("#1624 retro stale-base guard — Step 0.5 exists and is ordered before Step 1", () => {
test("Step 0.5 header is present in template", () => {
const body = readTmpl();
expect(body).toMatch(/### Step 0\.5: Stale-base \+ bad-today-anchor pre-flight guard/);
});
test("Step 0.5 appears before Step 1: Gather Raw Data", () => {
const body = readTmpl();
const step05 = body.indexOf("### Step 0.5:");
const step1 = body.indexOf("### Step 1: Gather Raw Data");
expect(step05).toBeGreaterThan(-1);
expect(step1).toBeGreaterThan(-1);
expect(step05).toBeLessThan(step1);
});
test("regenerated SKILL.md carries the Step 0.5 guard", () => {
const md = readMd();
expect(md).toMatch(/Step 0\.5: Stale-base \+ bad-today-anchor pre-flight guard/);
});
});
describe("#1624 retro guard — branch A: no-remote skip", () => {
test("template checks for 'origin' remote absence and skips with disclosure", () => {
const body = readTmpl();
// Must check git remote for 'origin' and short-circuit
expect(body).toMatch(/git remote[^|]*\|\s*grep -c '\^origin\$'/);
expect(body).toMatch(/RETRO_GUARD: no 'origin' remote/);
});
test("no-remote skip sets a verdict variable that gates later checks", () => {
const body = readTmpl();
// The verdict variable must be set so later branches short-circuit
expect(body).toMatch(/_RETRO_GUARD_VERDICT="skip-no-remote"/);
});
});
describe("#1624 retro guard — branch B: detached-HEAD skip", () => {
test("template checks for detached HEAD via git symbolic-ref", () => {
const body = readTmpl();
expect(body).toMatch(/git symbolic-ref --quiet HEAD/);
expect(body).toMatch(/RETRO_GUARD: detached HEAD/);
});
test("detached-HEAD branch is gated by prior verdict check (ordering)", () => {
const body = readTmpl();
// The detached-HEAD block must be guarded by the verdict check so
// no-remote always wins if both are true.
const branchBStart = body.indexOf("# Pre-check B: detached HEAD");
expect(branchBStart).toBeGreaterThan(-1);
const branchBSlice = body.slice(branchBStart, branchBStart + 500);
expect(branchBSlice).toMatch(/if \[ -z "\$_RETRO_GUARD_VERDICT" \]/);
});
});
describe("#1624 retro guard — branch C: fetch-fail warn", () => {
test("template warns and proceeds against last-known origin when fetch fails", () => {
const body = readTmpl();
// Match either `git fetch ... ||` or `if ! git fetch ...` shape.
expect(body).toMatch(/(?:if !\s+|[^\n]*\|\|\s*)git fetch origin <default>|git fetch origin <default>[^\n]*--quiet 2>\/dev\/null; then/);
expect(body).toMatch(/fetch[^\n]*failed[^\n]*offline/);
expect(body).toMatch(/_RETRO_GUARD_VERDICT="warn-fetch-failed"/);
});
test("fetch-fail warn is gated by prior verdict check (ordering)", () => {
const body = readTmpl();
const branchCStart = body.indexOf("# Pre-check C: fetch origin");
expect(branchCStart).toBeGreaterThan(-1);
const branchCSlice = body.slice(branchCStart, branchCStart + 500);
expect(branchCSlice).toMatch(/if \[ -z "\$_RETRO_GUARD_VERDICT" \]/);
});
});
describe("#1624 retro guard — branch D: stale-base BLOCK", () => {
test("template extracts latest origin/<default> commit date via git log -1 --format=%ci", () => {
const body = readTmpl();
// The BLOCK check must read the actual latest-commit date so the
// disclosure is concrete (not generic).
expect(body).toMatch(/git log -1 --format=%ci origin\/<default>/);
});
test("BLOCK prose names latest-commit date and instructs user remediation", () => {
const body = readTmpl();
// The BLOCK message must cite the date AND tell the user how to recover.
// "Retro window is stale" is the canonical first line.
expect(body).toMatch(/Retro window is stale/);
expect(body).toMatch(/git fetch origin <default>/);
expect(body).toMatch(/Confirm today's date/);
});
test("BLOCK branch is gated by prior verdict checks (ordering)", () => {
const body = readTmpl();
const branchDStart = body.indexOf("# Pre-check D:");
expect(branchDStart).toBeGreaterThan(-1);
const branchDSlice = body.slice(branchDStart, branchDStart + 800);
expect(branchDSlice).toMatch(/if \[ -z "\$_RETRO_GUARD_VERDICT" \]/);
});
});
describe("#1624 retro guard — disclosure must reach the narrative", () => {
test("template names the skip paths that must carry a disclosure line", () => {
const body = readTmpl();
// The post-bash prose must explicitly tell the model to surface
// these reasons in the retro output rather than silently dropping them.
expect(body).toMatch(/skip-no-remote/);
expect(body).toMatch(/skip-detached/);
expect(body).toMatch(/warn-fetch-failed/);
// The prose names disclosure + narrative together (either order) so the
// retro output is never silently confidently-wrong.
expect(body).toMatch(/(?:disclosure[\s\S]{0,200}narrative|narrative[\s\S]{0,200}disclosure)/);
});
});
+31
View File
@@ -187,6 +187,37 @@ describe('gstack-relink (#578)', () => {
expect(fs.lstatSync(path.join(skillsDir, 'qa', 'SKILL.md')).isSymbolicLink()).toBe(true);
});
test('creates a thin root alias wrapper for the /gstack slash command', () => {
setupMockInstall(['qa']);
fs.writeFileSync(
path.join(installDir, 'SKILL.md'),
'---\nname: gstack\ndescription: root\n---\n# gstack',
);
run(`${path.join(installDir, 'bin', 'gstack-config')} set skill_prefix false`, {
GSTACK_INSTALL_DIR: installDir,
GSTACK_SKILLS_DIR: skillsDir,
});
run(`${path.join(installDir, 'bin', 'gstack-relink')}`, {
GSTACK_INSTALL_DIR: installDir,
GSTACK_SKILLS_DIR: skillsDir,
});
const aliasDir = path.join(skillsDir, '_gstack-command');
const aliasSkill = path.join(aliasDir, 'SKILL.md');
expect(fs.lstatSync(aliasDir).isDirectory()).toBe(true);
expect(fs.lstatSync(aliasDir).isSymbolicLink()).toBe(false);
expect(fs.lstatSync(aliasSkill).isSymbolicLink()).toBe(true);
expect(fs.readlinkSync(aliasSkill)).toBe(path.join(installDir, 'SKILL.md'));
expect(fs.readFileSync(aliasSkill, 'utf-8')).toContain('name: gstack');
run(`${path.join(installDir, 'bin', 'gstack-config')} set skill_prefix true`, {
GSTACK_INSTALL_DIR: installDir,
GSTACK_SKILLS_DIR: skillsDir,
});
expect(fs.existsSync(aliasSkill)).toBe(true);
});
// FIRST INSTALL: --no-prefix must create ONLY flat names, zero gstack-* pollution
test('first install --no-prefix: only flat names exist, zero gstack-* entries', () => {
setupMockInstall(['qa', 'ship', 'review', 'plan-ceo-review', 'gstack-upgrade']);