mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-14 00:48:18 +00:00
* feat(bootstrap): TTY DX exploration harness + Krug onboarding fix wave Add a real-PTY exploration harness and land 16 verified "Don't Make Me Think" fixes on the paste-in install experience for Claude Code and Codex. Harness: - test/helpers/tty-harness.ts — spawns any CLI (gbrain/claude/codex) under a real pseudo-terminal (Bun terminal: spawn), timestamps every output burst, and turns silence windows into a measurable stall report. Hermetic; pure helpers unit-tested in test/tty-harness.test.ts. - scripts/dx-explore.ts — drives the fresh-user funnel (help / init / real claude-install / real codex-install / manual drive mode), writing transcripts to .context/dx-runs/ (gitignored). Fixes (all adversarially verified against the code first): - Keyless bare `gbrain init` completes in keyless mode instead of exit 1; multi-key non-TTY auto-picks the canonical default; typo stays fail-loud. - Provider picker probe-gates ollama (daemon-up != model-pulled) and offers an explicit "continue keyless" option that is the bare-Enter default. - Fresh-brain init prints one schema-setup line instead of ~240 migration names (GBRAIN_MIGRATE_VERBOSE=1 restores detail). - Init epilogue: memory-verbs funnel is last-on-screen; skills advisory compacted for init; Mod Status trimmed. - PGLite live-serve lock error names the fix (close the agent session). - Mode-picker banner interpolates the applied mode; expansion-key gate is Anthropic/OpenAI/Google, not OpenAI-only. - Missing `claude` binary skips MCP but still installs hooks; honest copy. - Foreign MCP-registration removal targets the conflicting scope and fails loud if it does not land. - Upgrade marker compares the running binary to latest and self-spawns via execPath, so a current/newer binary no longer nags from a stale cache. - interview --set/--skip after --confirm warns it voided the confirmation. - init --help matches behavior; init --supabase fails loud on non-TTY. - Provider capabilities attributed per provider across README / runbook / questions bank / bootstrap.md. - First-run tour: restart-first, prompt 3 true on day one, withheld on FAIL; README gives Codex the same scripted magic moment. - Empty-brain "0 takes" onboard nudge suppressed. - Broken settings.local.json aborts the hooks write fail-closed instead of silently dropping the user's permissions. Regenerated cli-flag-registry.generated.ts and llms-full.txt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(bootstrap): second DX polish wave — clean the success screen + honest copy (F17-F21) Follow-up to the DX fix wave, closing the top-5 remaining gaps the scorecard flagged (all human-facing polish, not survival): F17 — machine markers no longer leak to humans: - verify report drops the `[D3.6]` plan-tag from the first_run_tour detail. - the raw `UPGRADE_AVAILABLE <cur> <latest>` marker line prints ONLY on a non-TTY stderr (parsers still get it); an interactive human sees just the "gbrain X -> Y available" sentence. - per-migration "what changed" notices (v123/v124, incl. the #2704 ref) are suppressed on a FRESH-install replay via a module quiet flag; upgrades still narrate. (GBRAIN_MIGRATE_VERBOSE=1 restores them.) F18 — one obvious next action on the init success screen: the memory-verbs demo is the single "→ Do this next" hero, last on screen; import/migrate/doctor collapse into one terse "More:" footer; the graph block only shows for a non-empty brain. F19 — README "moment it clicks" is now the genuine cross-session brain round-trip (remember → restart → recall), explicitly distinguished from the identity-file recall, on both the Codex and Claude Code paths. F20 — the compact init skills advisory is human-voiced (no `[AGENT]` stage-direction on the human-facing success screen; the mode-picker's agent-directed block stays gated to the non-TTY channel). F21 — time promise reconciled: headline is ~15 min (personal-agent path) / ~30 min (always-on OpenClaw/Hermes); the runbook's search-mode line no longer claims "balanced" when keyless applies "conservative". README hooks copy says "on by default, with an opt-out" to match the runbook. Regenerated llms-full.txt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(bootstrap): address two-model adversarial review of the DX wave Fixes the regressions the 5-specialist + red-team + Claude/Codex adversarial pass found in the F1–F21 changes, each with a test: - Keyless upgrade hint pointed at `config set embedding_model`, which config.ts hard-refuses as a schema-sizing no-op — now names the working re-init recipe (`gbrain init --force --pglite --embedding-model <id>`), zero-key AND multi-key paths. - Multi-key TTY picker offered "continue keyless" but the caller aborted on it — now honors keyless like the zero-key path. - Detached update-refresh spawn used a `/gbrain$/` basename check that misfires for a renamed/official-named compiled binary (`gbrain-darwin-arm64`) and prepends the /$bunfs entrypoint — now detects dev-vs-compiled by the runtime basename (bun|node) so the refresh always runs. - `bootstrap status` reported the wire phase "done" on a hooks-only receipt (host CLI missing at wire time) — now "partial" with a re-run hint, so a resuming agent doesn't trust a false complete. - Post-repair MCP mismatch re-verifies and aborts instead of blessing a registration a racing writer may have re-claimed. - probeOpenAICompat's abort timer now spans the body read (was cleared before it), so a stalled `/v1/models` body can't hang init past the 1s cap. - Centralized the 4-copy stale-cache upgrade predicate into `pendingUpgradeVersion`; UPGRADE_AVAILABLE gains a GBRAIN_FORCE_UPGRADE_MARKER override for PTY-based agent harnesses. - Mode picker's expansion-key gate adds GEMINI_API_KEY; picker prompt is article-aware ("an embedding" / "a chat"); dead `!brainEmpty` clause removed; migrate.ts try/finally widened + stamp failures named in quiet mode. - DX harness: credential copies scrubbed even on SIGINT/interrupt (+chmod 600), child process TREE reaped on teardown, advisory made fail-open, KEY_MAP typed as a literal union. New tests: migrate quiet-replay, self-upgrade pending predicate + negative cache cases, bootstrap 127/scoped-remove/broken-settings dispatch, interview invalidation flag, verify tour-withheld-on-FAIL, init keyless/supabase/multi-key, init-nudge branches, ai-probes model parsing. Regenerated flag registry + template-repo. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * v0.45.8.0 fix(bootstrap): onboarding DX polish wave (F17-F21) + review fixes DX fix wave on the paste-in install/first-run experience for Claude Code and Codex, driven by a new real-PTY exploration harness. Keyless init completes instead of erroring, the migration wall collapses to one line, the success screen leads with one action, and the "magic moment" copy points at the genuine cross-session round-trip. Full detail in CHANGELOG. Version trio + openclaw manifest + runbook stamp bumped to 0.45.8.0; CHANGELOG release entry; TODOS onboarding-DX follow-ups filed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(bootstrap): OOBE hand-off — you own the brain, cold-start is skill #1 A working install now ends by making the two facts that matter actually land: - `gbrain bootstrap verify` prints (and returns as `handoff` in --json) an ownership block — the actual private-repo URL with what owning it means (read it, `gbrain bootstrap attach` on machine two, delete it and the brain is gone), or the local-only variant pointing at `gbrain bootstrap repo` — followed by the ONE next action: run the cold-start skill (Gmail/calendar/ contacts via ClawVisor, an OAuth vault so the agent never holds raw tokens; or offline archives), one consented phase at a time. Withheld on FAIL like the tour; shape stays unconditional for machine consumers. - cold-start ships in the downstream bundle (61 skills): its plugin exclusion ("host onboarding flow") predated the v0.45 personal-agent bootstrap and is deliberately reversed — the paste-in audience is exactly who day-one onboarding is for. It now LEADS the recommended set (ahead of book-mirror: every flagship skill only becomes magical once the brain holds the user's real life). - New drift guard: every recommended slug must be scaffoldable from the plugin bundle — recommended-but-unscaffoldable is a dead-end CTA and now fails the suite. - Runbook Hand off rewritten around the two must-land facts + the on-the-spot cold-start offer; README's Codex and Claude Code paths carry the same two follow-ups. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * v0.45.10.0 feat(bootstrap): the OOBE hand-off release Version trio + runbook stamp + template tree to 0.45.10.0; CHANGELOG entry; llms bundles regenerated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(ci): stop memory-verbs-conformance leaking a fake-keyed gateway into shard-mates The deterministic-embedder helper configures the MODULE-GLOBAL gateway with a fake OpenAI key; the file's afterAll never reset it. The bunfig preload's per-test restore only fires when the gateway is UNCONFIGURED, so the fake-keyed config persisted for every later file in the shard process — turn-context's corpus writes then embedded against real OpenAI and 401'd (CI shard-8 failure; shard re-binning from this branch's new test files exposed it). Fix both sides: conformance's afterAll now resetGateway()s back to the preload baseline and nulls both test transports; turn-context's beforeAll does the same defensively so it stays hermetic regardless of shard composition. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
242 lines
9.5 KiB
TypeScript
242 lines
9.5 KiB
TypeScript
/**
|
|
* Unit suite for test/helpers/tty-harness.ts — the PTY DX harness.
|
|
*
|
|
* Pure helpers (stripAnsi, computeStalls, renderStallsReport,
|
|
* parseDriveCommand, buildClaudeTuiSeed, saveTranscript) are exercised with
|
|
* ZERO subprocesses. Two live smokes spawn `sh` under a real PTY (cheap,
|
|
* no network, no API) and skip cleanly on a Bun without `terminal:` support
|
|
* — the same fail-SKIP posture as the agent-harness door tests.
|
|
*/
|
|
import { describe, test, expect } from 'bun:test';
|
|
import { mkdtempSync, readFileSync, rmSync, existsSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
|
|
import {
|
|
stripAnsi,
|
|
computeStalls,
|
|
renderStallsReport,
|
|
parseDriveCommand,
|
|
buildClaudeTuiSeed,
|
|
saveTranscript,
|
|
launchTty,
|
|
ptySupported,
|
|
KEY_MAP,
|
|
type PtyFrame,
|
|
} from './helpers/tty-harness.ts';
|
|
|
|
describe('stripAnsi', () => {
|
|
test('removes CSI color + cursor sequences', () => {
|
|
expect(stripAnsi('\x1b[1;32mgreen\x1b[0m plain \x1b[2K\x1b[1Gline')).toBe('green plain line');
|
|
});
|
|
|
|
test('removes OSC title sequences (BEL and ST terminated)', () => {
|
|
expect(stripAnsi('\x1b]0;title\x07text')).toBe('text');
|
|
expect(stripAnsi('\x1b]8;;http://x\x1b\\link')).toBe('link');
|
|
});
|
|
|
|
test('removes charset selection and keypad modes', () => {
|
|
expect(stripAnsi('\x1b(Bhello\x1b=world\x1b>')).toBe('helloworld');
|
|
});
|
|
|
|
test('removes private-mode CSI (cursor hide/show)', () => {
|
|
expect(stripAnsi('\x1b[?25lhidden\x1b[?25h')).toBe('hidden');
|
|
});
|
|
});
|
|
|
|
describe('computeStalls', () => {
|
|
const frames: PtyFrame[] = [
|
|
{ tMs: 100, data: 'boot\n' },
|
|
{ tMs: 300, data: 'fast\n' },
|
|
{ tMs: 5300, data: 'after long silence\n' },
|
|
{ tMs: 5400, data: 'tail\n' },
|
|
];
|
|
|
|
test('finds mid-run gaps over the threshold with the pre-gap screen as context', () => {
|
|
const stalls = computeStalls(frames, { thresholdMs: 2000 });
|
|
expect(stalls.length).toBe(1);
|
|
expect(stalls[0]!.startMs).toBe(300);
|
|
expect(stalls[0]!.durationMs).toBe(5000);
|
|
expect(stalls[0]!.context).toContain('fast');
|
|
});
|
|
|
|
test('counts startup silence (spawn → first byte)', () => {
|
|
const late: PtyFrame[] = [{ tMs: 4000, data: 'finally\n' }];
|
|
const stalls = computeStalls(late, { thresholdMs: 2000 });
|
|
expect(stalls.length).toBe(1);
|
|
expect(stalls[0]!.startMs).toBe(0);
|
|
expect(stalls[0]!.context).toBe('(no output yet)');
|
|
});
|
|
|
|
test('counts trailing silence when endMs is supplied', () => {
|
|
const stalls = computeStalls(frames, { thresholdMs: 2000, endMs: 12_000 });
|
|
expect(stalls.length).toBe(2);
|
|
expect(stalls[1]!.startMs).toBe(5400);
|
|
expect(stalls[1]!.durationMs).toBe(6600);
|
|
expect(stalls[1]!.context).toContain('tail');
|
|
});
|
|
|
|
test('below-threshold gaps are ignored', () => {
|
|
expect(computeStalls(frames, { thresholdMs: 6000 })).toEqual([]);
|
|
});
|
|
|
|
test('empty frames + endMs = one all-silence stall', () => {
|
|
const stalls = computeStalls([], { thresholdMs: 2000, endMs: 3000 });
|
|
expect(stalls.length).toBe(1);
|
|
expect(stalls[0]!.durationMs).toBe(3000);
|
|
});
|
|
|
|
test('empty frames without endMs = no stalls', () => {
|
|
expect(computeStalls([], { thresholdMs: 2000 })).toEqual([]);
|
|
});
|
|
});
|
|
|
|
describe('renderStallsReport', () => {
|
|
test('renders duration + context per stall', () => {
|
|
const md = renderStallsReport(
|
|
[{ startMs: 300, durationMs: 5000, context: 'Loading brain…' }],
|
|
10_000,
|
|
);
|
|
expect(md).toContain('5.0s at t+0.3s');
|
|
expect(md).toContain('Loading brain…');
|
|
expect(md).toContain('1 silence window');
|
|
});
|
|
|
|
test('clean report when no stalls', () => {
|
|
expect(renderStallsReport([], 4000)).toContain('No stalls at threshold');
|
|
});
|
|
});
|
|
|
|
describe('parseDriveCommand', () => {
|
|
test('parses line / send / key / note / stop', () => {
|
|
expect(parseDriveCommand('{"line":"hello"}')).toEqual({ kind: 'send', data: 'hello\r' });
|
|
expect(parseDriveCommand('{"send":"hello\\r"}')).toEqual({ kind: 'send', data: 'hello\r' });
|
|
expect(parseDriveCommand('{"key":"Enter"}')).toEqual({ kind: 'key', key: 'Enter' });
|
|
expect(parseDriveCommand('{"note":"confusing picker"}')).toEqual({
|
|
kind: 'note',
|
|
text: 'confusing picker',
|
|
});
|
|
expect(parseDriveCommand('{"stop":true}')).toEqual({ kind: 'stop' });
|
|
});
|
|
|
|
test('line strips its own trailing newline before appending Enter', () => {
|
|
expect(parseDriveCommand('{"line":"hello\\n"}')).toEqual({ kind: 'send', data: 'hello\r' });
|
|
});
|
|
|
|
test('re-escapes raw control bytes that zsh echo produces from \\r', () => {
|
|
// A literal CR byte inside the JSON string (what `echo '{"send":"x\r"}'`
|
|
// yields under zsh) must parse instead of being dropped.
|
|
expect(parseDriveCommand('{"send":"x\r"}')).toEqual({ kind: 'send', data: 'x\r' });
|
|
expect(parseDriveCommand('{"line":"y\r"}')).toEqual({ kind: 'send', data: 'y\r' });
|
|
});
|
|
|
|
test('rejects malformed JSON, unknown keys, unknown key names', () => {
|
|
expect(parseDriveCommand('not json')).toBeNull();
|
|
expect(parseDriveCommand('{"frobnicate":1}')).toBeNull();
|
|
expect(parseDriveCommand('{"key":"HyperMeta"}')).toBeNull();
|
|
expect(parseDriveCommand('{"stop":false}')).toBeNull();
|
|
expect(parseDriveCommand('null')).toBeNull();
|
|
expect(parseDriveCommand('"str"')).toBeNull();
|
|
});
|
|
|
|
test('every KEY_MAP name round-trips through the key command', () => {
|
|
for (const name of Object.keys(KEY_MAP)) {
|
|
expect(parseDriveCommand(JSON.stringify({ key: name }))).toEqual({ kind: 'key', key: name });
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('buildClaudeTuiSeed', () => {
|
|
test('marks onboarding complete and pre-trusts dirs', () => {
|
|
const seed = buildClaudeTuiSeed({ trustedDirs: ['/tmp/ws-a', '/tmp/ws-b'] });
|
|
expect(seed.hasCompletedOnboarding).toBe(true);
|
|
const projects = seed.projects as Record<string, { hasTrustDialogAccepted: boolean }>;
|
|
expect(projects['/tmp/ws-a']!.hasTrustDialogAccepted).toBe(true);
|
|
expect(projects['/tmp/ws-b']!.hasTrustDialogAccepted).toBe(true);
|
|
expect(seed.customApiKeyResponses).toBeUndefined();
|
|
});
|
|
|
|
test('approves the last 20 chars of a provided API key', () => {
|
|
const key = 'sk-ant-' + 'x'.repeat(40);
|
|
const seed = buildClaudeTuiSeed({ apiKey: key, trustedDirs: [] });
|
|
expect(seed.customApiKeyResponses).toEqual({ approved: [key.slice(-20)] });
|
|
});
|
|
});
|
|
|
|
describe('saveTranscript', () => {
|
|
test('writes the full bundle (meta, raw, visible, frames, stalls)', () => {
|
|
const dir = mkdtempSync(join(tmpdir(), 'gb-tty-unit-'));
|
|
try {
|
|
const frames: PtyFrame[] = [
|
|
{ tMs: 50, data: '\x1b[32mready\x1b[0m\n' },
|
|
{ tMs: 4050, data: 'done\n' },
|
|
];
|
|
saveTranscript(dir, {
|
|
frames,
|
|
raw: frames.map((f) => f.data).join(''),
|
|
meta: {
|
|
scenario: 'unit',
|
|
argv: ['sh', '-c', 'x'],
|
|
startedAtIso: '2026-08-12T00:00:00.000Z',
|
|
exitCode: 0,
|
|
durationMs: 4100,
|
|
},
|
|
});
|
|
expect(JSON.parse(readFileSync(join(dir, 'meta.json'), 'utf8')).scenario).toBe('unit');
|
|
expect(readFileSync(join(dir, 'visible.txt'), 'utf8')).toBe('ready\ndone\n');
|
|
expect(readFileSync(join(dir, 'raw.txt'), 'utf8')).toContain('\x1b[32m');
|
|
const frameLines = readFileSync(join(dir, 'frames.jsonl'), 'utf8').trim().split('\n');
|
|
expect(frameLines.length).toBe(2);
|
|
expect(readFileSync(join(dir, 'stalls.md'), 'utf8')).toContain('4.0s at t+0.1s');
|
|
} finally {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
describe.skipIf(!ptySupported())('launchTty (live PTY smoke)', () => {
|
|
test('captures timestamped frames from a real PTY child', async () => {
|
|
const session = launchTty(['sh', '-c', 'printf one; sleep 0.6; printf two'], {
|
|
timeoutMs: 15_000,
|
|
});
|
|
const code = await session.waitForExit(10_000);
|
|
await session.close();
|
|
expect(code).toBe(0);
|
|
expect(session.visible()).toContain('one');
|
|
expect(session.visible()).toContain('two');
|
|
const frames = session.frames();
|
|
expect(frames.length).toBeGreaterThanOrEqual(2);
|
|
// The 600ms sleep shows up as a measurable gap (loose bound: >= 300ms).
|
|
// Match the specific stall rather than index 0 — a slow spawn on a loaded
|
|
// CI box can prepend a startup stall ('(no output yet)') before it.
|
|
const stalls = computeStalls(frames, { thresholdMs: 300 });
|
|
expect(stalls.length).toBeGreaterThanOrEqual(1);
|
|
expect(stalls.some((s) => s.context.includes('one'))).toBe(true);
|
|
}, 20_000);
|
|
|
|
test('send + waitFor drive an interactive child; child sees a real TTY', async () => {
|
|
// Assert TTY-ness via `[ -t 0 ]` + a sentinel, NOT by matching the tty(1)
|
|
// device path — macOS PTYs are /dev/ttysNNN but Linux CI PTYs are
|
|
// /dev/pts/N, so a /dev\/tty pattern is a portability trap (bit us on CI).
|
|
const session = launchTty(['sh', '-c', '[ -t 0 ] && echo IS_TTY || echo NOT_TTY; read line; echo "got:$line"'], {
|
|
timeoutMs: 15_000,
|
|
});
|
|
await session.waitFor('IS_TTY', { timeoutMs: 8000 });
|
|
session.send('ping\r');
|
|
await session.waitFor('got:ping', { timeoutMs: 8000 });
|
|
await session.waitForExit(5000);
|
|
await session.close();
|
|
expect(session.exited()).toBe(true);
|
|
expect(session.visible()).not.toContain('NOT_TTY');
|
|
}, 20_000);
|
|
|
|
test('waitForQuiet settles after output stops and reports exit as quiet', async () => {
|
|
const session = launchTty(['sh', '-c', 'printf a; sleep 0.2; printf b'], {
|
|
timeoutMs: 15_000,
|
|
});
|
|
const quiet = await session.waitForQuiet({ quietMs: 500, timeoutMs: 10_000 });
|
|
expect(quiet).toBe(true);
|
|
await session.close();
|
|
}, 20_000);
|
|
});
|