mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-16 01:42:23 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3fa01a4538 | ||
|
|
ded4aeaeae |
@@ -223,16 +223,14 @@ export GBRAIN_REMOTE_CLIENT_ID=<Alice's client_id>
|
||||
export GBRAIN_REMOTE_CLIENT_SECRET=<Alice's client_secret>
|
||||
export GBRAIN_REMOTE_MCP_URL=https://brain.acme-co.com/mcp
|
||||
|
||||
gbrain search "performance review"
|
||||
gbrain search "performance review" --remote
|
||||
```
|
||||
|
||||
(On a thin-client install every shared op routes through the remote MCP server automatically — no flag needed. The env vars select whose credentials the call uses.)
|
||||
|
||||
Alice should see results only from `customers` and `shared`. The performance-review notes live in `internal`, which she's not scoped to read. She shouldn't see them.
|
||||
|
||||
```bash
|
||||
# Terminal 2, as Bob (export his credentials similarly)
|
||||
gbrain search "performance review"
|
||||
gbrain search "performance review" --remote
|
||||
```
|
||||
|
||||
Bob should see the performance-review notes from `internal`, plus anything related from `shared`. He shouldn't see anything that lives only in `customers`.
|
||||
@@ -516,7 +514,7 @@ The first sync embeds every page, which takes time. Check `gbrain sources status
|
||||
|
||||
### "I see a page I shouldn't see"
|
||||
|
||||
This shouldn't happen, but if you suspect it, run `gbrain search <query> --json` as the constrained client (thin-client install, with the client's `GBRAIN_REMOTE_*` env exported) and inspect the `source_id` field on every returned result. Every row should be in the client's `--federated-read` set. If one isn't, file an issue with the exact slug and source IDs.
|
||||
This shouldn't happen, but if you suspect it, run `gbrain search <query> --remote --json` as the constrained client and inspect the `source_id` field on every returned result. Every row should be in the client's `--federated-read` set. If one isn't, file an issue with the exact slug and source IDs.
|
||||
|
||||
### "The synthesized answer is wrong"
|
||||
|
||||
|
||||
+5
-84
@@ -464,11 +464,7 @@ async function main() {
|
||||
// routed path. Date → ISO string; bigint → string (postgres.js shape);
|
||||
// Buffer → object. Microsecond-cost; eliminates a whole drift bug class.
|
||||
const result = JSON.parse(JSON.stringify(rawResult, bigintToStringReplacer));
|
||||
// #380 pass-through: `--json` (undeclared on most ops, promised by docs)
|
||||
// emits the raw op result instead of the human formatter.
|
||||
const output = params.json === true
|
||||
? JSON.stringify(result, null, 2) + '\n'
|
||||
: formatResult(op.name, result);
|
||||
const output = formatResult(op.name, result);
|
||||
if (output) process.stdout.write(output);
|
||||
} catch (e: unknown) {
|
||||
// v0.42.20.0 (codex D4): on error, set exitCode + return so the `finally`
|
||||
@@ -551,10 +547,7 @@ async function runThinClientRouted(
|
||||
signal: sigintController.signal,
|
||||
});
|
||||
const result = unpackToolResult(raw);
|
||||
// #380: same --json seam as the local-engine path (renderer parity).
|
||||
const output = params.json === true
|
||||
? JSON.stringify(result, null, 2) + '\n'
|
||||
: formatResult(op.name, result);
|
||||
const output = formatResult(op.name, result);
|
||||
if (output) process.stdout.write(output);
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof RemoteMcpError) {
|
||||
@@ -764,28 +757,10 @@ export function resolveQueryImage(
|
||||
return { path: imagePath, base64, mime };
|
||||
}
|
||||
|
||||
/**
|
||||
* #380: undeclared flags that are honored DOWNSTREAM of parseOpArgs and must
|
||||
* keep passing through when unknown flags become hard errors:
|
||||
* - source → makeContext's resolveSourceId (the --source axis)
|
||||
* - brain → the mount/brain routing axis (docs promise the flag)
|
||||
* - dry_run → makeContext's ctx.dryRun (ops without a declared dry_run)
|
||||
* - json → raw-JSON output seam (local + thin-client paths)
|
||||
*/
|
||||
const PASSTHROUGH_VALUE_FLAGS = new Set(['source', 'brain']);
|
||||
const PASSTHROUGH_BOOL_FLAGS = new Set(['dry_run', 'json']);
|
||||
|
||||
export function parseOpArgs(op: Operation, args: string[]): Record<string, unknown> {
|
||||
const params: Record<string, unknown> = {};
|
||||
const positional = op.cliHints?.positional || [];
|
||||
let posIdx = 0;
|
||||
const cliName = op.cliHints?.name || op.name;
|
||||
const MAX_STDIN = 5_000_000; // 5MB cap, shared by stdin and --file
|
||||
// #380: `--file <path>` fills the op's declared stdin param (put's `content`)
|
||||
// from a file. Driven by cliHints.stdin — no per-op hard-coding — and
|
||||
// disabled when the op declares a real `file` param of its own.
|
||||
const fileParam = op.cliHints?.stdin && !op.params.file ? op.cliHints.stdin : undefined;
|
||||
let filePath: string | undefined;
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
@@ -799,42 +774,12 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
|
||||
}
|
||||
}
|
||||
const key = arg.slice(2).replace(/-/g, '_');
|
||||
if (fileParam && key === 'file') {
|
||||
if (i + 1 >= args.length) {
|
||||
console.error(`Error: ${arg} requires a value.`);
|
||||
process.exit(1);
|
||||
}
|
||||
filePath = args[++i];
|
||||
continue;
|
||||
}
|
||||
const paramDef = op.params[key];
|
||||
if (!paramDef) {
|
||||
if (PASSTHROUGH_BOOL_FLAGS.has(key)) {
|
||||
params[key] = true;
|
||||
continue;
|
||||
}
|
||||
if (PASSTHROUGH_VALUE_FLAGS.has(key)) {
|
||||
if (i + 1 >= args.length) {
|
||||
console.error(`Error: ${arg} requires a value.`);
|
||||
process.exit(1);
|
||||
}
|
||||
params[key] = args[++i];
|
||||
continue;
|
||||
}
|
||||
// #380: unknown flags were silently swallowed into params, so typos
|
||||
// like `put --file` created empty pages instead of erroring.
|
||||
console.error(`Unknown option for gbrain ${cliName}: ${arg}`);
|
||||
console.error(`Run 'gbrain ${cliName} --help' for valid flags.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (paramDef.type === 'boolean') {
|
||||
if (paramDef?.type === 'boolean') {
|
||||
params[key] = true;
|
||||
} else if (i + 1 < args.length) {
|
||||
params[key] = args[++i];
|
||||
if (paramDef.type === 'number') params[key] = Number(params[key]);
|
||||
} else {
|
||||
console.error(`Error: ${arg} requires a value.`);
|
||||
process.exit(1);
|
||||
if (paramDef?.type === 'number') params[key] = Number(params[key]);
|
||||
}
|
||||
} else if (posIdx < positional.length) {
|
||||
const key = positional[posIdx++];
|
||||
@@ -843,30 +788,10 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
|
||||
}
|
||||
}
|
||||
|
||||
// #380: resolve --file AFTER the loop so --file/--content conflicts are
|
||||
// caught in either order.
|
||||
if (filePath !== undefined && fileParam) {
|
||||
if (params[fileParam] !== undefined) {
|
||||
console.error(`Error: use only one of --file, --${fileParam}, or stdin for gbrain ${cliName}.`);
|
||||
process.exit(1);
|
||||
}
|
||||
let fileContent: string;
|
||||
try {
|
||||
fileContent = readFileSync(filePath, 'utf-8');
|
||||
} catch (e) {
|
||||
console.error(`Error: cannot read --file ${filePath}: ${e instanceof Error ? e.message : String(e)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (Buffer.byteLength(fileContent, 'utf-8') > MAX_STDIN) {
|
||||
console.error(`Error: file content exceeds ${MAX_STDIN} bytes. Split into smaller inputs.`);
|
||||
process.exit(1);
|
||||
}
|
||||
params[fileParam] = fileContent;
|
||||
}
|
||||
|
||||
// Read stdin for content params
|
||||
if (op.cliHints?.stdin && !params[op.cliHints.stdin] && !process.stdin.isTTY) {
|
||||
const stdinContent = readFileSync(0, 'utf-8');
|
||||
const MAX_STDIN = 5_000_000; // 5MB
|
||||
if (Buffer.byteLength(stdinContent, 'utf-8') > MAX_STDIN) {
|
||||
console.error(`Error: stdin content exceeds ${MAX_STDIN} bytes. Split into smaller inputs.`);
|
||||
process.exit(1);
|
||||
@@ -2328,10 +2253,6 @@ export function printOpHelp(op: Operation, invokedName?: string) {
|
||||
const prefix = isPos ? ` <${key}>` : ` --${key.replace(/_/g, '-')}`;
|
||||
console.log(`${prefix.padEnd(28)} ${def.description || ''}${req}`);
|
||||
}
|
||||
// #380: ops that read stdin also accept --file <path> (parseOpArgs).
|
||||
if (op.cliHints?.stdin && !op.params.file) {
|
||||
console.log(`${' --file <path>'.padEnd(28)} Read ${op.cliHints.stdin} from a file (alternative to --${op.cliHints.stdin} or stdin)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -186,6 +186,18 @@ export function isSourceStale(src: SourceRow, now = Date.now(), floorMin = FULL_
|
||||
return ageMin >= floorMin;
|
||||
}
|
||||
|
||||
/**
|
||||
* #2060: count sources past the per-source cycle freshness floor. Consumed
|
||||
* by autopilot's dispatch decision — a stale source forces the fanout path
|
||||
* even when the doctor plan is small (score 70–94, plan ≤ 3, est < 300s),
|
||||
* so targeted mode can't leave cycle_freshness stale indefinitely.
|
||||
* dispatchPerSource's own throttles (skipped_fresh / fanoutMax / failure
|
||||
* cooldown) bound the resulting work.
|
||||
*/
|
||||
export function countStaleSources(sources: SourceRow[], now = Date.now(), floorMin = FULL_CYCLE_FLOOR_MIN): number {
|
||||
return sources.filter((s) => isSourceStale(s, now, floorMin)).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Most recent SUCCESSFUL cycle for a source. Prefers `last_source_cycle_at`
|
||||
* (per-source phases, written by the split cycle) and falls back to the legacy
|
||||
|
||||
@@ -901,13 +901,27 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
|
||||
const FULL_CYCLE_FLOOR_MIN = 60;
|
||||
const minutesSinceLastFull = (Date.now() - lastFullCycleAt) / 60000;
|
||||
|
||||
// #2060: stale per-source cycle freshness is a dispatch input. Without
|
||||
// it, a brain sitting at score 70–94 with a small targeted plan (≤3
|
||||
// steps, <300s) stays in targeted mode indefinitely and no per-source
|
||||
// cycle is ever dispatched — cycle_freshness never advances. A stale
|
||||
// source forces the fanout path; dispatchPerSource's throttles
|
||||
// (skipped_fresh / fanoutMax / failure cooldown) bound the work.
|
||||
// Fail-open to 0: a read failure must not block dispatch.
|
||||
let staleCycleSources = 0;
|
||||
try {
|
||||
const { countStaleSources } = await import('./autopilot-fanout.ts');
|
||||
staleCycleSources = countStaleSources(await engine.listAllSources({ localPathOnly: true }));
|
||||
} catch { /* fail-open: freshness is a dispatch hint, not a gate */ }
|
||||
|
||||
const shouldFullCycle =
|
||||
(score >= 95 && plan.length === 0 && minutesSinceLastFull >= FULL_CYCLE_FLOOR_MIN) ||
|
||||
plan.length > 3 ||
|
||||
estTotal >= 300 ||
|
||||
score < 70;
|
||||
score < 70 ||
|
||||
staleCycleSources > 0;
|
||||
|
||||
const shouldSleep = score >= 95 && plan.length === 0 && minutesSinceLastFull < FULL_CYCLE_FLOOR_MIN;
|
||||
const shouldSleep = score >= 95 && plan.length === 0 && minutesSinceLastFull < FULL_CYCLE_FLOOR_MIN && staleCycleSources === 0;
|
||||
|
||||
if (shouldSleep) {
|
||||
if (jsonMode) {
|
||||
|
||||
+19
-10
@@ -854,7 +854,10 @@ interface SyncPhaseResult extends PhaseResult {
|
||||
/**
|
||||
* Resolve the source id for a brain directory by looking up the sources
|
||||
* table. Returns undefined when no registered source matches (falls back
|
||||
* to pre-v0.18 global config.sync.* keys).
|
||||
* to pre-v0.18 global config.sync.* keys) OR when MORE than one source
|
||||
* claims the path — an ambiguous match must not scope phases or stamp
|
||||
* last_full_cycle_at for an arbitrarily-picked source (the "freshness
|
||||
* stamp that lies" this resolution exists to prevent).
|
||||
*/
|
||||
async function resolveSourceForDir(
|
||||
engine: BrainEngine,
|
||||
@@ -865,10 +868,10 @@ async function resolveSourceForDir(
|
||||
if (brainDir === null) return undefined;
|
||||
try {
|
||||
const rows = await engine.executeRaw<{ id: string }>(
|
||||
`SELECT id FROM sources WHERE local_path = $1 LIMIT 1`,
|
||||
`SELECT id FROM sources WHERE local_path = $1 LIMIT 2`,
|
||||
[brainDir],
|
||||
);
|
||||
return rows[0]?.id;
|
||||
return rows.length === 1 ? rows[0]!.id : undefined;
|
||||
} catch {
|
||||
// sources table might not exist on very old brains — fall through.
|
||||
return undefined;
|
||||
@@ -2365,17 +2368,23 @@ export async function runCycle(
|
||||
}
|
||||
|
||||
// v0.38 (codex r1 P0-5): persist per-source cycle completion timestamp
|
||||
// when the cycle ran successfully against an explicit source. Read by
|
||||
// autopilot's per-source freshness gate next tick. Skipped when:
|
||||
// - opts.sourceId is unset (legacy callers — autopilot still here)
|
||||
// - engine is null (no-DB path)
|
||||
// when the cycle ran successfully against a resolvable source. Read by
|
||||
// autopilot's per-source freshness gate next tick.
|
||||
//
|
||||
// #1993: keyed off `cycleSourceId` (opts.sourceId ?? the source resolved
|
||||
// from brainDir) — the SAME id the cycle locked + scoped its phases to —
|
||||
// NOT raw opts.sourceId. The autopilot's inline cycle sets brainDir but
|
||||
// passes no explicit sourceId, so keying off opts.sourceId alone never
|
||||
// advanced last_full_cycle_at and cycle_freshness stayed stale even while
|
||||
// the autopilot cycled every interval. Skipped when:
|
||||
// - no source resolves (engine null, or no checkout AND no opts.sourceId)
|
||||
// - status is 'failed' or 'skipped' (don't mark a non-run as fresh)
|
||||
// - dryRun (writes are out of scope)
|
||||
//
|
||||
// Best-effort: a write failure does NOT change the CycleReport status.
|
||||
// The cost of writing the wrong timestamp post-failure is higher than
|
||||
// the cost of missing a successful write (next cycle will redo work).
|
||||
if (opts.sourceId && engine && !dryRun && !aborted && (status === 'ok' || status === 'clean' || status === 'partial')) {
|
||||
if (cycleSourceId && engine && !dryRun && !aborted && (status === 'ok' || status === 'clean' || status === 'partial')) {
|
||||
try {
|
||||
const nowIso = new Date().toISOString();
|
||||
// #2194 fix #3 (the cycle split): `last_source_cycle_at` is the NEW gate
|
||||
@@ -2385,13 +2394,13 @@ export async function runCycle(
|
||||
// phases (those gate on autopilot.last_global_at), so writing it on a
|
||||
// source-only cycle does not re-introduce the freshness poisoning codex
|
||||
// flagged in the rejected skip-based design.
|
||||
await engine.updateSourceConfig(opts.sourceId, {
|
||||
await engine.updateSourceConfig(cycleSourceId, {
|
||||
last_source_cycle_at: nowIso,
|
||||
last_full_cycle_at: nowIso,
|
||||
});
|
||||
} catch (e) {
|
||||
// Best-effort; cycle already succeeded by the time we get here.
|
||||
console.warn(`[cycle] failed to write last_source_cycle_at for source ${opts.sourceId}: ${e instanceof Error ? e.message : String(e)}`);
|
||||
console.warn(`[cycle] failed to write last_source_cycle_at for source ${cycleSourceId}: ${e instanceof Error ? e.message : String(e)}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -769,7 +769,7 @@ const get_page: Operation = {
|
||||
|
||||
const put_page: Operation = {
|
||||
name: 'put_page',
|
||||
description: 'Write/update a page (markdown with frontmatter). Chunks, embeds, reconciles tags, and (when auto_link/auto_timeline are enabled) extracts + reconciles graph links and timeline entries. On the CLI, `gbrain put SLUG --file PATH` reads content from a file (also `--content` or stdin). For provenance write-through and a binary-NUL guard, prefer `gbrain capture --file PATH --slug SLUG` (v0.39.3.0).',
|
||||
description: 'Write/update a page (markdown with frontmatter). Chunks, embeds, reconciles tags, and (when auto_link/auto_timeline are enabled) extracts + reconciles graph links and timeline entries. For large content on Windows (pipe-buffer limit ~45KB) or any file-as-input workflow, use `gbrain capture --file PATH --slug SLUG` — capture reads the file as a Buffer with a binary-NUL guard and adds provenance write-through (v0.39.3.0).',
|
||||
params: {
|
||||
slug: { type: 'string', required: true, description: 'Page slug' },
|
||||
content: { type: 'string', required: true, description: 'Full markdown content with YAML frontmatter' },
|
||||
@@ -1384,10 +1384,7 @@ const list_pages: Operation = {
|
||||
params: {
|
||||
type: { type: 'string', description: 'Filter by page type' },
|
||||
tag: { type: 'string', description: 'Filter by tag' },
|
||||
limit: { type: 'number', description: 'Max results (default 50, capped at 100 — use offset to paginate beyond)' },
|
||||
// #2876: the 100-row cap was silent and there was no way past it even
|
||||
// though both engines already support OFFSET on listPages.
|
||||
offset: { type: 'number', description: 'Skip first N results (pagination; pair with limit)' },
|
||||
limit: { type: 'number', description: 'Max results (default 50)' },
|
||||
// v0.29 — surface filter that already exists on PageFilters.
|
||||
updated_after: {
|
||||
type: 'string',
|
||||
@@ -1418,10 +1415,6 @@ const list_pages: Operation = {
|
||||
type: p.type as any,
|
||||
tag: p.tag as string,
|
||||
limit: clampSearchLimit(p.limit as number | undefined, 50, 100),
|
||||
// #2876: thread pagination through (engines already honor offset).
|
||||
offset: Number.isFinite(p.offset as number) && (p.offset as number) > 0
|
||||
? Math.floor(p.offset as number)
|
||||
: undefined,
|
||||
includeDeleted: (p.include_deleted as boolean) === true,
|
||||
updated_after: typeof p.updated_after === 'string' ? p.updated_after : undefined,
|
||||
sort,
|
||||
|
||||
@@ -54,6 +54,20 @@ describe('autopilot.ts ↔ dispatchPerSource wiring', () => {
|
||||
expect(AUTOPILOT_SRC).toMatch(/lastFullCycleAt\s*=\s*Date\.now\(\)/);
|
||||
});
|
||||
|
||||
test('stale per-source cycle freshness is a shouldFullCycle input (#2060)', () => {
|
||||
// Targeted mode (score 70–94, plan ≤3, est <300s) must not be able to
|
||||
// starve per-source cycle dispatch: a stale source (per countStaleSources
|
||||
// over listAllSources) forces the fanout path, and the sleep gate must
|
||||
// not fire while stale sources exist. Without these terms, cycle
|
||||
// freshness never advances for a brain that always lands in targeted mode.
|
||||
expect(AUTOPILOT_SRC).toMatch(/countStaleSources/);
|
||||
const fullCycleDeclIdx = AUTOPILOT_SRC.indexOf('const shouldFullCycle');
|
||||
expect(fullCycleDeclIdx).toBeGreaterThan(-1);
|
||||
const decl = AUTOPILOT_SRC.slice(fullCycleDeclIdx, fullCycleDeclIdx + 700);
|
||||
expect(decl).toMatch(/staleCycleSources\s*>\s*0/);
|
||||
expect(decl).toMatch(/const shouldSleep[^;]*staleCycleSources\s*===\s*0/);
|
||||
});
|
||||
|
||||
test('does NOT regress to the single-job dispatch on the full-cycle path', () => {
|
||||
// Pre-PR: the shouldFullCycle branch did:
|
||||
// const job = await queue.add('autopilot-cycle', { repoPath }, {
|
||||
|
||||
@@ -14,6 +14,7 @@ import { describe, test, expect } from 'bun:test';
|
||||
import {
|
||||
readLastFullCycleAt,
|
||||
isSourceStale,
|
||||
countStaleSources,
|
||||
selectSourcesForDispatch,
|
||||
resolveFanoutMax,
|
||||
dispatchPerSource,
|
||||
@@ -74,6 +75,23 @@ describe('isSourceStale', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('countStaleSources (#2060 dispatch-decision input)', () => {
|
||||
const NOW = Date.parse('2026-05-22T12:00:00.000Z');
|
||||
test('counts never-cycled + past-floor sources, ignores fresh', () => {
|
||||
const sources = [
|
||||
src('never-cycled'), // stale (null)
|
||||
src('old', new Date(NOW - 2 * 60 * 60_000).toISOString()), // stale (2h)
|
||||
src('fresh', new Date(NOW - 30 * 60_000).toISOString()), // fresh (30min)
|
||||
];
|
||||
expect(countStaleSources(sources, NOW)).toBe(2);
|
||||
});
|
||||
test('returns 0 for all-fresh and for empty list', () => {
|
||||
const fresh = src('a', new Date(NOW - 10 * 60_000).toISOString());
|
||||
expect(countStaleSources([fresh], NOW)).toBe(0);
|
||||
expect(countStaleSources([], NOW)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('selectSourcesForDispatch', () => {
|
||||
const NOW = Date.parse('2026-05-22T12:00:00.000Z');
|
||||
const fresh = (id: string, agoMin: number) =>
|
||||
|
||||
@@ -1,41 +1,8 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
import { parseOpArgs } from '../src/cli.ts';
|
||||
import { operationsByName } from '../src/core/operations.ts';
|
||||
|
||||
describe('parseOpArgs', () => {
|
||||
// #380: `gbrain put SLUG --file PATH` reads content from the file instead
|
||||
// of silently swallowing the flag and creating an empty page.
|
||||
test('put --file reads the stdin param (content) from a file', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'gbrain-put-file-'));
|
||||
try {
|
||||
const pagePath = join(dir, 'page.md');
|
||||
writeFileSync(pagePath, '# From file\n\nBody loaded from --file.\n');
|
||||
const params = parseOpArgs(operationsByName.put_page, ['concepts/from-file', '--file', pagePath]);
|
||||
expect(params.slug).toBe('concepts/from-file');
|
||||
expect(params.content).toBe('# From file\n\nBody loaded from --file.\n');
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// #380 regression guard: undeclared-but-honored flags must keep passing
|
||||
// through when unknown flags become hard errors (--source is read by
|
||||
// makeContext; --json by the output seam; --dry-run by ctx.dryRun).
|
||||
test('pass-through allowlist flags survive on ops that do not declare them', () => {
|
||||
const params = parseOpArgs(operationsByName.get_page, [
|
||||
'people/alice-example', '--source', 'wiki', '--json', '--dry-run',
|
||||
]);
|
||||
expect(params).toEqual({
|
||||
slug: 'people/alice-example',
|
||||
source: 'wiki',
|
||||
json: true,
|
||||
dry_run: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('--no-<boolean> maps to false without consuming the next flag', () => {
|
||||
const params = parseOpArgs(operationsByName.query, [
|
||||
'freshEmbedSourceScope code source',
|
||||
|
||||
+1
-71
@@ -1,5 +1,5 @@
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
|
||||
@@ -120,76 +120,6 @@ describe('CLI dispatch integration', () => {
|
||||
expect(exitCode).toBe(0);
|
||||
});
|
||||
|
||||
// #380 / PR #856: put --help documents the --file input path.
|
||||
test('put --help documents --file input', async () => {
|
||||
const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'put', '--help'], {
|
||||
cwd: repoRoot,
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
});
|
||||
const stdout = await new Response(proc.stdout).text();
|
||||
const exitCode = await proc.exited;
|
||||
expect(stdout).toContain('Usage: gbrain put');
|
||||
expect(stdout).toContain('--file <path>');
|
||||
expect(exitCode).toBe(0);
|
||||
});
|
||||
|
||||
// #380: unknown flags on shared ops are a hard error (previously silently
|
||||
// swallowed into params — `put --file` created empty pages). parseOpArgs
|
||||
// runs BEFORE engine connect, so the error must fire without a brain.
|
||||
test('unknown shared-op flags fail before DB connection', async () => {
|
||||
const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-unknown-flag-'));
|
||||
try {
|
||||
const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'get', 'people/alice', '--bogus'], {
|
||||
cwd: repoRoot,
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
env: isolatedEnv(home),
|
||||
});
|
||||
const stderr = await new Response(proc.stderr).text();
|
||||
const exitCode = await proc.exited;
|
||||
expect(stderr).toContain('Unknown option for gbrain get: --bogus');
|
||||
expect(stderr).not.toContain('No brain configured');
|
||||
expect(exitCode).toBe(1);
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('put rejects combining --file and --content', async () => {
|
||||
const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-put-conflict-'));
|
||||
try {
|
||||
const pagePath = join(home, 'page.md');
|
||||
writeFileSync(pagePath, 'file body\n');
|
||||
const proc = Bun.spawn(
|
||||
['bun', 'run', 'src/cli.ts', 'put', 'a/b', '--content', 'inline', '--file', pagePath],
|
||||
{ cwd: repoRoot, stdout: 'pipe', stderr: 'pipe', env: isolatedEnv(home) },
|
||||
);
|
||||
const stderr = await new Response(proc.stderr).text();
|
||||
const exitCode = await proc.exited;
|
||||
expect(stderr).toContain('use only one of --file, --content, or stdin');
|
||||
expect(exitCode).toBe(1);
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('put --file with a missing path errors instead of writing an empty page', async () => {
|
||||
const home = mkdtempSync(join(tmpdir(), 'gbrain-cli-put-missing-file-'));
|
||||
try {
|
||||
const proc = Bun.spawn(
|
||||
['bun', 'run', 'src/cli.ts', 'put', 'a/b', '--file', join(home, 'nope.md')],
|
||||
{ cwd: repoRoot, stdout: 'pipe', stderr: 'pipe', env: isolatedEnv(home) },
|
||||
);
|
||||
const stderr = await new Response(proc.stderr).text();
|
||||
const exitCode = await proc.exited;
|
||||
expect(stderr).toContain('cannot read --file');
|
||||
expect(exitCode).toBe(1);
|
||||
} finally {
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('upgrade --help prints usage without running upgrade', async () => {
|
||||
const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'upgrade', '--help'], {
|
||||
cwd: repoRoot,
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
* cycles. Closes codex round-1 P0-5 (write site for last_full_cycle_at
|
||||
* was unspecified pre-PR).
|
||||
*
|
||||
* Conditions for write:
|
||||
* - opts.sourceId is set (legacy callers without sourceId skip the write)
|
||||
* Conditions for write (keyed off `cycleSourceId` = opts.sourceId ?? the
|
||||
* source resolved from brainDir, so the autopilot's inline cycle — brainDir
|
||||
* set, no explicit sourceId — also advances the timestamp, #1993):
|
||||
* - a source resolves (explicit sourceId, or brainDir matches a source)
|
||||
* - engine is non-null (no-DB path skips)
|
||||
* - status is 'ok' | 'clean' | 'partial' (failed/skipped don't mark fresh)
|
||||
* - dryRun is false
|
||||
@@ -90,17 +92,45 @@ describe('runCycle last_full_cycle_at exit hook', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('legacy caller (no sourceId) does NOT write any source timestamp', async () => {
|
||||
test('no explicit sourceId but brainDir resolves a source → writes the resolved source timestamp', async () => {
|
||||
await withEnv({ GBRAIN_HOME: gbrainHome }, async () => {
|
||||
await seedSource('default-like');
|
||||
// No sourceId passed; should remain untouched.
|
||||
// The autopilot's inline cycle sets brainDir but passes no sourceId.
|
||||
// runCycle resolves the source from brainDir (local_path match) into
|
||||
// cycleSourceId and stamps last_full_cycle_at for it — otherwise
|
||||
// cycle_freshness reports the brain stale even while the autopilot
|
||||
// cycles every interval (#1993).
|
||||
await seedSource('resolved-from-dir'); // local_path = brainDir
|
||||
expect(await readLastFullCycleAt('resolved-from-dir')).toBeNull();
|
||||
|
||||
const t0 = Date.now();
|
||||
const report = await runCycle(engine, {
|
||||
brainDir,
|
||||
phases: ['lint'],
|
||||
});
|
||||
expect(['ok', 'clean']).toContain(report.status);
|
||||
|
||||
const after = await readLastFullCycleAt('resolved-from-dir');
|
||||
expect(after).not.toBeNull();
|
||||
expect(new Date(after!).getTime()).toBeGreaterThanOrEqual(t0);
|
||||
});
|
||||
});
|
||||
|
||||
test('no sourceId and brainDir matches no source → does not write', async () => {
|
||||
await withEnv({ GBRAIN_HOME: gbrainHome }, async () => {
|
||||
// A source exists but its local_path does NOT match brainDir, so
|
||||
// resolveSourceForDir returns undefined, cycleSourceId is undefined,
|
||||
// and no per-source timestamp is written.
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO sources (id, name, local_path, config, archived, created_at)
|
||||
VALUES ('unmatched', 'unmatched', '/no/such/repo', '{}'::jsonb, false, NOW())
|
||||
ON CONFLICT (id) DO UPDATE SET local_path = EXCLUDED.local_path`,
|
||||
[],
|
||||
);
|
||||
await runCycle(engine, {
|
||||
brainDir,
|
||||
phases: ['lint'],
|
||||
});
|
||||
// No per-source write happens; default source's config stays empty.
|
||||
const after = await readLastFullCycleAt('default-like');
|
||||
expect(after).toBeNull();
|
||||
expect(await readLastFullCycleAt('unmatched')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { operationsByName } from '../src/core/operations.ts';
|
||||
|
||||
/**
|
||||
* #2876: `gbrain list --limit` silently clamped at 100 with no pagination.
|
||||
* list_pages now declares `offset` (both engines already supported it on
|
||||
* PageFilters) and the limit description discloses the 100-row cap.
|
||||
*/
|
||||
describe('list_pages pagination (#2876)', () => {
|
||||
const listPagesOp = operationsByName.list_pages;
|
||||
|
||||
function makeCtx(captured: unknown[]) {
|
||||
return {
|
||||
engine: {
|
||||
listPages: async (filters: unknown) => {
|
||||
captured.push(filters);
|
||||
return [];
|
||||
},
|
||||
},
|
||||
config: { engine: 'pglite' },
|
||||
logger: { info() {}, warn() {}, error() {} },
|
||||
dryRun: false,
|
||||
remote: false,
|
||||
sourceId: 'default',
|
||||
} as any;
|
||||
}
|
||||
|
||||
test('declares offset param and discloses the 100-row cap on limit', () => {
|
||||
expect(listPagesOp.params.offset).toBeDefined();
|
||||
expect(listPagesOp.params.offset.type).toBe('number');
|
||||
expect(listPagesOp.params.limit.description).toContain('100');
|
||||
});
|
||||
|
||||
test('threads offset through to engine.listPages', async () => {
|
||||
const captured: any[] = [];
|
||||
await listPagesOp.handler(makeCtx(captured), { limit: 10, offset: 30 });
|
||||
expect(captured[0].offset).toBe(30);
|
||||
expect(captured[0].limit).toBe(10);
|
||||
});
|
||||
|
||||
test('drops negative, non-finite, and zero offsets', async () => {
|
||||
const captured: any[] = [];
|
||||
const ctx = makeCtx(captured);
|
||||
await listPagesOp.handler(ctx, { offset: -5 });
|
||||
await listPagesOp.handler(ctx, { offset: Infinity });
|
||||
await listPagesOp.handler(ctx, { offset: 0 });
|
||||
for (const f of captured) expect(f.offset).toBeUndefined();
|
||||
});
|
||||
|
||||
test('floors fractional offsets', async () => {
|
||||
const captured: any[] = [];
|
||||
await listPagesOp.handler(makeCtx(captured), { offset: 7.9 });
|
||||
expect(captured[0].offset).toBe(7);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user