mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-03 01:46:55 +02:00
* refactor(resolvers): split review.ts into MECE resolver modules (pure move) Move every function from scripts/resolvers/review.ts, unchanged, into: - review-dashboard.ts: review dashboard, plan-file review report - plan-gates.ts: approval check, exit-plan-mode gate, plan-file discovery, plan-completion audit/gate (ship + review), plan verification exec - spec-review.ts: both spec review loops, benefits-from, anti-shortcut clause - outside-voice-steps.ts: Codex second opinion, adversarial step, Codex plan review, Codex doc review, disabled-outside record - review-scope.ts: scope drift, cross-review dedup, shared-code reuse review.ts is deleted; index.ts imports the new modules. gen-skill-docs output is byte-identical for every host (--host all). Test imports and source-path references are re-pointed; the two source-text report/gate tests in gen-skill-docs.test.ts become behavioral renders across every consuming skill and host. All 46 touchfile entries that named review.ts now name all five modules, guarded by a recorded selection golden. * test(browse): black-box auth matrix for every server route and both surfaces Drives buildFetchHandler fetchLocal/fetchTunnel with no token, wrong token, root token, scoped token and the SSE cookie for all 33 routes, plus unmatched paths and wrong methods. Denials assert today's exact status, body and content type; allowed credentials assert the handler was reached. Written against the unchanged if-chain server so the W3 route-table refactor must keep it green. * refactor(shard-engine): move scripts/test-strict-output.ts to scripts/lib/shard-engine.ts The shared shard engine grows from the existing strict-output module (runShardChild, killProcessGroup, signal forwarding, strict classifier). scripts/test-strict-output.ts stays as a re-export so existing importers, mock.module paths and the strict-output/run-shard-child tests are unchanged. The engine inherits the global touchfile entry; the free runner's CLI-routing fixture copies the new module. * refactor(resolvers): decompose the three >150-line review resolvers (output-neutral) Split generateAdversarialStep, generateCodexPlanReview and generatePlanCompletionAuditInner into per-section helpers whose template literals are copied verbatim, so every function in the new modules is at or under 150 lines. gen-skill-docs output is byte-identical for every host (--host all, compared against96764e80with a fixed --link-root). * refactor(resolvers): one outside-voice failure policy (deliberate prose unification) outsideVoiceFailurePolicy(ctx, opts) in outside-voice.ts now renders the auth / timeout / empty-response bullets for all four call sites that hand-typed them (Codex second opinion, adversarial step, Codex plan review, design outside voices). Options are explicit per site (timeoutMinutes, onTimeout, stderrOnEmpty, fallback, escape) with no defaults. Deliberate generated-prose changes (every host): - office-hours: 'Fall back to <native> subagent.' becomes 'Fall back to the <native> subagent below.' - plan-devex-review: the plain 'Auth failure (stderr contains ...)' bullets become the canonical bold bullets; auth also triggers on 'API key'; 'auth failed' becomes 'authentication failed'. - review/ship adversarial: 'exceeded 9 minutes and was terminated' becomes 'timed out after 9 minutes and was terminated'; the timeout is still MISSING COVERAGE. - design outside voices: unchanged. Adds ratchet (d) (test/outside-voice-failure-policy.test.ts) with a reasoned allowlist for /codex's own CLI errors, the MISSING COVERAGE retention test, refreshed codex/factory ship goldens, and outside-voice.ts in every touchfile entry of review.ts and design.ts (selection golden extended). * test(pty): fake PTY session driver with an injectable clock through the runner launch seam The three plan-skill runners take an optional PtyDriver (launch, now, monotonic, sleep); omitted, they use the real launcher and clocks exactly as before. test/helpers/pty/fake-session.ts feeds scripted frames through that seam, and claude-pty-runner.runners.unit.test.ts runs observation, counting and floor for success, deadline timeout, permission prompt and plan-ready outcomes with no CLI or real timers. These cases must stay green unchanged through the W4 split and the runPtySession extraction. Touchfiles: every entry that lists claude-pty-runner.ts or pty-screen.ts now also lists test/helpers/pty/**. * refactor(shard-engine): run both lanes on the shared engine; lane policy injected Engine (scripts/lib/shard-engine.ts) gains the W2 primitives: per-shard tmp/Chromium sandbox + async cleanup backstop, log-path allocation and full-stream log capture, one duration-seed reader/writer with a lane predicate, LanePolicy (seed predicate + zero-execution verdict), strictShardStatus, and the shared CLI flag loop. runShardChild takes an optional companion (signal/settle) and waits a bounded 250ms to reap a wall-killed child. Free lane stops spawning shards itself: runFreeShard uses runShardChild with trackShardBrowser as the companion (win32 path unchanged: no process group, no negative-pid kill). Its sync state-dir removal stays lane policy. Paid lane uses the sandbox, log, seed, verdict and flag primitives; the hollow-shard guard applies PAID_LANE_POLICY. Lane outcomes are unchanged (free keeps >= 0 seeds and file-count zero-exec rule; paid keeps > 0 seeds, warning under selection and passed-empty under EVALS_ALL). paid-free-boundary's closure assertion now names the engine module, where the strict classifier lives. * test(shard-engine): engine unit tests, fixture-corpus equivalence, per-lane CLI parity - test/shard-engine.test.ts: failing/unhandled/module-load output fails both lanes, per-lane zero-execution and seed rules, whole-group kill on a wall timeout (both lanes), mocked-win32 path with no negative-pid kill, companion settle order, log capture, sandbox isolation, flag loop. - test/shard-engine-equivalence.test.ts + test/fixtures/shard-equivalence: seven outcome fixtures plus one real shard, run through both lanes and compared with classifications recorded from the base runners (96764e80). - test/shard-cli-parity.test.ts + test/fixtures/shard-cli-parity: flag set, defaults, validation errors and the Unknown argument error per lane match the base runners. * refactor(shard-engine): decompose runFreeShard and runPaidShard to <= 150 lines Output-neutral extraction under the fixture-corpus equivalence and runner tests: captureFreeStream, explainFreeVerdict and logFreeRecovery (free); paidShardCommand, settleShardSpool, settleBootstrapRetention and printLogTail (paid). The bootstrap scope-creation block that bootstrap-retention.test.ts evaluates stays verbatim. * refactor(pty): split claude-pty-runner.ts into test/helpers/pty/* behind a barrel Pure move: every line of the former 5,047-line runner lands verbatim in one module (four private helpers gain `export` for cross-module use): binary, screen (absorbs test/helpers/pty-screen.ts, which now re-exports it), launch, session (PtyDriver), judge, classify, auq, plan-native, boundaries, runners/{observation,counting,floor}. claude-pty-runner.ts re-exports the original public surface by name; pty/ modules import siblings directly. Tests that read the runner's source text: - rewritten as behavioral: the unit test's model-pin tripwire (fake CLI argv: fallback chain, --model before extraArgs, hermetic --strict-mcp-config), pty-skill-seeding-wiring (runners through the fake driver; launcher through a fake CLI reporting CLAUDE_CONFIG_DIR). The "three wrappers forward model" grep is replaced by the runners' fake-driver launch assertions. - pty-screen-session / pty-screen-supervision: stop copying runner source; they mock.module the real pty/screen.ts (and the fixture cleanup) instead. - re-pointed to the owning module (they execute a sliced runner body with injected boundaries; no seam exists for those boundaries yet): eng-seeded-completion-ai, plan-floor-permission, plan-create-prepublication, plan-count-completion; hermetic-wiring's source guard now reads pty/launch.ts and scans every pty/ module for raw process.env spreads. - plan-count-timeout and pty-output-wake mock the viewport at pty/screen.ts. * test(ratchet-c): enforcing module/function size ratchet and moved-code touchfile coverage Ratchet (c) ships enforcing: test/helpers/module-size.ts counts file and top-level function lengths by brace matching over masked source (strings, comments, regex literals and template text masked; ${} expressions kept), covering function declarations, arrow functions assigned to consts and route-table handler properties, with no parser dependency. Its self-test uses template literals and code-fence braces copied from scripts/resolvers/review.ts and design.ts. test/fixtures/module-size-ratchet.json binds scripts/lib/shard-engine.ts (<= 800 lines, <= 150 per function) and records the residual runner sizes (free 2352, paid 1921) as non-growth caps; allowlist entries are keyed on file plus matched text and need a reason. Failure output lists file:line, the rule, Fix: and the allowlist path. touchfiles.test.ts gains the moved-code superset check over test/fixtures/touchfile-move-goldens/ (W2 golden recorded at96764e80: test-strict-output.ts and test-paid-shards.ts global, test-free-shards.ts none). * refactor(browse): declared route table replaces the buildFetchHandler if-chain The ~1,300-line if-chain in buildFetchHandler becomes a route table: each entry declares method, path, auth kind and surfaces, and one auth gate in browse/src/routes/table.ts returns the per-kind denial (root-bearer, scoped, root-or-sse-cookie: 401 Unauthorized; root-token: 403 Root token required; extension-origin: 403 Forbidden). Unmatched requests take the declared fallthrough (root-bearer check, then plain-text 404). Handlers move to browse/src/routes/{core,pairing,pty,tokens,tunnel,activity,commands,files, inspector}.ts and receive a RouteContext with auth checks as functions instead of closing over factory locals. Dispatch order is unchanged: tunnel filter, beforeRoute overlay, gate, handler. TUNNEL_PATHS stays a literal in server.ts. Behavior-preserving: the black-box auth matrix from the previous commit passes unchanged. /memory and /inspector/events are declared root-bearer because the blanket check always ran before their SSE-cookie branch. Source-text route tests are rewritten as behavioral tests through buildFetchHandler or a route's real handler with a stub RouteContext (browse/test/route-test-harness.ts). Checks with no runtime seam are re-pointed to the route modules: Surface type, /inspector/events SSE helper, sanitizeReplacer imports, /pty-inject-scan sidecar-client import, and the ngrok config lookup and startTunnel wiring that stay in server.ts. * test(browse): stubbed-handler auth matrix and route inventory for the route table Every ROUTES entry runs through the real dispatcher and gate with stub handlers on each declared surface and six credentials; denials assert the exact status and body each auth kind returned at96764e8, admitted credentials assert the handler ran (with the gate's TokenInfo for scoped routes). Also pins the reviewed route inventory (method, path, auth kind, surfaces), that every entry declares auth and surfaces, that the table's tunnel paths equal the TUNNEL_PATHS literal with GET /connect admitted, the unmatched fallthrough, and that the root token is rejected on every tunnel route through buildFetchHandler. * test(browse): ratchet (b) keeps route dispatch inside the route table Scans browse/src/server.ts and browse/src/routes/*.ts for pathname comparisons; only the table matcher and the tunnel-surface filter are allowed, listed with reasons in browse/test/fixtures/route-dispatch-allowlist.json (keyed on file plus line text). Also checks every entry declares auth and surfaces and that gstack registers no beforeRoute overlay itself. Self-tests plant a violation and assert the file:line, Fix: and allowlist path in the message, that a shifted line stays allowlisted, and that a reasonless entry is rejected. * test: touchfile superset check for modules moved out of browse/src/server.ts Records the paid evals selected by touching browse/src/server.ts at96764e80(17 E2E, 1 LLM judge) and asserts every browse/src/routes/*.ts module selects a superset. The test reads every golden in test/fixtures/moved-module-selection/ so other moved-code goldens can sit beside it. * test(shard-engine): give non-timeout corpus fixtures CI headroom; keep the POSIX golden off the Windows lane Only the wall-timeout fixture keeps a 3s wall; the rest get 60s so a loaded host cannot turn a pass into a timeout. Base and branch runners still agree on every classification under the new walls. The Windows exclusion entry moves the free runner's ratchet (c) residual cap to 2356 lines. * refactor(pty): one runPtySession loop drives observation, counting and floor test/helpers/pty/session.ts owns launch -> start -> (poll -> tick)* -> timeout and the failure contract the three runners each hand-rolled: the run's own error wins over capture and close errors, close always runs, owned fixture cleanup runs last (also when launch fails). Each runner now supplies a PtySessionPlan: its boot/command step, poll cadence (2s observation/floor sleep; counting's output wake + 250ms coalesce), tick policy (permission handling, native identity, terminal rules stay per runner because they differ) and capture hooks. The runner bodies are decomposed into top-level steps so no function exceeds 150 lines; behavior is unchanged and the fake-driver cases from the first W4 commit pass unmodified. The counting capture step and the native completion-summary predicate are now named functions (countingCapture, isNativeCompletionSummary), so plan-create-prepublication and plan-count-completion call them directly instead of executing sliced source. The two harnesses that still execute a sliced runner body with injected boundaries (eng-seeded-completion-ai, plan-floor-permission) pass the PtyDriver seam instead of overriding Date/Bun.sleep. * test(ratchet-c): register route modules, review resolver modules and server.ts residual cap * refactor(pty): decompose launchClaudePty and engNumberedFindingAUQ under 150 lines launchClaudePty (349 lines) becomes launch preparation (args, hermetic child env, owned state roots), recorder creation, spawn, the trust-dialog watcher, close, and the session handle over one PtyProcess state object. The failure order is unchanged: abort the viewport, dispose any recorders created so far, dispose the viewport, rethrow. The --model / --strict-mcp-config ordering and seedSkills wiring stay pinned by the behavioral fake-CLI tests. engNumberedFindingAUQ (345 lines) keeps its guards and dispatch; each self-contained issue family (declared cache, library retry hooks, cache owner, injected singleton, shared writers, injected export) moves verbatim into its own function. Every pty/ module is now <= 800 lines and every top-level function <= 150 lines. * test(pty): split claude-pty-runner.unit.test.ts along the pty/ module seams The 188 unit tests move verbatim into claude-pty-runner.{screen,classify, auq,launch,plan-native,boundaries}.unit.test.ts (test names unchanged; each file imports only what it uses from the barrel). The five files that no longer read a SKILL.md template join the test-of-test ratchet baseline with a reason. * test(touchfiles): moved PTY modules keep their paid-eval selection test/fixtures/touchfile-selection/w4-pty.json records, at96764e8, the paid evals selected by touching test/helpers/claude-pty-runner.ts (20) and test/helpers/pty-screen.ts (20). touchfiles.test.ts now asserts every .ts file under test/helpers/pty/ (and pty/screen.ts for both sources) selects a superset, reading every golden in that directory so later moves can add one; a planted-violation case pins the report and its Fix line. * fix(browse): unexchanged pair setup keys no longer authenticate bearer requests validateToken accepted a gsk_setup_ key as a bearer on /command, /batch and /file (found while building the W3 auth matrix). A setup key now only authenticates the /connect exchange. * W1: one state-root owner (lib/state-root.ts + bin/gstack-state-root.sh), gstack-paths --explain and fail-stop, parity tests * W1: guarded migration of every executable state-root site; uninstall deletes only ~/.gstack Bins, careful/freeze hooks, setup, upgrade migrations, browse/src, design, ios-qa daemon, lib and scripts resolve the state root through bin/gstack-state-root.sh (bash) or lib/state-root.ts (TS). Bins source the twin and stop with a reinstall message when it is missing; hooks source it and never spawn gstack-paths. browse/src/config.ts and lib/cso/state.ts delegate to resolveStateRoot. Analytics writers and readers move together so the usage log stays one file. gstack-uninstall deletes state only at ~/.gstack, refuses (exit 2) when it resolves to /, $HOME or an ancestor, the checkout or the git root, and leaves any other resolved root in place with the removal command. Fixtures that copy single bins now copy the twin. * W1: privacy keys and trust-policy deny tiers merge across state roots; gstack-config reporting; test hermeticity readConfigKey / gstack_read_config_key return the most restrictive telemetry, memorable_recall, codex_reviews and update_check across the resolved root and ~/.gstack; other keys read the resolved root only. gstack-config set reports an overriding root with the exact override command, list shows the winning root and a root-variable disagreement line. gstack-gbrain-repo-policy get merges deny/read-only tiers. gstack-egress reads through readConfigKey. test-setup.ts strips inherited GSTACK_STATE_ROOT/GSTACK_STATE_DIR and redirects the legacy root. * W1: shared hook logging helper (hosts/claude/hooks/hook-log.ts) One hook-errors.log writer: root from resolveStateRoot, 0600 on every append, opt-in rate limit used only by memorable-user-prompt. The five hooks route through it. * W1: docs/state-root.md and README troubleshooting pointer Precedence table, a real --explain example, the move-your-state recipe, merged privacy keys, the uninstall rule, the resolver-failure fix, and the plugin-mode note (evidence gate: no official plugin distribution). * W1b: template and resolver prose resolve state through guarded gstack-paths; ratchet (a) Every gstack-paths eval in templates and resolvers carries the fail-stop guard; executable ~/.gstack paths in bash blocks (context recovery preamble, eureka log, analytics, project artifacts, upgrade snooze, setup-gbrain lock, retro snapshots, ship consent marker) use $GSTACK_STATE_ROOT, and the writer prose that pairs with them points at the printed PROJECT_DIR / RETRO_FILE. ship drops export GSTACK_STATE_ROOT. SKILL.md regenerated (claude + codex), ship goldens re-pinned, parity and context-budget caps raised to the measured sizes with notes. test/state-root-ratchet.test.ts enforces the rule with a reasoned allowlist; W1 touchfile entries plus a superset golden. * refactor: apply W1 state-root edits in W2/W3/W5-owned files; one moved-code touchfile golden for all workstreams * test: fold the moved-code touchfile golden into touchfiles.test.ts; fix integration fixture closure and caps * v1.91.11.0: CHANGELOG, TODOS, docs and conventions for the refactor wave * test: re-measure plan-ceo/design-consultation caps and ship goldens after the guarded plan-discovery and spec-review blocks; add the state-root twin to the workflow-boundaries fixture * fix(windows): migrations resolve their directory with either path separator; state-root parity compares under the HOME Git Bash actually sees * fix(review,ship): state plan-check timing after smoke expiry and test_stub Skip semantics (review workflow judge clarity) * test(qa-eval): webhook fix eval asks for the fix loop's post-repair probes; eight-scenario coverage stays in the report-only case and the harness recheck * test(qa-eval): re-pin the webhook prompt contract to the fix-loop stage; R29 coverage omissions stay bound by the report-only case * fix(review,ship): plan checks publish a checkpoint before each probe; only the smoke expiry stop is skipped * fix(qa): carry #2999's checkpoint receipt link, report-template line and full-revision placeholder (identical hunks) * test(qa-callers): disable git auto maintenance in the caller fixture Git 2.47+ runs auto maintenance detached after commit; on the CI runner's git 2.55 it rewrote .git/objects fan-out directories while the write observer was running, which surfaced as unauthorized mutations. Same gc.auto=0 / maintenance.auto=false guard the shared-libs fixture already uses. * test(plan-mode-no-op): require prose evidence for the prose-fallback members so a spinner-frame judge verdict cannot end the run as asked * test(ship-docsync): carry #2999's seeded-attempt docsync harness (identical files) The doc-sync fault cases replayed attempt 1 before reaching their gate and ran out of their 285s budget. The fixture now seeds attempt 1 and the parent starts at the gate under test. Taken byte-identical from origin/capy/audit-fix-wave (fb526898,e6ac813d,6ce10ff7,d0c53577,77cce3be). Local: stale-before, recovery and late-result 6/6 PASS (97-164s); the whole file 12/12 PASS.
1047 lines
45 KiB
TypeScript
Executable File
1047 lines
45 KiB
TypeScript
Executable File
#!/usr/bin/env bun
|
|
/**
|
|
* gstack-brain-cache — three-tier cache for brain-aware planning skills.
|
|
*
|
|
* Subcommands:
|
|
* get <entity-name> [--project <slug>] — return digest content; refresh if stale
|
|
* refresh [--full] [--entity X] [--project <slug>] — force refresh one or all
|
|
* invalidate <entity-name> [--project <slug>] — mark stale; next get triggers cold
|
|
* digest <entity-slug> — compress a brain page slug to digest
|
|
* meta [--project <slug>] — print _meta.json
|
|
*
|
|
* (Later commits add: bootstrap [T2b], list [T18], purge [T18], retention sweep [T18].)
|
|
*
|
|
* Cache layout:
|
|
* ~/.gstack/brain-cache/ ← cross-project (user-profile only)
|
|
* ~/.gstack/projects/<slug>/brain-cache/ ← per-project (everything else)
|
|
*
|
|
* Atomic writes via .tmp + rename. Stale-but-usable fallback when brain
|
|
* unreachable. Concurrent-refresh dedup is a follow-up commit (T15).
|
|
*/
|
|
|
|
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, statSync, unlinkSync, readdirSync, openSync, closeSync } from 'fs';
|
|
import { join, dirname } from 'path';
|
|
import { homedir, hostname } from 'os';
|
|
import { spawnSync } from 'child_process';
|
|
import { resolveStateRoot } from '../lib/state-root';
|
|
import { execGbrainJson, spawnGbrain } from '../lib/gbrain-exec';
|
|
import {
|
|
BRAIN_CACHE_ENTITIES,
|
|
CACHE_REFRESH_LOCK_TIMEOUT_MS,
|
|
GSTACK_SCHEMA_PACK_NAME,
|
|
GSTACK_SCHEMA_PACK_VERSION,
|
|
SALIENCE_DEFAULT_ALLOWLIST,
|
|
type BrainCacheEntity,
|
|
} from '../scripts/brain-cache-spec';
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Paths + meta
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
const GSTACK_HOME = resolveStateRoot();
|
|
|
|
interface CacheMeta {
|
|
/** Version of the schema pack the cache was built against. Mismatch → full rebuild. */
|
|
schema_version: string;
|
|
/** SHA8 hash of the brain MCP endpoint URL (or 'local' for on-disk engines). */
|
|
endpoint_hash: string;
|
|
/** Per-entity last-refresh epoch ms. Absent → never refreshed. */
|
|
last_refresh: Record<string, number>;
|
|
/** Per-entity last-attempt epoch ms (even if attempt failed). For stale-but-usable diagnostics. */
|
|
last_attempt?: Record<string, number>;
|
|
}
|
|
|
|
/** Returns the directory holding a given entity's cache file. */
|
|
export function entityDir(entity: BrainCacheEntity, projectSlug: string | null): string {
|
|
if (entity.scope === 'cross-project') {
|
|
return join(GSTACK_HOME, 'brain-cache');
|
|
}
|
|
if (!projectSlug) {
|
|
throw new Error(`Per-project entity needs a project slug: ${entity.file}`);
|
|
}
|
|
return join(GSTACK_HOME, 'projects', projectSlug, 'brain-cache');
|
|
}
|
|
|
|
/** Returns the path to the cache file for a given entity. */
|
|
export function entityPath(entityName: string, projectSlug: string | null): string {
|
|
const entity = BRAIN_CACHE_ENTITIES[entityName];
|
|
if (!entity) throw new Error(`Unknown brain cache entity: ${entityName}`);
|
|
return join(entityDir(entity, projectSlug), entity.file);
|
|
}
|
|
|
|
/** Returns the path to the _meta.json for a given scope. */
|
|
export function metaPath(scope: 'cross-project' | 'per-project', projectSlug: string | null): string {
|
|
if (scope === 'cross-project') {
|
|
return join(GSTACK_HOME, 'brain-cache', '_meta.json');
|
|
}
|
|
if (!projectSlug) throw new Error('Per-project meta needs a project slug');
|
|
return join(GSTACK_HOME, 'projects', projectSlug, 'brain-cache', '_meta.json');
|
|
}
|
|
|
|
function loadMeta(scope: 'cross-project' | 'per-project', projectSlug: string | null): CacheMeta {
|
|
const path = metaPath(scope, projectSlug);
|
|
if (!existsSync(path)) {
|
|
return { schema_version: GSTACK_SCHEMA_PACK_VERSION, endpoint_hash: detectEndpointHash(), last_refresh: {}, last_attempt: {} };
|
|
}
|
|
try {
|
|
const parsed = JSON.parse(readFileSync(path, 'utf-8')) as unknown;
|
|
// #1879: a valid JSON file can still be the wrong shape. JSON.parse can return
|
|
// null/array/string/number, and a partial object can omit last_refresh — three
|
|
// consumers (isStale, cmdInvalidate, refreshEntity) dereference meta.last_refresh
|
|
// unguarded and crash with a TypeError.
|
|
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
return { schema_version: GSTACK_SCHEMA_PACK_VERSION, endpoint_hash: detectEndpointHash(), last_refresh: {}, last_attempt: {} };
|
|
}
|
|
const meta = parsed as CacheMeta;
|
|
// Normalize ONLY the dereferenced maps. Do NOT default schema_version /
|
|
// endpoint_hash — leaving them absent makes schemaVersionMismatch() /
|
|
// endpointSwitched() correctly force a rebuild (missing identity = mismatch =
|
|
// safe). Defaulting them to current values would suppress invalidation and
|
|
// trust a stale file of unknown provenance.
|
|
meta.last_refresh = meta.last_refresh ?? {};
|
|
meta.last_attempt = meta.last_attempt ?? {};
|
|
return meta;
|
|
} catch {
|
|
// Corrupt _meta — start fresh (entries will refresh on next access).
|
|
return { schema_version: GSTACK_SCHEMA_PACK_VERSION, endpoint_hash: detectEndpointHash(), last_refresh: {}, last_attempt: {} };
|
|
}
|
|
}
|
|
|
|
function saveMeta(scope: 'cross-project' | 'per-project', projectSlug: string | null, meta: CacheMeta): void {
|
|
const path = metaPath(scope, projectSlug);
|
|
mkdirSync(dirname(path), { recursive: true });
|
|
atomicWrite(path, JSON.stringify(meta, null, 2));
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Endpoint hash detection
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
import { createHash } from 'crypto';
|
|
|
|
function sha8(input: string): string {
|
|
return createHash('sha256').update(input).digest('hex').slice(0, 8);
|
|
}
|
|
|
|
/**
|
|
* Detects the active brain endpoint (MCP URL or 'local') and returns its
|
|
* stable identity hash. Used to detect when the user switches brains
|
|
* (different endpoint → different cache).
|
|
*
|
|
* Reads BOTH registration scopes in ~/.claude.json (#2499): project scope
|
|
* (.projects["/abs/path"].mcpServers.gbrain — what `claude mcp add`
|
|
* WITHOUT --scope user writes) first, preferring the nearest ancestor of
|
|
* cwd (longest matching project key) so nested repos resolve to their own
|
|
* brain, then user scope (.mcpServers.gbrain) as the fallback. That order
|
|
* is Claude Code's own name-conflict precedence (local beats user) —
|
|
* verified empirically against claude 2.1.233 with a hermetic fake $HOME:
|
|
* `claude mcp get gbrain` reports "Scope: Local config" and the
|
|
* project-local URL when both scopes define the name — so the hash tracks
|
|
* the endpoint the project actually talks to. Before the project-scope
|
|
* read, two different project-scoped brains both hashed to 'local', so
|
|
* switching between them never invalidated the cache — the exact scenario
|
|
* this function exists to catch.
|
|
*
|
|
* Params exist for tests; production callers use the defaults.
|
|
*/
|
|
export function detectEndpointHash(
|
|
claudeJsonPath: string = join(homedir(), '.claude.json'),
|
|
cwd: string = process.cwd(),
|
|
): string {
|
|
if (existsSync(claudeJsonPath)) {
|
|
try {
|
|
const cfg = JSON.parse(readFileSync(claudeJsonPath, 'utf-8'));
|
|
const gbrainServer = resolveGbrainMcpEntry(cfg, cwd);
|
|
const url = gbrainServer?.url || gbrainServer?.transport?.url;
|
|
if (typeof url === 'string' && url.length > 0) {
|
|
return sha8(url);
|
|
}
|
|
} catch { /* fall through to local */ }
|
|
}
|
|
// Local engine — no endpoint URL; use a stable literal hash.
|
|
return 'local';
|
|
}
|
|
|
|
interface McpEntryish {
|
|
url?: unknown;
|
|
transport?: { url?: unknown };
|
|
}
|
|
|
|
/**
|
|
* Nearest-ancestor project-scope gbrain entry for cwd, else the user-scope
|
|
* entry (#2499). Project-local first — Claude Code's own precedence for a
|
|
* same-name conflict (see detectEndpointHash's docstring for the empirical
|
|
* evidence). Path-boundary-aware: /a/repo never matches /a/repo2. Both
|
|
* separators are accepted so Windows project keys resolve.
|
|
*/
|
|
function resolveGbrainMcpEntry(
|
|
cfg: unknown,
|
|
cwd: string,
|
|
): McpEntryish | undefined {
|
|
const root = cfg as {
|
|
mcpServers?: Record<string, McpEntryish>;
|
|
projects?: Record<string, { mcpServers?: Record<string, McpEntryish> }>;
|
|
} | null;
|
|
const projects = root?.projects;
|
|
if (projects && typeof projects === 'object') {
|
|
let best: { key: string; entry: McpEntryish } | undefined;
|
|
for (const [key, val] of Object.entries(projects)) {
|
|
if (!val || typeof val !== 'object') continue;
|
|
const entry = val.mcpServers?.gbrain;
|
|
if (!entry || typeof entry !== 'object') continue;
|
|
const isAncestor =
|
|
cwd === key || cwd.startsWith(`${key}/`) || cwd.startsWith(`${key}\\`);
|
|
if (!isAncestor) continue;
|
|
if (!best || key.length > best.key.length) best = { key, entry };
|
|
}
|
|
if (best) return best.entry;
|
|
}
|
|
return root?.mcpServers?.gbrain;
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Atomic write (tmp + rename)
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
function atomicWrite(path: string, content: string): void {
|
|
mkdirSync(dirname(path), { recursive: true });
|
|
const tmp = `${path}.tmp.${process.pid}.${Date.now()}`;
|
|
writeFileSync(tmp, content, 'utf-8');
|
|
renameSync(tmp, path);
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Staleness + refresh logic
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
/** Returns true if the cached digest is past its TTL. */
|
|
function isStale(entityName: string, meta: CacheMeta): boolean {
|
|
const entity = BRAIN_CACHE_ENTITIES[entityName];
|
|
if (!entity) return true;
|
|
const last = meta.last_refresh[entityName];
|
|
if (!last) return true;
|
|
return Date.now() - last > entity.ttl_ms;
|
|
}
|
|
|
|
/** Returns true if the cache file exists on disk. */
|
|
function hasFile(entityName: string, projectSlug: string | null): boolean {
|
|
return existsSync(entityPath(entityName, projectSlug));
|
|
}
|
|
|
|
/** Returns true if schema version recorded in meta differs from current pack version. */
|
|
function schemaVersionMismatch(meta: CacheMeta): boolean {
|
|
return meta.schema_version !== GSTACK_SCHEMA_PACK_VERSION;
|
|
}
|
|
|
|
/** Returns true if endpoint hash recorded in meta differs from current detected endpoint. */
|
|
function endpointSwitched(meta: CacheMeta): boolean {
|
|
return meta.endpoint_hash !== detectEndpointHash();
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Subcommand: get
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
interface GetResult {
|
|
/** Path to the digest file. */
|
|
path: string;
|
|
/** Cache state: 'warm' (fresh + valid), 'cold-refreshed' (was stale, refreshed inline), 'stale-fallback' (used stale because refresh failed), 'missing' (no cache and no refresh). */
|
|
state: 'warm' | 'cold-refreshed' | 'stale-fallback' | 'missing';
|
|
/** Optional message for diagnostics. */
|
|
message?: string;
|
|
}
|
|
|
|
export function cmdGet(entityName: string, projectSlug: string | null): GetResult {
|
|
const entity = BRAIN_CACHE_ENTITIES[entityName];
|
|
if (!entity) throw new Error(`Unknown entity: ${entityName}`);
|
|
const scope = entity.scope;
|
|
const meta = loadMeta(scope, projectSlug);
|
|
|
|
// Schema-version mismatch → full rebuild (D4 A4).
|
|
if (schemaVersionMismatch(meta) || endpointSwitched(meta)) {
|
|
rebuildAllForScope(scope, projectSlug);
|
|
// After rebuild, meta is fresh; fall through to warm path.
|
|
const newMeta = loadMeta(scope, projectSlug);
|
|
if (hasFile(entityName, projectSlug) && !isStale(entityName, newMeta)) {
|
|
return { path: entityPath(entityName, projectSlug), state: 'warm' };
|
|
}
|
|
// Rebuild may have failed for this entity specifically.
|
|
return { path: entityPath(entityName, projectSlug), state: 'missing', message: 'rebuild after schema/endpoint change' };
|
|
}
|
|
|
|
if (hasFile(entityName, projectSlug) && !isStale(entityName, meta)) {
|
|
return { path: entityPath(entityName, projectSlug), state: 'warm' };
|
|
}
|
|
|
|
// Stale or missing — try cold refresh.
|
|
const refreshed = refreshEntity(entityName, projectSlug);
|
|
if (refreshed) {
|
|
return { path: entityPath(entityName, projectSlug), state: 'cold-refreshed' };
|
|
}
|
|
// Refresh failed. Use stale-but-usable if file exists.
|
|
if (hasFile(entityName, projectSlug)) {
|
|
return { path: entityPath(entityName, projectSlug), state: 'stale-fallback', message: 'brain unreachable; using stale cache' };
|
|
}
|
|
// No cache and no refresh = missing.
|
|
return { path: entityPath(entityName, projectSlug), state: 'missing', message: 'brain unreachable; no cache available' };
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Subcommand: refresh
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Lockfile dedup (T15 / D3)
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Returns the lock file path for a project scope. Cross-project entities
|
|
* still lock per-project (the project triggering the refresh holds the lock);
|
|
* concurrent attempts from different projects on cross-project entities
|
|
* serialize naturally because they're rare and the lock window is short.
|
|
*/
|
|
function lockPath(projectSlug: string | null): string {
|
|
const dir = projectSlug
|
|
? join(GSTACK_HOME, 'projects', projectSlug, 'brain-cache')
|
|
: join(GSTACK_HOME, 'brain-cache');
|
|
return join(dir, '.refresh.lock');
|
|
}
|
|
|
|
interface LockHandle {
|
|
fd: number;
|
|
path: string;
|
|
}
|
|
|
|
/**
|
|
* Try to acquire the refresh lock. Returns null when another process holds it
|
|
* (and the lock is fresh). Stale locks (process dead OR older than the
|
|
* timeout) are taken over.
|
|
*/
|
|
function tryAcquireLock(projectSlug: string | null): LockHandle | null {
|
|
const path = lockPath(projectSlug);
|
|
mkdirSync(dirname(path), { recursive: true });
|
|
|
|
// If a lock exists, see if it's stale
|
|
if (existsSync(path)) {
|
|
try {
|
|
const raw = readFileSync(path, 'utf-8');
|
|
const lock = JSON.parse(raw) as { pid: number; host: string; ts: number };
|
|
const age = Date.now() - lock.ts;
|
|
const sameHost = lock.host === hostname();
|
|
const processGone = sameHost && lock.pid > 0 && !isPidAlive(lock.pid);
|
|
if (age <= CACHE_REFRESH_LOCK_TIMEOUT_MS && !processGone) {
|
|
return null; // someone else holds a fresh lock
|
|
}
|
|
// Stale: take over
|
|
} catch {
|
|
// Corrupt lock file → take over
|
|
}
|
|
}
|
|
|
|
// Write our lock (best-effort O_EXCL via tmp+rename for atomic creation)
|
|
const payload = JSON.stringify({ pid: process.pid, host: hostname(), ts: Date.now() });
|
|
const tmp = `${path}.tmp.${process.pid}.${Date.now()}`;
|
|
try {
|
|
writeFileSync(tmp, payload);
|
|
renameSync(tmp, path);
|
|
} catch (err) {
|
|
return null;
|
|
}
|
|
|
|
// Race: another process may have raced us. Re-read and verify ownership.
|
|
try {
|
|
const raw = readFileSync(path, 'utf-8');
|
|
const lock = JSON.parse(raw) as { pid: number; host: string };
|
|
if (lock.pid !== process.pid || lock.host !== hostname()) {
|
|
return null;
|
|
}
|
|
} catch {
|
|
return null;
|
|
}
|
|
return { fd: -1, path };
|
|
}
|
|
|
|
function releaseLock(handle: LockHandle): void {
|
|
try { unlinkSync(handle.path); } catch { /* best effort */ }
|
|
}
|
|
|
|
function isPidAlive(pid: number): boolean {
|
|
try {
|
|
process.kill(pid, 0);
|
|
return true;
|
|
} catch (err: any) {
|
|
if (err?.code === 'EPERM') return true; // exists but we don't own it
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Run a refresh callback under the project-scoped lock. If another refresh is
|
|
* already in flight, returns 'dedup' and the caller can either wait + retry
|
|
* (the resolver does this) or fall through to stale-but-usable. Stale locks
|
|
* (process dead, or older than CACHE_REFRESH_LOCK_TIMEOUT_MS) are taken over.
|
|
*/
|
|
export function withRefreshLock<T>(projectSlug: string | null, fn: () => T): T | 'dedup' {
|
|
const handle = tryAcquireLock(projectSlug);
|
|
if (!handle) return 'dedup';
|
|
try {
|
|
return fn();
|
|
} finally {
|
|
releaseLock(handle);
|
|
}
|
|
}
|
|
|
|
/** Refreshes one entity from the brain. Returns true on success. */
|
|
export function refreshEntity(entityName: string, projectSlug: string | null): boolean {
|
|
const entity = BRAIN_CACHE_ENTITIES[entityName];
|
|
if (!entity) return false;
|
|
|
|
// Mark attempt
|
|
const meta = loadMeta(entity.scope, projectSlug);
|
|
meta.last_attempt = meta.last_attempt || {};
|
|
meta.last_attempt[entityName] = Date.now();
|
|
|
|
// Fetch from brain. The actual fetch logic varies per entity — derived digests
|
|
// (recent-decisions, salience) need different queries from direct page reads.
|
|
// For T2a we implement the direct-page path; derived digests get filled in by
|
|
// the resolver / write-back paths in later commits.
|
|
const digestContent = fetchAndCompressEntity(entityName, projectSlug);
|
|
if (digestContent === null) {
|
|
saveMeta(entity.scope, projectSlug, meta);
|
|
return false;
|
|
}
|
|
|
|
// Enforce per-entity budget by truncating from end (oldest items live there
|
|
// by convention in our compressor). The per-skill budget is separately
|
|
// enforced at preflight injection time.
|
|
let final = digestContent;
|
|
if (Buffer.byteLength(final, 'utf-8') > entity.budget_bytes) {
|
|
final = truncateToBudget(final, entity.budget_bytes);
|
|
}
|
|
|
|
atomicWrite(entityPath(entityName, projectSlug), final);
|
|
meta.last_refresh[entityName] = Date.now();
|
|
// Keep schema/endpoint identity fresh.
|
|
meta.schema_version = GSTACK_SCHEMA_PACK_VERSION;
|
|
meta.endpoint_hash = detectEndpointHash();
|
|
saveMeta(entity.scope, projectSlug, meta);
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Refresh all entities for a scope (per-project or cross-project).
|
|
* Used by --full and by schema/endpoint-change rebuilds.
|
|
*/
|
|
export function refreshAll(projectSlug: string | null): { success: number; failed: number } {
|
|
let success = 0;
|
|
let failed = 0;
|
|
for (const [name, entity] of Object.entries(BRAIN_CACHE_ENTITIES)) {
|
|
// Cross-project entities only refresh when explicitly targeted via no-slug calls
|
|
if (entity.scope === 'cross-project' && projectSlug) continue;
|
|
if (entity.scope === 'per-project' && !projectSlug) continue;
|
|
if (refreshEntity(name, projectSlug)) success++; else failed++;
|
|
}
|
|
return { success, failed };
|
|
}
|
|
|
|
/** Rebuild on schema-version mismatch or endpoint switch. Wipes affected scope first. */
|
|
function rebuildAllForScope(scope: 'cross-project' | 'per-project', projectSlug: string | null): void {
|
|
// Wipe files but preserve dir; meta gets fully rewritten by refreshes below.
|
|
for (const [name, entity] of Object.entries(BRAIN_CACHE_ENTITIES)) {
|
|
if (entity.scope !== scope) continue;
|
|
const p = entityPath(name, projectSlug);
|
|
if (existsSync(p)) {
|
|
try { unlinkSync(p); } catch { /* best effort */ }
|
|
}
|
|
}
|
|
// Fresh meta starts here
|
|
const fresh: CacheMeta = {
|
|
schema_version: GSTACK_SCHEMA_PACK_VERSION,
|
|
endpoint_hash: detectEndpointHash(),
|
|
last_refresh: {},
|
|
last_attempt: {},
|
|
};
|
|
saveMeta(scope, projectSlug, fresh);
|
|
// Refresh all entities in this scope
|
|
for (const [name, entity] of Object.entries(BRAIN_CACHE_ENTITIES)) {
|
|
if (entity.scope !== scope) continue;
|
|
refreshEntity(name, projectSlug);
|
|
}
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Subcommand: invalidate
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
export function cmdInvalidate(entityName: string, projectSlug: string | null): void {
|
|
const entity = BRAIN_CACHE_ENTITIES[entityName];
|
|
if (!entity) throw new Error(`Unknown entity: ${entityName}`);
|
|
const meta = loadMeta(entity.scope, projectSlug);
|
|
delete meta.last_refresh[entityName];
|
|
saveMeta(entity.scope, projectSlug, meta);
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Fetch + compress per-entity
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Returns the digest markdown content for an entity, or null if the brain is
|
|
* unreachable / the source page doesn't exist.
|
|
*
|
|
* For T2a we implement the entity → page-slug mapping for the simple cases.
|
|
* Derived digests (recent-decisions, salience) get specialized paths.
|
|
*/
|
|
function fetchAndCompressEntity(entityName: string, projectSlug: string | null): string | null {
|
|
switch (entityName) {
|
|
case 'user-profile':
|
|
return fetchUserProfile();
|
|
case 'product':
|
|
return fetchProduct(projectSlug);
|
|
case 'goals':
|
|
return fetchGoals(projectSlug);
|
|
case 'developer-persona':
|
|
return fetchSimplePage(`gstack/developer-persona/${projectSlug}`);
|
|
case 'brand':
|
|
return fetchSimplePage(`gstack/brand/${projectSlug}`);
|
|
case 'competitive-intel':
|
|
return fetchSimplePage(`gstack/competitive-intel/${projectSlug}`);
|
|
case 'recent-decisions':
|
|
return fetchRecentDecisions(projectSlug);
|
|
case 'salience':
|
|
// D9 salience allowlist applied in T17 commit; T2a returns raw output for now.
|
|
return fetchSalience(projectSlug);
|
|
default:
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Generic single-page fetch via `gbrain get`. Returns null on miss/unreachable. */
|
|
function fetchSimplePage(slug: string): string | null {
|
|
const result = spawnGbrain(['get', slug, '--json'], { timeout: 10_000 });
|
|
if (result.status !== 0) return null;
|
|
try {
|
|
const page = JSON.parse(result.stdout) as { body?: string; title?: string };
|
|
if (!page?.body) return null;
|
|
return compressPage(slug, page.title || slug, page.body);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function fetchUserProfile(): string | null {
|
|
// The user-slug discovery is implemented in T16 (D4 A3). For T2a we accept
|
|
// env GSTACK_USER_SLUG as override, fallback to $USER for direct calls.
|
|
const slug = process.env.GSTACK_USER_SLUG || process.env.USER || 'unknown';
|
|
return fetchSimplePage(`gstack/user-profile/${slug}`);
|
|
}
|
|
|
|
function fetchProduct(projectSlug: string | null): string | null {
|
|
if (!projectSlug) return null;
|
|
return fetchSimplePage(`gstack/product/${projectSlug}`);
|
|
}
|
|
|
|
/**
|
|
* Goals are LIST queries: all gstack/goal/<project>/* pages.
|
|
* Compress the top N by recency.
|
|
*/
|
|
function fetchGoals(projectSlug: string | null): string | null {
|
|
if (!projectSlug) return null;
|
|
const result = execGbrainJson<{ pages?: Array<{ slug: string; title?: string; body?: string }> }>([
|
|
'list-pages',
|
|
'--type', 'gstack/goal',
|
|
'--limit', '10',
|
|
'--json',
|
|
]);
|
|
if (!result?.pages) return null;
|
|
const goals = result.pages.filter((p) => p.slug?.startsWith(`gstack/goal/${projectSlug}/`));
|
|
if (goals.length === 0) {
|
|
// Empty digest is valid (just header + 'no active goals' line)
|
|
return `# Active goals (project: ${projectSlug})\n\n_No active goals recorded yet._\n`;
|
|
}
|
|
const lines = goals.map((g) => `- [[${g.slug}]] — ${g.title || '(untitled)'}`);
|
|
return `# Active goals (project: ${projectSlug})\n\n${lines.join('\n')}\n`;
|
|
}
|
|
|
|
/**
|
|
* recent-decisions: last 5 gstack/skill-run pages for this project, compressed
|
|
* to one-line summaries.
|
|
*/
|
|
function fetchRecentDecisions(projectSlug: string | null): string | null {
|
|
if (!projectSlug) return null;
|
|
const result = execGbrainJson<{ pages?: Array<{ slug: string; title?: string }> }>([
|
|
'list-pages',
|
|
'--type', 'gstack/skill-run',
|
|
'--limit', '5',
|
|
'--sort', 'updated_desc',
|
|
'--json',
|
|
]);
|
|
if (!result?.pages) {
|
|
// F10 bug fix: this branch used to return the hardcoded
|
|
// "_No prior skill runs recorded._" string here, which is indistinguishable
|
|
// from a genuine zero-rows result. That silently converted a gbrain-
|
|
// unreachable FAILURE into a "successful" cached digest — refreshEntity()
|
|
// would write it and stamp last_refresh, so the false negative survived
|
|
// every subsequent TTL cycle forever. Returning null instead lets cmdGet's
|
|
// existing missing/stale-fallback machinery report the true state, exactly
|
|
// like every sibling fetcher (fetchGoals, fetchSimplePage) already does on
|
|
// failure.
|
|
return null;
|
|
}
|
|
// A malformed payload ({pages: {}} etc.) must classify as failure, not crash
|
|
// refreshEntity mid-refresh — same honest-missing polarity as the F10 fix.
|
|
if (!Array.isArray(result.pages)) return null;
|
|
if (result.pages.length === 0) {
|
|
return `# Recent decisions (project: ${projectSlug})\n\n_No prior skill runs recorded._\n`;
|
|
}
|
|
const lines = result.pages.map((p) => `- ${p.title || p.slug}`);
|
|
return `# Recent decisions (project: ${projectSlug})\n\n${lines.join('\n')}\n`;
|
|
}
|
|
|
|
/**
|
|
* Reads the user's salience allowlist override from gstack-config. If unset,
|
|
* returns SALIENCE_DEFAULT_ALLOWLIST. The override is comma-separated; we
|
|
* trim and drop empty entries.
|
|
*/
|
|
export function getSalienceAllowlist(): ReadonlyArray<string> {
|
|
// Short-circuit via env var for tests + headless callers.
|
|
const env = process.env.GSTACK_SALIENCE_ALLOWLIST;
|
|
if (typeof env === 'string' && env.length > 0) {
|
|
return env.split(',').map((s) => s.trim()).filter(Boolean);
|
|
}
|
|
// Shell out to gstack-config with a tight timeout. Falls back to defaults
|
|
// on any failure (config script missing, command non-zero, parse error).
|
|
try {
|
|
const skillRoot = join(homedir(), '.claude', 'skills', 'gstack');
|
|
const bin = join(skillRoot, 'bin', 'gstack-config');
|
|
if (!existsSync(bin)) return SALIENCE_DEFAULT_ALLOWLIST;
|
|
const result = spawnSync(bin, ['get', 'salience_allowlist'], { timeout: 2000, encoding: 'utf-8' });
|
|
if (result.status !== 0 || !result.stdout) return SALIENCE_DEFAULT_ALLOWLIST;
|
|
const trimmed = result.stdout.trim();
|
|
if (!trimmed) return SALIENCE_DEFAULT_ALLOWLIST;
|
|
const parts = trimmed.split(',').map((s) => s.trim()).filter(Boolean);
|
|
return parts.length > 0 ? parts : SALIENCE_DEFAULT_ALLOWLIST;
|
|
} catch {
|
|
return SALIENCE_DEFAULT_ALLOWLIST;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* D9 salience privacy gate: returns true if the slug starts with any allowlisted
|
|
* prefix. Anything NOT matching is stripped at digest write time so that family,
|
|
* therapy, reflection, and other sensitive content never leaks into work-flow
|
|
* planning prompts by default.
|
|
*/
|
|
export function isSalienceSlugAllowed(slug: string, allowlist: ReadonlyArray<string>): boolean {
|
|
for (const prefix of allowlist) {
|
|
if (slug.startsWith(prefix)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function fetchSalience(projectSlug: string | null): string | null {
|
|
// get-recent-salience is a gbrain CLI sub-shape; we use the MCP-shape JSON
|
|
const result = execGbrainJson<{ pages?: Array<{ slug: string; title?: string; emotional_weight?: number }> }>([
|
|
'get-recent-salience',
|
|
'--days', '14',
|
|
'--limit', '10',
|
|
'--json',
|
|
]);
|
|
// F10 bug fix (sibling of fetchRecentDecisions above): a gbrain-unreachable
|
|
// failure used to render the identical hardcoded "no salient pages" string
|
|
// as a genuine empty result, which refreshEntity() then cached as if it
|
|
// were verified truth. Unlike recent-decisions there is no project-local
|
|
// fallback for salience — it is specifically gbrain's emotional-weight-
|
|
// ranked *brain* pages, not project decision/work data, and conflating the
|
|
// two would defeat the D9 privacy allowlist's purpose. So on failure we
|
|
// return null and let the cache report 'missing' (same as product.md,
|
|
// goals.md, etc. already do on this machine) instead of asserting a claim
|
|
// we have no way to verify.
|
|
if (!result?.pages) return null;
|
|
|
|
// D9 privacy gate: strip entries outside the allowlist BEFORE rendering.
|
|
// Sensitive personal content (family, therapy, reflection) is never written
|
|
// into the digest cache file, even when the brain itself ranks it salient.
|
|
const allowlist = getSalienceAllowlist();
|
|
const filtered = result.pages.filter((p) => p.slug && isSalienceSlugAllowed(p.slug, allowlist));
|
|
const stripped = result.pages.length - filtered.length;
|
|
if (filtered.length === 0) {
|
|
const header = `# Recent salience (last 14d)`;
|
|
const note = stripped > 0
|
|
? `\n_All ${stripped} salient entries stripped by allowlist gate (no work-flow content in window)._\n`
|
|
: `\n_No salient pages in last 14d._\n`;
|
|
return `${header}\n${note}`;
|
|
}
|
|
const lines = filtered.map((p) => `- [[${p.slug}]] — ${p.title || ''} (weight: ${p.emotional_weight?.toFixed(2) ?? 'n/a'})`);
|
|
const footer = stripped > 0
|
|
? `\n\n_${stripped} private entries stripped by allowlist gate._`
|
|
: '';
|
|
return `# Recent salience (last 14d)\n\n${lines.join('\n')}${footer}\n`;
|
|
}
|
|
|
|
/**
|
|
* Compress a brain page body into a digest. The compressor keeps frontmatter
|
|
* out, trims body to the first H2/H3 sections, and prepends a slug header.
|
|
* Per-entity budget enforcement happens at the caller (refreshEntity).
|
|
*/
|
|
function compressPage(slug: string, title: string, body: string): string {
|
|
const trimmed = body
|
|
.replace(/^---[\s\S]*?---\s*\n/m, '') // strip frontmatter
|
|
.trim();
|
|
return `# ${title}\nslug: ${slug}\n\n${trimmed}\n`;
|
|
}
|
|
|
|
/**
|
|
* Truncate a digest to a byte budget. Tries to cut at the last newline before
|
|
* the budget so the digest stays readable.
|
|
*/
|
|
function truncateToBudget(content: string, budgetBytes: number): string {
|
|
const buf = Buffer.from(content, 'utf-8');
|
|
if (buf.byteLength <= budgetBytes) return content;
|
|
const truncated = buf.slice(0, budgetBytes).toString('utf-8');
|
|
const lastNewline = truncated.lastIndexOf('\n');
|
|
const cleanCut = lastNewline > budgetBytes * 0.8 ? truncated.slice(0, lastNewline) : truncated;
|
|
return `${cleanCut}\n\n_(digest truncated to ${budgetBytes}-byte budget)_\n`;
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Subcommand: digest
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Public: compress a brain page slug to digest format. Used by callers that
|
|
* want to know what the digest WOULD look like without writing to cache.
|
|
*/
|
|
export function cmdDigest(slug: string): string | null {
|
|
return fetchSimplePage(slug);
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Subcommand: meta
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
export function cmdMeta(projectSlug: string | null): CacheMeta {
|
|
if (projectSlug) return loadMeta('per-project', projectSlug);
|
|
return loadMeta('cross-project', null);
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Subcommand: bootstrap (T2b)
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Bootstrap synthesizes draft entity content from CLAUDE.md + README +
|
|
* recent commits + learnings.jsonl for a fresh project. Emits as JSON for
|
|
* the caller (skill template) to AUQ-confirm before any write to the brain.
|
|
*
|
|
* This keeps the CLI pure (no AUQ logic) while preventing silent
|
|
* auto-extraction garbage (D10 T4 fix). The agent is responsible for the
|
|
* "Synthesized X — looks right?" prompt per entity.
|
|
*/
|
|
export interface BootstrapDraft {
|
|
product?: { slug: string; title: string; body: string };
|
|
goals?: Array<{ slug: string; title: string; body: string }>;
|
|
developer_persona?: { slug: string; title: string; body: string };
|
|
brand?: { slug: string; title: string; body: string };
|
|
competitive_intel?: { slug: string; title: string; body: string };
|
|
}
|
|
|
|
export function cmdBootstrap(projectSlug: string): BootstrapDraft {
|
|
const draft: BootstrapDraft = {};
|
|
const repoRoot = process.env.GSTACK_REPO_ROOT || process.cwd();
|
|
|
|
// Product synthesis: CLAUDE.md headline + README first paragraph
|
|
let claudeMd = '';
|
|
try { claudeMd = readFileSync(join(repoRoot, 'CLAUDE.md'), 'utf-8'); } catch { /* missing is fine */ }
|
|
let readmeMd = '';
|
|
try { readmeMd = readFileSync(join(repoRoot, 'README.md'), 'utf-8'); } catch { /* missing is fine */ }
|
|
|
|
const productLead = synthesizeProductLead(claudeMd, readmeMd, projectSlug);
|
|
if (productLead) {
|
|
draft.product = {
|
|
slug: `gstack/product/${projectSlug}`,
|
|
title: projectSlug,
|
|
body: productLead,
|
|
};
|
|
}
|
|
|
|
// Goals: try learnings.jsonl + recent commit messages mentioning "goal" or "ship"
|
|
const learningsPath = join(GSTACK_HOME, 'projects', projectSlug, 'learnings.jsonl');
|
|
const goalsHints = synthesizeGoalsHints(learningsPath, repoRoot);
|
|
if (goalsHints.length > 0) {
|
|
draft.goals = goalsHints.slice(0, 3).map((hint, idx) => ({
|
|
slug: `gstack/goal/${projectSlug}/bootstrap-${idx + 1}`,
|
|
title: hint.title,
|
|
body: hint.body,
|
|
}));
|
|
}
|
|
|
|
return draft;
|
|
}
|
|
|
|
function synthesizeProductLead(claudeMd: string, readmeMd: string, slug: string): string | null {
|
|
// First H1 in CLAUDE.md or README, plus first paragraph after it.
|
|
const source = claudeMd || readmeMd;
|
|
if (!source) return null;
|
|
const h1Match = source.match(/^#\s+(.+)$/m);
|
|
const heading = h1Match?.[1]?.trim() || slug;
|
|
// First non-heading paragraph
|
|
const paraMatch = source.match(/(?:^|\n)([^#\n][^\n]+(?:\n[^#\n][^\n]+)*)/);
|
|
const lead = paraMatch?.[1]?.trim() || '(no description found in CLAUDE.md or README)';
|
|
return [
|
|
`# ${heading}`,
|
|
'',
|
|
'## What',
|
|
lead.slice(0, 500),
|
|
'',
|
|
'## Stage',
|
|
'(fill in current stage, e.g., v1.x shipped, in development, paused)',
|
|
'',
|
|
'## Team',
|
|
'(fill in team composition + size)',
|
|
'',
|
|
'## Active goals',
|
|
'(populated by /office-hours over time)',
|
|
'',
|
|
'## Recent decisions',
|
|
'(populated by /plan-ceo-review over time)',
|
|
'',
|
|
].join('\n');
|
|
}
|
|
|
|
function synthesizeGoalsHints(learningsPath: string, repoRoot: string): Array<{ title: string; body: string }> {
|
|
const hints: Array<{ title: string; body: string }> = [];
|
|
if (existsSync(learningsPath)) {
|
|
try {
|
|
const lines = readFileSync(learningsPath, 'utf-8').split('\n').filter(Boolean);
|
|
for (const line of lines.slice(-10)) {
|
|
try {
|
|
const entry = JSON.parse(line);
|
|
if (entry?.insight && (entry?.type === 'pattern' || entry?.type === 'architecture')) {
|
|
hints.push({
|
|
title: entry.insight.slice(0, 80),
|
|
body: `Source: learnings.jsonl\nType: ${entry.type}\n\n${entry.insight}\n`,
|
|
});
|
|
}
|
|
} catch { /* skip malformed line */ }
|
|
}
|
|
} catch { /* unreadable file, skip */ }
|
|
}
|
|
return hints;
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Subcommand: list (T18)
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Lists all gstack-owned pages currently in the brain for a project, grouped
|
|
* by type. Powers the user's ability to audit what gstack has written.
|
|
*/
|
|
export function cmdList(projectSlug: string | null): Array<{ type: string; slug: string; title?: string }> {
|
|
// We probe each gstack/<type>/ namespace via list-pages with a type filter.
|
|
const types = ['gstack/user-profile', 'gstack/product', 'gstack/goal', 'gstack/developer-persona', 'gstack/brand', 'gstack/competitive-intel', 'gstack/skill-run', 'gstack/take'];
|
|
const all: Array<{ type: string; slug: string; title?: string }> = [];
|
|
for (const type of types) {
|
|
const result = execGbrainJson<{ pages?: Array<{ slug: string; title?: string }> }>([
|
|
'list-pages',
|
|
'--type', type,
|
|
'--limit', '200',
|
|
'--json',
|
|
]);
|
|
if (!result?.pages) continue;
|
|
for (const page of result.pages) {
|
|
if (projectSlug && !page.slug?.includes(`/${projectSlug}`) && type !== 'gstack/user-profile') {
|
|
continue;
|
|
}
|
|
all.push({ type, slug: page.slug, title: page.title });
|
|
}
|
|
}
|
|
return all;
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// Subcommand: purge (T18)
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Delete one gstack-owned page from the brain. Caller (skill template) is
|
|
* responsible for the confirm prompt; this is the raw operation.
|
|
*/
|
|
export function cmdPurge(slug: string): { deleted: boolean; error?: string } {
|
|
if (!slug.startsWith('gstack/')) {
|
|
return { deleted: false, error: 'refusing to purge non-gstack page' };
|
|
}
|
|
const result = spawnGbrain(['delete-page', slug], { timeout: 10_000 });
|
|
if (result.status !== 0) {
|
|
return { deleted: false, error: result.stderr?.trim() || `exit ${result.status}` };
|
|
}
|
|
// Also invalidate any cached digests that referenced this page.
|
|
// Best-effort — derived digests may need explicit invalidate.
|
|
return { deleted: true };
|
|
}
|
|
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
// CLI dispatch
|
|
// ──────────────────────────────────────────────────────────────────────────
|
|
|
|
function parseArgs(argv: string[]): { cmd: string; positional: string[]; flags: Record<string, string | boolean> } {
|
|
const cmd = argv[2] || '';
|
|
const rest = argv.slice(3);
|
|
const positional: string[] = [];
|
|
const flags: Record<string, string | boolean> = {};
|
|
for (let i = 0; i < rest.length; i++) {
|
|
const arg = rest[i];
|
|
if (arg.startsWith('--')) {
|
|
const key = arg.slice(2);
|
|
const next = rest[i + 1];
|
|
if (next && !next.startsWith('--')) {
|
|
flags[key] = next;
|
|
i++;
|
|
} else {
|
|
flags[key] = true;
|
|
}
|
|
} else {
|
|
positional.push(arg);
|
|
}
|
|
}
|
|
return { cmd, positional, flags };
|
|
}
|
|
|
|
function projectSlugFromFlag(flags: Record<string, string | boolean>): string | null {
|
|
const v = flags.project;
|
|
return typeof v === 'string' ? v : null;
|
|
}
|
|
|
|
function printUsage(): void {
|
|
process.stderr.write(`Usage: gstack-brain-cache <subcommand>
|
|
|
|
Subcommands:
|
|
get <entity-name> [--project <slug>]
|
|
refresh [--full] [--entity X] [--project <slug>]
|
|
invalidate <entity-name> [--project <slug>]
|
|
digest <entity-slug>
|
|
meta [--project <slug>]
|
|
bootstrap --project <slug> — emit synthesized entity drafts (JSON)
|
|
list [--project <slug>] — list gstack-owned pages in brain
|
|
purge <slug> — delete a gstack-owned brain page (refuses non-gstack/ slugs)
|
|
`);
|
|
}
|
|
|
|
async function main(): Promise<number> {
|
|
const { cmd, positional, flags } = parseArgs(process.argv);
|
|
const projectSlug = projectSlugFromFlag(flags);
|
|
|
|
try {
|
|
switch (cmd) {
|
|
case 'get': {
|
|
const entityName = positional[0];
|
|
if (!entityName) { printUsage(); return 1; }
|
|
const result = cmdGet(entityName, projectSlug);
|
|
if (result.state === 'missing') {
|
|
process.stderr.write(`(${result.state}: ${result.message ?? 'no cache'})\n`);
|
|
return 2;
|
|
}
|
|
if (result.state !== 'warm') {
|
|
process.stderr.write(`(${result.state}${result.message ? ': ' + result.message : ''})\n`);
|
|
}
|
|
process.stdout.write(readFileSync(result.path, 'utf-8'));
|
|
return 0;
|
|
}
|
|
case 'refresh': {
|
|
// D3: dedup concurrent refreshes via lockfile. Skipped (dedup) when
|
|
// another process is already mid-refresh on the same project.
|
|
if (flags.entity) {
|
|
const entityName = String(flags.entity);
|
|
const result = withRefreshLock(projectSlug, () => refreshEntity(entityName, projectSlug));
|
|
if (result === 'dedup') {
|
|
process.stderr.write(`(dedup: another refresh in flight)\n`);
|
|
return 3;
|
|
}
|
|
process.stdout.write(result ? `refreshed ${entityName}\n` : `failed to refresh ${entityName}\n`);
|
|
return result ? 0 : 1;
|
|
}
|
|
const allResult = withRefreshLock(projectSlug, () => refreshAll(projectSlug));
|
|
if (allResult === 'dedup') {
|
|
process.stderr.write(`(dedup: another refresh in flight)\n`);
|
|
return 3;
|
|
}
|
|
process.stdout.write(`refreshed=${allResult.success} failed=${allResult.failed}\n`);
|
|
return allResult.failed > 0 ? 1 : 0;
|
|
}
|
|
case 'invalidate': {
|
|
const entityName = positional[0];
|
|
if (!entityName) { printUsage(); return 1; }
|
|
cmdInvalidate(entityName, projectSlug);
|
|
process.stdout.write(`invalidated ${entityName}\n`);
|
|
return 0;
|
|
}
|
|
case 'digest': {
|
|
const slug = positional[0];
|
|
if (!slug) { printUsage(); return 1; }
|
|
const content = cmdDigest(slug);
|
|
if (content === null) {
|
|
process.stderr.write('brain unreachable or page not found\n');
|
|
return 2;
|
|
}
|
|
process.stdout.write(content);
|
|
return 0;
|
|
}
|
|
case 'meta': {
|
|
const meta = cmdMeta(projectSlug);
|
|
process.stdout.write(JSON.stringify(meta, null, 2) + '\n');
|
|
return 0;
|
|
}
|
|
case 'bootstrap': {
|
|
if (!projectSlug) {
|
|
process.stderr.write('bootstrap requires --project <slug>\n');
|
|
return 1;
|
|
}
|
|
const draft = cmdBootstrap(projectSlug);
|
|
process.stdout.write(JSON.stringify(draft, null, 2) + '\n');
|
|
return 0;
|
|
}
|
|
case 'list': {
|
|
const pages = cmdList(projectSlug);
|
|
if (flags.json) {
|
|
process.stdout.write(JSON.stringify(pages, null, 2) + '\n');
|
|
} else {
|
|
for (const p of pages) {
|
|
process.stdout.write(`${p.type}\t${p.slug}\t${p.title ?? ''}\n`);
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
case 'purge': {
|
|
const slug = positional[0];
|
|
if (!slug) { printUsage(); return 1; }
|
|
const result = cmdPurge(slug);
|
|
if (result.deleted) {
|
|
process.stdout.write(`deleted ${slug}\n`);
|
|
return 0;
|
|
}
|
|
process.stderr.write(`failed: ${result.error}\n`);
|
|
return 1;
|
|
}
|
|
case '':
|
|
case 'help':
|
|
case '--help':
|
|
case '-h':
|
|
printUsage();
|
|
return 0;
|
|
default:
|
|
process.stderr.write(`unknown subcommand: ${cmd}\n`);
|
|
printUsage();
|
|
return 1;
|
|
}
|
|
} catch (err) {
|
|
process.stderr.write(`error: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
// Only run main when invoked as a script (not when imported by tests)
|
|
if (import.meta.main) {
|
|
main().then((code) => process.exit(code));
|
|
}
|