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
This commit is contained in:
authored and GitHub committed 2026-11-22 11:00:45 +00:00
1 parent 094263d71b
commit 95cf15b3c9
13 files changed
+340 -62

No files matched your search

+11 -5
View File
@@ -516,14 +516,20 @@ function fetchAndCompressEntity(entityName: string, projectSlug: string | null):
}
}
/** Generic single-page fetch via `gbrain get`. Returns null on miss/unreachable. */
function fetchSimplePage(slug: string): string | null {
/**
* Generic single-page fetch via `gbrain get`. Returns null on miss/unreachable.
* gbrain stores slugs lowercased, and `get --json` carries the page text in
* `compiled_truth` (`content` for a streamed page); its `body` is a read-mode name.
*/
function fetchSimplePage(requested: string): string | null {
const slug = requested.toLowerCase();
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);
const page = JSON.parse(result.stdout) as { compiled_truth?: string; content?: string; title?: string };
const text = page?.compiled_truth || page?.content;
if (!text) return null;
return compressPage(slug, page.title || slug, text);
} catch {
return null;
}
+44 -26
View File
@@ -668,7 +668,9 @@ guard_unpublished_range() {
if [ "$rc" -eq 2 ]; then
echo "BRAIN_SYNC: push blocked: unpushed commits hold transcript pages and bun is not on PATH to check them against your transcript consent" >&2
fi
[ "$rc" -eq 0 ]
[ "$rc" -eq 0 ] && return 0
BRAIN_ADVANCE_ARMED=0
return 1
}
# Finalize the drain: delete exactly the spool record files this drain
@@ -877,6 +879,7 @@ validate_outgoing_paths() {
if ! out=$(python3 "$SCRIPT_DIR/gstack-brain-sync-index.py" --outgoing "$GSTACK_HOME"); then
ST_CASE_NAMES=${out%$'\r'}
write_status "error" "outgoing artifact path validation refused: a local commit adds a path that differs only by letter case from a path on the remote; local commits and queue preserved. Repair: https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#artifact-case-collision"
BRAIN_ADVANCE_ARMED=0
return 1
fi
out=${out%$'\r'}
@@ -1228,6 +1231,40 @@ subcmd_publish_removals() {
esac
}
# #2516: advance the brain worktree gbrain indexes to the artifacts repo's
# HEAD. It runs from the drain's EXIT trap, after this drain's own commit and
# any merge from origin, while the drain lock is still held, so gbrain sees
# what the drain just published instead of the HEAD from before it. An
# up-to-date worktree costs two rev-parses. An advance that leaves the worktree
# behind (a failure, or a refused dirty or unmanaged worktree) stamps the time,
# which holds the next attempt and its warning for 24h; a later success clears
# the stamp. INT/TERM disarm it, so a cancelled drain never checks anything out,
# and so does a transcript-consent or letter-case refusal (guard_unpublished_range,
# validate_outgoing_paths), so a commit kept local by one never reaches gbrain.
# The advance itself never force-removes (see gstack-gbrain-source-wireup).
BRAIN_ADVANCE_ARMED=0
advance_brain_worktree() {
[ "$BRAIN_ADVANCE_ARMED" = 1 ] || return 0
BRAIN_ADVANCE_ARMED=0
local wt="${GSTACK_BRAIN_WORKTREE:-$HOME/.gstack-brain-worktree}" stamp="$GSTACK_HOME/.brain-worktree-last-advance"
[ -e "$wt" ] || return 0
local head now last rc=0
head=$(git -C "$GSTACK_HOME" rev-parse HEAD 2>/dev/null) || return 0
[ "$(git -C "$wt" rev-parse HEAD 2>/dev/null)" != "$head" ] || return 0
now=$(date +%s)
last=$(cat "$stamp" 2>/dev/null || echo 0)
case "$last" in ''|*[!0-9]*) last=0 ;; esac
[ $(( now - last )) -ge 86400 ] || return 0
"$SCRIPT_DIR/gstack-gbrain-source-wireup" --advance-only 1>&2 || rc=$?
if [ "$(git -C "$wt" rev-parse HEAD 2>/dev/null)" = "$head" ]; then
rm -f "$stamp" 2>/dev/null || true
return 0
fi
echo "$now" > "$stamp" 2>/dev/null || true
[ "$rc" -eq 0 ] || echo "BRAIN_SYNC: warning: brain worktree advance failed — gbrain may be indexing stale code (run gstack-gbrain-source-wireup to repair)" >&2
return 0
}
subcmd_once() {
if ! sync_active; then
# Silent no-op when feature not initialized / disabled.
@@ -1239,8 +1276,11 @@ subcmd_once() {
# the next skill boundary catches up. Released on EVERY exit from here on,
# including the empty-queue fast path and an INT during the detector's
# network push; the mktemp block below re-traps with tempfile cleanup added.
# The EXIT trap also advances the brain worktree (advance_brain_worktree).
gstack_brain_lock_acquire "$GSTACK_HOME" try || exit 0
trap 'gstack_brain_lock_release' EXIT INT TERM
BRAIN_ADVANCE_ARMED=1
trap 'advance_brain_worktree; gstack_brain_lock_release' EXIT
trap 'BRAIN_ADVANCE_ARMED=0; gstack_brain_lock_release' INT TERM
validate_outgoing_paths || exit 0
@@ -1258,29 +1298,6 @@ subcmd_once() {
local mode
mode=$("$CONFIG_BIN" get artifacts_sync_mode 2>/dev/null || echo off)
# #2516: advance the brain worktree gbrain indexes to the artifacts repo's
# HEAD once a day — previously it only moved when setup-gbrain / sync-gbrain
# / brain-restore ran, so brains silently served stale code forever. Runs
# inside THIS run lock (never concurrent with the ingest steps below) and
# before they touch the worktree. Attempt-throttled: the stamp is written on
# ATTEMPT, so a persistently-failing advance warns once per 24h, not at
# every skill boundary. The advance itself refuses dirty or unmanaged
# worktrees and never force-removes (see gstack-gbrain-source-wireup).
if [ -e "${GSTACK_BRAIN_WORKTREE:-$HOME/.gstack-brain-worktree}" ]; then
local adv_stamp adv_now adv_last adv_age
adv_stamp="$GSTACK_HOME/.brain-worktree-last-advance"
adv_now=$(date +%s)
adv_last=$(cat "$adv_stamp" 2>/dev/null || echo 0)
case "$adv_last" in ''|*[!0-9]*) adv_last=0 ;; esac
adv_age=$(( adv_now - adv_last ))
if [ "$adv_age" -ge 86400 ]; then
echo "$adv_now" > "$adv_stamp" 2>/dev/null || true
if ! "$SCRIPT_DIR/gstack-gbrain-source-wireup" --advance-only 1>&2; then
echo "BRAIN_SYNC: warning: brain worktree advance failed — gbrain may be indexing stale code (run gstack-gbrain-source-wireup to repair)" >&2
fi
fi
fi
# Removals go first, so a removal commit whose push fails is one more
# unpushed commit for the detector below.
REMOVALS_PUSHED=0
@@ -1360,7 +1377,8 @@ subcmd_once() {
groups_file=$(mktemp "${TMPDIR:-/tmp}/brain-sync-groups.XXXXXX") || { rm -f "$paths_file" "$class_file" "$snapshot_file"; write_status "error" "mktemp failed"; exit 1; }
# Single trap covers all: lock release AND tempfile cleanup (the siblings
# are the staging and hold steps' scratch files).
trap 'rm -f "$paths_file" "$paths_file".* "$class_file" "$snapshot_file" "$groups_file" "$groups_file".* 2>/dev/null; gstack_brain_lock_release' EXIT INT TERM
trap 'rm -f "$paths_file" "$paths_file".* "$class_file" "$snapshot_file" "$groups_file" "$groups_file".* 2>/dev/null; advance_brain_worktree; gstack_brain_lock_release' EXIT
trap 'BRAIN_ADVANCE_ARMED=0; rm -f "$paths_file" "$paths_file".* "$class_file" "$snapshot_file" "$groups_file" "$groups_file".* 2>/dev/null; gstack_brain_lock_release' INT TERM
# Fail-safe (G1): a classifier that dies mid-run (ENOSPC/OOM/SIGKILL, or a
# shape the defensive filters don't cover) may have already written the
+4 -1
View File
@@ -240,7 +240,10 @@ export function resolveMemoryIngestSources(
*/
export function federatedCuratedSourceId(env?: NodeJS.ProcessEnv): string | null {
const rows = parseSourcesList(execGbrainJson(["sources", "list", "--json"], { baseEnv: env, timeout: 10_000 }));
const row = rows.find((r) => (r as { federated?: boolean }).federated === true && isArtifactsSourceRow(r, env));
const explicit = (env ?? process.env).GSTACK_BRAIN_SOURCE_ID;
const row = rows.find(
(r) => (r as { federated?: boolean }).federated === true && (explicit ? r.id === explicit : isArtifactsSourceRow(r, env)),
);
return row?.id ?? null;
}
+2 -2
View File
@@ -96,6 +96,7 @@ import {
type StateEntry,
} from "../lib/memory-ingest-landing";
import { writeReceipt } from "../lib/egress-receipt";
import { artifactBody } from "../lib/memory-artifact-body";
import { checkOwnedStagingDir, STAGING_MARKER } from "../lib/staging-guard";
import { hasRepoPolicyStore, repoPolicyTierBatch } from "../lib/gbrain-repo-policy-client";
import { resolveStateRoot, mergedStateRoots, type StateRootEnv } from "../lib/state-root";
@@ -978,8 +979,7 @@ function buildArtifactPage(path: string, type: MemoryType, raw?: string): PageRe
const tags = [type, `repo:${slug_repo}`, `date:${date}`];
// Truncate body to 200KB
const body = raw.slice(0, 200000);
const body = artifactBody(path, raw);
return {
slug,
@@ -0,0 +1 @@
**gbrain memory lookups find the pages they were looking for.** `GSTACK_BRAIN_SOURCE_ID` now names the artifacts source for `/sync-gbrain`'s duplicate-import guard and for `gstack-decision-search --semantic`, so a brain host whose source is a clone elsewhere stops importing plans and design docs twice (#4443) and gets its "Related from memory" hits (#4327). Planning skills' product, brand and persona digests read the page text current gbrain returns, under the lowercase slug it stores (#4265). Every artifacts sync now advances the brain worktree after its own commit, so gbrain indexes what was just published instead of waiting up to a day (#4179). An oversized timeline, learnings or eureka log keeps its newest complete rows in the brain instead of its oldest, cut mid-row (#4362).
+12 -4
View File
@@ -47,6 +47,11 @@ The command:
(never auto-executed — run it yourself, or on your own machine
`bin/gstack-gbrain-source-wireup` does the same wiring) so
`gbrain search` can index your synced learnings, plans, and designs.
When the brain host is this same machine and the source sits somewhere
other than `~/.gstack-brain-worktree` (a `--url` or `--path ~/<id>`
clone), set `GSTACK_BRAIN_SOURCE_ID` to the source's id so `/sync-gbrain`
doesn't import your plans and designs a second time and
`gstack-decision-search --semantic` searches that source.
The old `gstack-brain-reader add --ingest-url ...` HTTP path was
removed in v1.15.1.0 — it depended on a `/ingest-repo` endpoint gbrain
never shipped.
@@ -268,10 +273,13 @@ this — it happens automatically at the first skill invocation each day.
Historical note (#2516): that daily pull refreshed only `~/.gstack` itself —
NOT the detached worktree at `~/.gstack-brain-worktree` that gbrain actually
indexes, so the brain silently served stale pages until the next
setup-gbrain/sync-gbrain run. Since this fix, the daily sync also advances
the brain worktree (`gstack-gbrain-source-wireup --advance-only`, throttled
via `~/.gstack/.brain-worktree-last-advance`); a failed advance warns instead
of failing silently, and never force-resets a dirty worktree.
setup-gbrain/sync-gbrain run. Since this fix, every sync ends by advancing
the brain worktree to the commit it just made
(`gstack-gbrain-source-wireup --advance-only`), so gbrain indexes what the
sync published. An advance that fails, or that refuses a dirty worktree,
warns once and waits 24 hours before trying again
(`~/.gstack/.brain-worktree-last-advance`); it never force-resets a dirty
worktree.
## Uninstall
+10 -6
View File
@@ -12,9 +12,9 @@
* 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 whose local_path is the gstack brain
* worktree (`~/.gstack-brain-worktree`), id `default` by convention — NOT a
* `gstack-brain-<user>` id. Scoping search to it keeps code/doc corpora out.
* - 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";
@@ -30,9 +30,11 @@ export interface SemanticHit {
}
/**
* Resolve the curated-memory source id (the gstack brain worktree). Returns null
* when gbrain is down/unparseable OR no worktree-backed source is registered — the
* caller then searches unscoped (best-effort) rather than failing.
* 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 });
@@ -43,6 +45,8 @@ export function resolveMemorySourceId(env?: NodeJS.ProcessEnv): string | 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),
);
+16
View File
@@ -0,0 +1,16 @@
/** Longest artifact page body gstack-memory-ingest writes, in JS characters. */
export const ARTIFACT_BODY_MAX_CHARS = 200_000;
/**
* An artifact page's body. A file within the cap is kept whole. Past it, a
* markdown file keeps its start, and an append-only .jsonl log (timeline,
* learnings, eureka) keeps its newest complete rows, so the page holds the
* latest events and never ends in a cut row (#4362).
*/
export function artifactBody(path: string, raw: string, max = ARTIFACT_BODY_MAX_CHARS): string {
if (raw.length <= max || !path.endsWith(".jsonl")) return raw.slice(0, max);
const start = raw.length - max;
if (raw[start - 1] === "\n") return raw.slice(start);
const nextRow = raw.indexOf("\n", start);
return nextRow === -1 || nextRow === raw.length - 1 ? raw.slice(0, max) : raw.slice(nextRow + 1);
}
+59
View File
@@ -0,0 +1,59 @@
/**
* #4265: single-page brain-cache entities read the page text gbrain's
* `get --json` actually returns (compiled_truth; body is a read-mode name),
* under the lowercased slug gbrain stores.
*/
import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
import { delimiter, join } from 'path';
import { tmpdir } from 'os';
const CACHE = '../bin/gstack-brain-cache';
let TMP_HOME: string;
let STUB: string;
const saved = { home: process.env.GSTACK_HOME, path: process.env.PATH };
beforeEach(() => {
TMP_HOME = mkdtempSync(join(tmpdir(), 'gstack-cache-page-'));
STUB = mkdtempSync(join(tmpdir(), 'gstack-cache-page-gbrain-'));
writeFileSync(join(STUB, 'page.json'), JSON.stringify({
slug: 'gstack/product/some-org-some-repo',
title: 'Some product',
body: 'auto',
compiled_truth: '## What it is\nA tool that ships code.',
timeline: '',
}) + '\n');
writeFileSync(join(STUB, 'gbrain'), [
'#!/bin/sh',
'here=$(dirname "$0")',
'echo "$@" >> "$here/calls"',
'[ "$1" = get ] && [ "$2" = gstack/product/some-org-some-repo ] && cat "$here/page.json" && exit 0',
'echo "page_not_found" >&2',
'exit 1',
'',
].join('\n'));
chmodSync(join(STUB, 'gbrain'), 0o755);
process.env.PATH = `${STUB}${delimiter}${saved.path ?? ''}`;
process.env.GSTACK_HOME = TMP_HOME;
delete require.cache[require.resolve(CACHE)];
});
afterEach(() => {
if (saved.home) process.env.GSTACK_HOME = saved.home; else delete process.env.GSTACK_HOME;
process.env.PATH = saved.path;
rmSync(TMP_HOME, { recursive: true, force: true });
rmSync(STUB, { recursive: true, force: true });
});
describe.skipIf(process.platform === 'win32')('brain-cache single-page read (#4265)', () => {
test('a product page under a mixed-case project slug comes back as a digest', async () => {
const mod = await import(CACHE);
const result = mod.cmdGet('product', 'Some-Org-some-repo');
expect(result.state).toBe('cold-refreshed');
const digest = readFileSync(result.path, 'utf-8');
expect(digest).toContain('# Some product');
expect(digest).toContain('A tool that ships code.');
expect(digest).not.toContain('auto');
expect(readFileSync(join(STUB, 'calls'), 'utf-8')).toContain('get gstack/product/some-org-some-repo --json');
});
});
+70 -18
View File
@@ -130,29 +130,81 @@ describe('gstack-gbrain-source-wireup --advance-only (#2516)', () => {
});
});
describe('brain-sync --once daily advance wiring (#2516)', () => {
test('once advances the worktree behind a 24h attempt stamp', () => {
describe('brain-sync --once advance wiring (#2516, #4179)', () => {
const stamp = () => path.join(tmpHome, '.brain-worktree-last-advance');
test('every drain advances a behind worktree, with no daily window', () => {
makeArtifactsRepoWithWorktree();
run(['gstack-config', 'set', 'artifacts_sync_mode', 'artifacts-only']);
const second = commit(tmpHome, 'second');
const r1 = run(['gstack-brain-sync', '--once']);
expect(r1.status).toBe(0);
const stamp = path.join(tmpHome, '.brain-worktree-last-advance');
expect(fs.existsSync(stamp)).toBe(true);
expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
expect(git(['rev-parse', 'HEAD'], worktreePath()).stdout).toBe(second);
// Within the 24h window: parent advances again, --once does NOT re-advance.
const third = commit(tmpHome, 'third');
const r2 = run(['gstack-brain-sync', '--once']);
expect(r2.status).toBe(0);
expect(git(['rev-parse', 'HEAD'], worktreePath()).stdout).toBe(second);
expect(git(['rev-parse', 'HEAD'], worktreePath()).stdout).not.toBe(third);
// Expire the stamp → the next --once advances again.
fs.writeFileSync(stamp, String(Math.floor(Date.now() / 1000) - 90000));
const r3 = run(['gstack-brain-sync', '--once']);
expect(r3.status).toBe(0);
expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
expect(git(['rev-parse', 'HEAD'], worktreePath()).stdout).toBe(third);
expect(fs.existsSync(stamp())).toBe(false);
});
test("the advance runs after the drain's own commit, so the worktree holds what it just published", () => {
const bare = fs.mkdtempSync(path.join(os.tmpdir(), 'wtree-adv-remote-'));
try {
spawnSync('git', ['init', '--bare', '-q', '-b', 'main', bare], { timeout: 30_000 });
expect(run(['gstack-artifacts-init', '--remote', bare]).status).toBe(0);
run(['gstack-config', 'set', 'artifacts_sync_mode', 'full']);
git(['worktree', 'add', '--detach', worktreePath(), 'HEAD'], tmpHome);
fs.mkdirSync(path.join(tmpHome, 'projects', 'p'), { recursive: true });
fs.writeFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"x","insight":"y","ts":"2026-11-22T10:00:00Z"}\n');
run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
expect(git(['log', '-1', '--format=%s'], tmpHome).stdout).toMatch(/^sync: 1 file/);
expect(git(['rev-parse', 'HEAD'], worktreePath()).stdout).toBe(git(['rev-parse', 'HEAD'], tmpHome).stdout);
expect(fs.existsSync(path.join(worktreePath(), 'projects/p/learnings.jsonl'))).toBe(true);
} finally {
fs.rmSync(bare, { recursive: true, force: true });
}
});
test('a drain whose push the transcript consent refuses leaves the worktree where it was', () => {
const bare = fs.mkdtempSync(path.join(os.tmpdir(), 'wtree-adv-remote-'));
try {
spawnSync('git', ['init', '--bare', '-q', '-b', 'main', bare], { timeout: 30_000 });
expect(run(['gstack-artifacts-init', '--remote', bare]).status).toBe(0);
run(['gstack-config', 'set', 'artifacts_sync_mode', 'full']);
const head = git(['rev-parse', 'HEAD'], tmpHome).stdout;
git(['worktree', 'add', '--detach', worktreePath(), head], tmpHome);
fs.mkdirSync(path.join(tmpHome, 'transcripts'), { recursive: true });
fs.writeFileSync(path.join(tmpHome, 'transcripts/session.md'), 'a transcript page\n');
git(['add', '-f', 'transcripts/session.md'], tmpHome);
git(['-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '-m', 'transcript'], tmpHome);
fs.mkdirSync(path.join(tmpHome, 'projects', 'p'), { recursive: true });
fs.writeFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"x","insight":"y","ts":"2026-11-22T10:00:00Z"}\n');
run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
const status = JSON.parse(fs.readFileSync(path.join(tmpHome, '.brain-sync-status.json'), 'utf-8'));
expect(status.message).toContain('outside your transcript consent');
expect(git(['log', '-1', '--format=%s'], tmpHome).stdout).toMatch(/^sync: 1 file/);
expect(git(['rev-parse', 'HEAD'], worktreePath()).stdout).toBe(head);
} finally {
fs.rmSync(bare, { recursive: true, force: true });
}
});
test('a refused advance holds retries for 24h; a later success clears the hold', () => {
const { head } = makeArtifactsRepoWithWorktree();
run(['gstack-config', 'set', 'artifacts_sync_mode', 'artifacts-only']);
const second = commit(tmpHome, 'second');
fs.writeFileSync(path.join(worktreePath(), 'artifact.md'), 'local edit\n');
expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
expect(git(['rev-parse', 'HEAD'], worktreePath()).stdout).toBe(head);
expect(fs.existsSync(stamp())).toBe(true);
git(['checkout', '--', 'artifact.md'], worktreePath());
expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
expect(git(['rev-parse', 'HEAD'], worktreePath()).stdout).toBe(head);
fs.writeFileSync(stamp(), String(Math.floor(Date.now() / 1000) - 90000));
expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
expect(git(['rev-parse', 'HEAD'], worktreePath()).stdout).toBe(second);
expect(fs.existsSync(stamp())).toBe(false);
});
});
+29
View File
@@ -126,6 +126,35 @@ exit 1
expect(semanticRecall("anything", env())).toBeNull();
});
test("GSTACK_BRAIN_SOURCE_ID names a source outside the worktree and scopes search to it (#4327)", () => {
writeShim(
`#!/usr/bin/env bash
if [ "$1" = "sources" ]; then echo '{"sources":[{"id":"default","local_path":"/u/.gstack-brain-worktree"},{"id":"acme-gstack-artifacts","local_path":"/srv/brain/acme-gstack-artifacts","federated":true}]}'; exit 0; fi
if [ "$1" = "search" ] && [ "$4" = "acme-gstack-artifacts" ]; then echo "[0.52] projects/acme/checkpoints/x -- Working on: example"; exit 0; fi
if [ "$1" = "search" ]; then echo "[0.91] WRONG-SOURCE -- not the named source"; exit 0; fi
exit 1
`,
);
const named = { ...env(), GSTACK_BRAIN_SOURCE_ID: "acme-gstack-artifacts" };
expect(resolveMemorySourceId(named)).toBe("acme-gstack-artifacts");
expect(semanticRecall("example", named)).toEqual([
{ score: 0.52, slug: "projects/acme/checkpoints/x", snippet: "Working on: example" },
]);
});
test("an unregistered GSTACK_BRAIN_SOURCE_ID degrades to null, never the worktree or an unscoped search (#4327)", () => {
writeShim(
`#!/usr/bin/env bash
if [ "$1" = "sources" ]; then echo '{"sources":[{"id":"default","local_path":"/u/.gstack-brain-worktree"}]}'; exit 0; fi
if [ "$1" = "search" ]; then echo "[0.91] WRONG-SOURCE -- should not search"; exit 0; fi
exit 1
`,
);
const named = { ...env(), GSTACK_BRAIN_SOURCE_ID: "missing-source" };
expect(resolveMemorySourceId(named)).toBeNull();
expect(semanticRecall("example", named)).toBeNull();
});
test("degrades to null when gbrain search exits non-zero", () => {
writeShim(
`#!/usr/bin/env bash
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "fs";
import { join } from "path";
import { ARTIFACT_BODY_MAX_CHARS, artifactBody } from "../lib/memory-artifact-body";
const rows = (n: number) => Array.from({ length: n }, (_, i) => JSON.stringify({ ts: `2026-11-${String(i).padStart(5, "0")}`, skill: "ship", event: "completed" })).join("\n") + "\n";
describe("artifactBody (#4362)", () => {
test("a file within the cap is kept whole", () => {
const raw = rows(10);
expect(artifactBody("/h/.gstack/projects/p/timeline.jsonl", raw)).toBe(raw);
});
test("an oversized .jsonl log keeps its newest complete rows", () => {
const raw = rows(5000);
expect(raw.length).toBeGreaterThan(ARTIFACT_BODY_MAX_CHARS);
const body = artifactBody("/h/.gstack/projects/p/timeline.jsonl", raw);
expect(body.length).toBeLessThanOrEqual(ARTIFACT_BODY_MAX_CHARS);
expect(raw.endsWith(body)).toBe(true);
const kept = body.trimEnd().split("\n");
for (const line of kept) expect(() => JSON.parse(line)).not.toThrow();
expect(kept.at(-1)).toBe(raw.trimEnd().split("\n").at(-1));
});
test("a cut that lands on a row boundary keeps that whole row", () => {
const raw = "a\nbb\ncc\n";
expect(artifactBody("t.jsonl", raw, 6)).toBe("bb\ncc\n");
expect(artifactBody("t.jsonl", raw, 7)).toBe("bb\ncc\n");
});
test("an oversized final .jsonl row never yields an empty body", () => {
const raw = "a\n" + "x".repeat(ARTIFACT_BODY_MAX_CHARS + 10) + "\n";
const body = artifactBody("t.jsonl", raw);
expect(body.length).toBeGreaterThan(0);
expect(body.length).toBeLessThanOrEqual(ARTIFACT_BODY_MAX_CHARS);
});
test("an oversized markdown file keeps its start, as before", () => {
const raw = "# Plan\n" + "x".repeat(ARTIFACT_BODY_MAX_CHARS);
expect(artifactBody("/h/.gstack/projects/p/ceo-plans/plan.md", raw)).toBe(raw.slice(0, ARTIFACT_BODY_MAX_CHARS));
});
test("buildArtifactPage builds its body with artifactBody", () => {
const src = readFileSync(join(import.meta.dir, "..", "bin", "gstack-memory-ingest.ts"), "utf-8");
const fn = src.slice(src.indexOf("function buildArtifactPage("), src.indexOf("// ── Writer"));
expect(fn).toContain("const body = artifactBody(path, raw);");
});
});
@@ -16,6 +16,7 @@ import { join } from "path";
import { spawnSync } from "child_process";
import {
federatedCuratedSourceId,
FEDERATED_CURATED_TYPES,
MEMORY_INGEST_TYPES,
resolveMemoryIngestSources,
@@ -25,6 +26,39 @@ const ROOT = join(import.meta.dir, "..");
const SCRIPT = join(ROOT, "bin", "gstack-gbrain-sync.ts");
const ENV = "GSTACK_MEMORY_INGEST_SOURCES";
describe.skipIf(process.platform === "win32")("federatedCuratedSourceId honors GSTACK_BRAIN_SOURCE_ID (#4443)", () => {
function probe(localPath: string, sourceId?: string, federated = true): string | null {
const home = mkdtempSync(join(tmpdir(), "gstack-4443-"));
try {
const bin = join(home, "bin");
mkdirSync(bin);
writeFileSync(
join(bin, "gbrain"),
`#!/bin/sh\n[ "$1" = sources ] && [ "$2" = list ] && echo '{"sources":[{"id":"acme-gstack-artifacts","local_path":"${localPath}","federated":${federated},"page_count":750}]}' && exit 0\nexit 1\n`,
);
chmodSync(join(bin, "gbrain"), 0o755);
return federatedCuratedSourceId({
HOME: home,
GSTACK_HOME: join(home, ".gstack"),
PATH: `${bin}:${process.env.PATH}`,
...(sourceId === undefined ? {} : { GSTACK_BRAIN_SOURCE_ID: sourceId }),
});
} finally {
rmSync(home, { recursive: true, force: true });
}
}
test("a source at a host-side clone is found by the id the variable names", () => {
expect(probe("/srv/brain/sources/acme-gstack-artifacts")).toBeNull();
expect(probe("/srv/brain/sources/acme-gstack-artifacts", "acme-gstack-artifacts")).toBe("acme-gstack-artifacts");
});
test("a named source must still be federated, and an unknown id never falls back to the path match", () => {
expect(probe("/srv/brain/sources/acme-gstack-artifacts", "acme-gstack-artifacts", false)).toBeNull();
expect(probe("/srv/brain/sources/acme-gstack-artifacts", "other-source")).toBeNull();
});
});
describe("resolveMemoryIngestSources (#2922)", () => {
test("unset, empty, whitespace or `all` → null (full walk)", () => {
expect(resolveMemoryIngestSources(undefined, ENV)).toBeNull();