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

+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();