Files
gstack/lib/gstack-decision-semantic.ts
T
95cf15b3c9 gbrain memory lookups find the artifacts source, product pages and newest timeline rows (#4685)
`/sync-gbrain` and `gstack-decision-search --semantic` now find a brain
host's artifacts source through `GSTACK_BRAIN_SOURCE_ID`, planning
skills read their product and brand digests from current gbrain, and the
brain gets each sync's newest artifacts and timeline rows.

Why: five outside reports (#4443, #4327, #4265, #4179, #4362), each
reproduced on main by a test that fails before this change and passes
after it.

Nothing to do unless your artifacts source lives outside
`~/.gstack-brain-worktree`; then set `GSTACK_BRAIN_SOURCE_ID` to its id.

Co-authored-by: Barack-zero-to-one <121355791+Barack-zero-to-one@users.noreply.github.com>
Co-authored-by: exGeni <135786749+exGeni@users.noreply.github.com>
Co-authored-by: atharva081106 <176514655+atharva081106@users.noreply.github.com>
Co-authored-by: extremenelson <2460114+extremenelson@users.noreply.github.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/specialist-batched#1 reader=testing
Review-Finding: p1v/outside-voice#2 reader=outside-voice
2026-11-22 11:00:45 +00:00

98 lines
4.2 KiB
TypeScript

/**
* gstack-decision-semantic — OPTIONAL gbrain enhancement for decision resurfacing.
*
* This is the ONLY decision module that touches gbrain. The reliable core
* (lib/gstack-decision.ts) has zero gbrain imports and works with gbrain OFF; this
* module is loaded lazily by `gstack-decision-search` only on `--semantic`, and every
* path degrades to `null` (caller shows the reliable file results) when gbrain is
* absent, unconfigured, times out, or returns nothing. It NEVER throws and NEVER
* hangs (10s spawn timeout). We do not wire core function to this — gbrain is an
* enhancement, never a dependency (the code-search lesson).
*
* Surface reality (verified against gbrain 0.42.x, not guessed):
* - `gbrain search "<q>"` prints TEXT lines `[score] slug -- snippet`, NOT JSON
* (so we parse the text surface; execGbrainJson would always null here).
* - The curated-memory source is the one GSTACK_BRAIN_SOURCE_ID names, else the
* one whose local_path is the gstack brain worktree (`~/.gstack-brain-worktree`),
* id `default` by convention. Scoping search to it keeps code/doc corpora out.
*/
import { spawnGbrain } from "./gbrain-exec";
import { parseSourcesList } from "./gbrain-sources";
const TIMEOUT_MS = 10_000;
const BRAIN_WORKTREE_SUFFIX = ".gstack-brain-worktree";
export interface SemanticHit {
score: number;
slug: string;
snippet: string;
}
/**
* Resolve the curated-memory source id: the registered source GSTACK_BRAIN_SOURCE_ID
* names (as gstack-gbrain-sync and the source wireup read it), else the gstack brain
* worktree's source. Returns null when gbrain is down/unparseable, the named source is
* not registered, or no worktree-backed source is registered; the caller then shows
* the file results only, never an unscoped search.
*/
export function resolveMemorySourceId(env?: NodeJS.ProcessEnv): string | null {
const r = spawnGbrain(["sources", "list", "--json"], { baseEnv: env, timeout: TIMEOUT_MS });
if (r.status !== 0) return null;
let rows;
try {
rows = parseSourcesList(JSON.parse(r.stdout || "null"));
} catch {
return null;
}
const explicit = (env ?? process.env).GSTACK_BRAIN_SOURCE_ID;
if (explicit) return rows.some((s) => s.id === explicit) ? explicit : null;
const atWorktree = rows.filter(
(s) => typeof s.local_path === "string" && s.local_path.endsWith(BRAIN_WORKTREE_SUFFIX),
);
const pick = atWorktree.find((s) => s.id === "default") ?? atWorktree[0];
return pick?.id ?? null;
}
/**
* Parse gbrain search's text output into scored hits. Lines look like:
* `[0.4361] slug -- snippet text...`
* Non-matching lines (banners, blanks) are skipped. Exported for deterministic
* unit testing of the parser without a live gbrain.
*/
export function parseSearchHits(stdout: string, minScore: number, limit: number): SemanticHit[] {
const hits: SemanticHit[] = [];
for (const line of stdout.split("\n")) {
const m = line.match(/^\[([\d.]+)\]\s+(\S+)\s+--\s+(.*)$/);
if (!m) continue;
const score = parseFloat(m[1]);
if (!Number.isFinite(score) || score < minScore) continue;
hits.push({ score, slug: m[2], snippet: m[3].trim() });
}
return hits.slice(0, limit);
}
/**
* Semantic recall over the curated-memory source. Returns parsed hits, or `null`
* when gbrain is unavailable / errors (caller MUST degrade to the reliable file
* results on null). An empty array means gbrain ran but found nothing relevant
* (e.g. memory not synced yet) — also honest, distinct from null. Never throws,
* never hangs.
*/
export function semanticRecall(
query: string,
env?: NodeJS.ProcessEnv,
minScore = 0.1,
limit = 3,
): SemanticHit[] | null {
if (!query.trim()) return null;
// Require the curated-memory source. If it's absent (gbrain down OR no worktree-backed
// source), degrade to null rather than searching UNSCOPED — an unscoped search pulls
// code/doc corpora that would be mislabeled as "related decisions" (Codex finding).
const sourceId = resolveMemorySourceId(env);
if (!sourceId) return null;
const r = spawnGbrain(["search", query, "--source", sourceId], { baseEnv: env, timeout: TIMEOUT_MS });
if (r.status !== 0) return null; // gbrain down / not on PATH / errored → degrade
return parseSearchHits(r.stdout || "", minScore, limit);
}