mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-17 10:22:34 +00:00
Compare commits
91
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a3f0722080 | ||
|
|
0431dfd67f | ||
|
|
50406fc212 | ||
|
|
0556dbdc2c | ||
|
|
220af4b2d0 | ||
|
|
fe6850b067 | ||
|
|
8fc93c8fac | ||
|
|
3454dca0b4 | ||
|
|
5dcf3e7b2f | ||
|
|
dbca701008 | ||
|
|
4b6cf32c9f | ||
|
|
0c66715f90 | ||
|
|
55af5fc091 | ||
|
|
10b5746053 | ||
|
|
5bee08c3c4 | ||
|
|
f02919c041 | ||
|
|
66fa5fba22 | ||
|
|
e79b8d5780 | ||
|
|
fc1f88cdcb | ||
|
|
70ffe4a2a2 | ||
|
|
5a295bc293 | ||
|
|
2724c3b6c9 | ||
|
|
1233051a20 | ||
|
|
53c9086945 | ||
|
|
033fd24fe8 | ||
|
|
8915fba476 | ||
|
|
372f013158 | ||
|
|
439bbaac3a | ||
|
|
a1bb7683d0 | ||
|
|
94535fc0e0 | ||
|
|
a6aafddd23 | ||
|
|
c92af9a7d6 | ||
|
|
beedacde56 | ||
|
|
f8dbfca2f5 | ||
|
|
b7f70970c1 | ||
|
|
1b099aeaca | ||
|
|
2941e17798 | ||
|
|
503f61e6e4 | ||
|
|
0367c800a4 | ||
|
|
23df0227bd | ||
|
|
3225bdf768 | ||
|
|
6ec5261700 | ||
|
|
b0d136ee6d | ||
|
|
47d7e95b74 | ||
|
|
c0d4def5bc | ||
|
|
c0a4b80f0d | ||
|
|
0bd752b3f7 | ||
|
|
6e4c2435e3 | ||
|
|
1a9ab6a95f | ||
|
|
7c06af281d | ||
|
|
5ac81b0d0a | ||
|
|
c0cb6c533b | ||
|
|
d67be8b570 | ||
|
|
a356f64e4f | ||
|
|
a1dadebd60 | ||
|
|
c43ed81c72 | ||
|
|
1d0df706fe | ||
|
|
8078c46ab7 | ||
|
|
e20a6a5328 | ||
|
|
1a449bf501 | ||
|
|
74358329e1 | ||
|
|
a8a94f5742 | ||
|
|
f065eb1509 | ||
|
|
49cf5202cb | ||
|
|
b928f40bcd | ||
|
|
bb5a66942d | ||
|
|
6cf4f3122d | ||
|
|
6cf8d8d66c | ||
|
|
355fbc6947 | ||
|
|
2c96787867 | ||
|
|
8a5296f3cb | ||
|
|
8837bfe5f2 | ||
|
|
e1526bfebe | ||
|
|
44cae62324 | ||
|
|
56ccc14bcc | ||
|
|
e7ffbc057c | ||
|
|
0a757bf780 | ||
|
|
2b020ba2bd | ||
|
|
d43fb631bc | ||
|
|
292b8b1637 | ||
|
|
e78ad9ff9e | ||
|
|
2840734d70 | ||
|
|
d69f211629 | ||
|
|
02ba4b4fc2 | ||
|
|
d9eb027bdd | ||
|
|
62e009d192 | ||
|
|
314fefa560 | ||
|
|
7f841fae7f | ||
|
|
1fabbb9849 | ||
|
|
64920f83c9 | ||
|
|
e861b92da7 |
@@ -206,7 +206,11 @@ jobs:
|
||||
needs: cache-check
|
||||
if: needs.cache-check.outputs.hit != 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
# 22, not 15: under parallel PR load the PGLite WASM cold-starts stretch a
|
||||
# shard past 15 min while every test is still passing — the timeout then
|
||||
# cancels the job and the test-status gate reads it as a failure. 13 runs
|
||||
# died this way on 2026-07-21/22 alone.
|
||||
timeout-minutes: 22
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
|
||||
@@ -71,8 +71,8 @@ GBrain is designed to be installed and operated by an AI agent. The fastest path
|
||||
|
||||
If you don't already have an AI agent platform running, start with one of these. Both are designed to read GBrain's install protocol and execute it:
|
||||
|
||||
- **[OpenClaw](https://github.com/openclawagents/openclaw)** — deploy [AlphaClaw on Render](https://render.com/deploy?repo=https://github.com/chrysb/alphaclaw) (one click, 8GB+ RAM)
|
||||
- **[Hermes](https://github.com/openclawagents/hermes)** — deploy on [Railway](https://github.com/praveen-ks-2001/hermes-agent-template) (one click)
|
||||
- **[OpenClaw](https://github.com/openclaw/openclaw)** — deploy [AlphaClaw on Render](https://render.com/deploy?repo=https://github.com/chrysb/alphaclaw) (one click, 8GB+ RAM)
|
||||
- **[Hermes](https://github.com/NousResearch/hermes-agent)** — deploy on [Railway](https://github.com/praveen-ks-2001/hermes-agent-template) (one click)
|
||||
|
||||
Then paste this into your agent:
|
||||
|
||||
|
||||
Vendored
-56
File diff suppressed because one or more lines are too long
Vendored
+56
File diff suppressed because one or more lines are too long
Vendored
+1
-1
@@ -7,7 +7,7 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
|
||||
<script type="module" crossorigin src="/admin/assets/index-BpDk4NI4.js"></script>
|
||||
<script type="module" crossorigin src="/admin/assets/index-CoGEje3-.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/admin/assets/index-GxkWX7v3.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
+2
-6
@@ -5,14 +5,13 @@ import { AgentsPage } from './pages/Agents';
|
||||
import { RequestLogPage } from './pages/RequestLog';
|
||||
import { CalibrationPage } from './pages/Calibration';
|
||||
import { JobsWatchPage } from './pages/JobsWatch';
|
||||
import { SourcesPage } from './pages/Sources';
|
||||
import { api } from './api';
|
||||
|
||||
type Page = 'login' | 'dashboard' | 'agents' | 'sources' | 'log' | 'calibration' | 'jobs';
|
||||
type Page = 'login' | 'dashboard' | 'agents' | 'log' | 'calibration' | 'jobs';
|
||||
|
||||
function getPage(): Page {
|
||||
const hash = window.location.hash.replace('#', '') || 'dashboard';
|
||||
if (['login', 'dashboard', 'agents', 'sources', 'log', 'calibration', 'jobs'].includes(hash)) return hash as Page;
|
||||
if (['login', 'dashboard', 'agents', 'log', 'calibration', 'jobs'].includes(hash)) return hash as Page;
|
||||
return 'dashboard';
|
||||
}
|
||||
|
||||
@@ -55,8 +54,6 @@ export function App() {
|
||||
onClick={() => navigate('dashboard')}>Dashboard</a>
|
||||
<a className={`nav-item ${page === 'agents' ? 'active' : ''}`}
|
||||
onClick={() => navigate('agents')}>Agents</a>
|
||||
<a className={`nav-item ${page === 'sources' ? 'active' : ''}`}
|
||||
onClick={() => navigate('sources')}>Sources</a>
|
||||
<a className={`nav-item ${page === 'log' ? 'active' : ''}`}
|
||||
onClick={() => navigate('log')}>Request Log</a>
|
||||
<a className={`nav-item ${page === 'calibration' ? 'active' : ''}`}
|
||||
@@ -86,7 +83,6 @@ export function App() {
|
||||
<main className="main">
|
||||
{page === 'dashboard' && <DashboardPage />}
|
||||
{page === 'agents' && <AgentsPage />}
|
||||
{page === 'sources' && <SourcesPage />}
|
||||
{page === 'log' && <RequestLogPage />}
|
||||
{page === 'calibration' && <CalibrationPage />}
|
||||
{page === 'jobs' && <JobsWatchPage />}
|
||||
|
||||
@@ -52,22 +52,4 @@ export const api = {
|
||||
apiFetchText(`/admin/api/calibration/charts/${encodeURIComponent(type)}${holder ? `?holder=${encodeURIComponent(holder)}` : ''}`),
|
||||
// v0.41 D2 — live minion-jobs dashboard snapshot.
|
||||
jobsWatch: () => apiFetch('/admin/api/jobs/watch'),
|
||||
// v0.41.29 Sources tab + federated-read management
|
||||
sources: () => apiFetch('/admin/api/sources'),
|
||||
agentsFederatedRead: () => apiFetch('/admin/api/agents/federated-read'),
|
||||
grantRead: (clientId: string, sourceId: string) =>
|
||||
apiFetch(`/admin/api/agents/${encodeURIComponent(clientId)}/grant-read`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ source_id: sourceId }),
|
||||
}),
|
||||
revokeRead: (clientId: string, sourceId: string) =>
|
||||
apiFetch(`/admin/api/agents/${encodeURIComponent(clientId)}/revoke-read`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ source_id: sourceId }),
|
||||
}),
|
||||
setFederatedRead: (clientId: string, sourceIds: string[]) =>
|
||||
apiFetch(`/admin/api/agents/${encodeURIComponent(clientId)}/set-federated-read`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ source_ids: sourceIds }),
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -381,16 +381,8 @@ function CredentialsModal({ credentials, onClose }: {
|
||||
);
|
||||
}
|
||||
|
||||
interface FederationState {
|
||||
source_id: string | null;
|
||||
federated_read: string[];
|
||||
}
|
||||
|
||||
function AgentDrawer({ agent, onClose, onRevoked }: { agent: Agent; onClose: () => void; onRevoked: () => void }) {
|
||||
const [tab, setTab] = useState<'claude-code' | 'chatgpt' | 'claude-cowork' | 'perplexity' | 'cursor' | 'json'>('claude-code');
|
||||
const [federation, setFederation] = useState<FederationState | null>(null);
|
||||
const [allSources, setAllSources] = useState<string[]>([]);
|
||||
const [showFederation, setShowFederation] = useState(false);
|
||||
const copy = (text: string) => navigator.clipboard.writeText(text);
|
||||
const serverUrl = window.location.origin;
|
||||
|
||||
@@ -398,30 +390,6 @@ function AgentDrawer({ agent, onClose, onRevoked }: { agent: Agent; onClose: ()
|
||||
const isOAuth = agent.auth_type === 'oauth';
|
||||
const agentName = agent.name || agent.client_name || 'unknown';
|
||||
|
||||
// Lazy-load federation state when the drawer opens for an OAuth client.
|
||||
// The /admin/api/agents endpoint doesn't carry source_id / federated_read,
|
||||
// so we fetch /admin/api/agents/federated-read separately and pair by id.
|
||||
useEffect(() => {
|
||||
if (!isOAuth || !cid) return;
|
||||
let cancelled = false;
|
||||
Promise.all([
|
||||
api.agentsFederatedRead().catch(() => ({ clients: [] })),
|
||||
api.sources().catch(() => ({ sources: [] })),
|
||||
]).then(([feds, srcs]: any) => {
|
||||
if (cancelled) return;
|
||||
const me = (feds.clients || []).find((c: any) => c.client_id === cid);
|
||||
setFederation(me ? { source_id: me.source_id, federated_read: me.federated_read || [] } : null);
|
||||
setAllSources((srcs.sources || []).map((s: any) => s.source_id));
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [cid, isOAuth]);
|
||||
|
||||
const reloadFederation = async () => {
|
||||
const feds: any = await api.agentsFederatedRead().catch(() => ({ clients: [] }));
|
||||
const me = (feds.clients || []).find((c: any) => c.client_id === cid);
|
||||
setFederation(me ? { source_id: me.source_id, federated_read: me.federated_read || [] } : null);
|
||||
};
|
||||
|
||||
// For API keys, we can't show the actual token (it was shown once at creation).
|
||||
// For OAuth, we show the client_id and tell them to use their secret.
|
||||
|
||||
@@ -585,34 +553,6 @@ function AgentDrawer({ agent, onClose, onRevoked }: { agent: Agent; onClose: ()
|
||||
<span>{agent.token_ttl ? (agent.token_ttl >= 31536000 ? 'No expiry' : agent.token_ttl >= 86400 ? `${Math.floor(agent.token_ttl / 86400)}d` : agent.token_ttl >= 3600 ? `${Math.floor(agent.token_ttl / 3600)}h` : `${agent.token_ttl}s`) : '1h (default)'}</span>
|
||||
</div>
|
||||
|
||||
{isOAuth && federation && (
|
||||
<>
|
||||
<div className="section-title" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<span>Federation</span>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
style={{ padding: '4px 10px', fontSize: 12 }}
|
||||
onClick={() => setShowFederation(true)}
|
||||
>
|
||||
Manage reads
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: '6px 12px', fontSize: 13 }}>
|
||||
<span style={{ color: 'var(--text-secondary)' }}>Write source</span>
|
||||
<span className="mono">{federation.source_id || '(none)'}</span>
|
||||
<span style={{ color: 'var(--text-secondary)' }}>Federated reads</span>
|
||||
<span style={{ fontSize: 12 }}>
|
||||
{federation.federated_read.length === 0
|
||||
? <span style={{ color: 'var(--text-muted)' }}>(empty — no federated reads)</span>
|
||||
: federation.federated_read.map((s) => (
|
||||
<span key={s} className="badge badge-read" style={{ marginRight: 4, marginBottom: 2 }}>{s}</span>
|
||||
))
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/*
|
||||
Config Export visible for both auth_type=oauth AND auth_type=api_key.
|
||||
Claude Code + Cursor + JSON tabs render real snippets regardless
|
||||
@@ -688,142 +628,6 @@ function AgentDrawer({ agent, onClose, onRevoked }: { agent: Agent; onClose: ()
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showFederation && federation && (
|
||||
<FederationModal
|
||||
clientId={cid}
|
||||
clientName={agentName}
|
||||
allSources={allSources}
|
||||
currentReads={federation.federated_read}
|
||||
writeSource={federation.source_id}
|
||||
onClose={() => setShowFederation(false)}
|
||||
onSaved={async () => {
|
||||
await reloadFederation();
|
||||
setShowFederation(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* FederationModal — admin counterpart of `gbrain auth set-federated-read`.
|
||||
* Source checkbox list; "Save" submits the full new list via the
|
||||
* race-safe atomic SQL path in setFederatedReadCore. Per the CLI's
|
||||
* documented contract, this is wholesale-replace semantics — concurrent
|
||||
* grant/revoke from a CLI operator would be last-writer-wins against
|
||||
* a Save here.
|
||||
*/
|
||||
function FederationModal({
|
||||
clientId, clientName, allSources, currentReads, writeSource, onClose, onSaved,
|
||||
}: {
|
||||
clientId: string;
|
||||
clientName: string;
|
||||
allSources: string[];
|
||||
currentReads: string[];
|
||||
writeSource: string | null;
|
||||
onClose: () => void;
|
||||
onSaved: () => Promise<void> | void;
|
||||
}) {
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set(currentReads));
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const toggle = (id: string) => {
|
||||
const next = new Set(selected);
|
||||
if (next.has(id)) next.delete(id); else next.add(id);
|
||||
setSelected(next);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.setFederatedRead(clientId, Array.from(selected));
|
||||
await onSaved();
|
||||
} catch (e: any) {
|
||||
setError(e.message || 'save failed');
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Union: all known sources + any current reads not in the source list
|
||||
// (e.g. orphan entries from before the source was deleted). The latter
|
||||
// surface as "(missing source)" so operators can revoke them.
|
||||
const allKnown = new Set([...allSources, ...currentReads]);
|
||||
const ordered = Array.from(allKnown).sort();
|
||||
|
||||
return (
|
||||
<div className="modal-overlay" onClick={onClose}>
|
||||
<div className="modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 520 }}>
|
||||
<div className="modal-header">
|
||||
<div style={{ fontSize: 16, fontWeight: 600 }}>Manage federated reads</div>
|
||||
<div style={{ fontSize: 13, color: 'var(--text-secondary)', marginTop: 4 }}>
|
||||
<strong>{clientName}</strong> — pick which sources this client can read in addition to its
|
||||
{writeSource ? <> write source <code className="mono">{writeSource}</code></> : <> write source</>}.
|
||||
</div>
|
||||
</div>
|
||||
<div className="modal-body" style={{ maxHeight: '50vh', overflowY: 'auto' }}>
|
||||
{ordered.length === 0 && (
|
||||
<div style={{ color: 'var(--text-muted)', fontSize: 13 }}>
|
||||
No sources registered. Use <code>gbrain sources add <id> --path <dir></code> from the CLI first.
|
||||
</div>
|
||||
)}
|
||||
{ordered.map((id) => {
|
||||
const isOrphan = !allSources.includes(id);
|
||||
const isWriteSource = id === writeSource;
|
||||
return (
|
||||
<label
|
||||
key={id}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
padding: '8px 10px',
|
||||
borderBottom: '1px solid var(--border)',
|
||||
cursor: 'pointer',
|
||||
fontSize: 13,
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.has(id)}
|
||||
onChange={() => toggle(id)}
|
||||
style={{ width: 16, height: 16, margin: 0, flexShrink: 0, cursor: 'pointer' }}
|
||||
/>
|
||||
<span className="mono" style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{id}</span>
|
||||
{isWriteSource && <span className="badge badge-write" style={{ fontSize: 10, flexShrink: 0 }}>write source</span>}
|
||||
{isOrphan && <span className="badge badge-danger" style={{ fontSize: 10, flexShrink: 0 }}>missing source</span>}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{error && (
|
||||
<div style={{
|
||||
background: 'rgba(239,68,68,0.08)',
|
||||
border: '1px solid rgba(239,68,68,0.3)',
|
||||
color: '#ef4444',
|
||||
padding: '10px 12px',
|
||||
borderRadius: 6,
|
||||
margin: '12px 0',
|
||||
fontSize: 12,
|
||||
}}>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<div className="modal-footer">
|
||||
<button type="button" className="btn btn-secondary" onClick={onClose} disabled={saving}>Cancel</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? 'Saving…' : `Save (${selected.size} source${selected.size === 1 ? '' : 's'})`}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { api } from '../api';
|
||||
|
||||
interface SourceRow {
|
||||
source_id: string;
|
||||
name: string;
|
||||
local_path: string | null;
|
||||
sync_enabled: boolean;
|
||||
last_sync_at: string | null;
|
||||
staleness_hours: number | null;
|
||||
staleness_class: 'fresh' | 'stale' | 'severe' | 'unknown';
|
||||
last_commit: string | null;
|
||||
pages: number;
|
||||
chunks_total: number;
|
||||
chunks_unembedded: number;
|
||||
embedding_coverage_pct: number;
|
||||
}
|
||||
|
||||
interface FederatedClient {
|
||||
client_id: string;
|
||||
client_name: string;
|
||||
source_id: string | null;
|
||||
federated_read: string[];
|
||||
}
|
||||
|
||||
function timeAgo(iso: string | null): string {
|
||||
if (!iso) return 'never';
|
||||
const s = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
|
||||
if (s < 0) return 'in the future?';
|
||||
if (s < 60) return 'just now';
|
||||
if (s < 3600) return `${Math.floor(s / 60)}m ago`;
|
||||
if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
|
||||
return `${Math.floor(s / 86400)}d ago`;
|
||||
}
|
||||
|
||||
function stalenessColor(cls: string): string {
|
||||
switch (cls) {
|
||||
case 'fresh': return '#4ade80';
|
||||
case 'stale': return '#fbbf24';
|
||||
case 'severe': return '#ef4444';
|
||||
default: return 'var(--text-muted)';
|
||||
}
|
||||
}
|
||||
|
||||
function coverageColor(pct: number): string {
|
||||
if (pct >= 99) return '#4ade80';
|
||||
if (pct >= 90) return '#fbbf24';
|
||||
return '#ef4444';
|
||||
}
|
||||
|
||||
export function SourcesPage() {
|
||||
const [sources, setSources] = useState<SourceRow[]>([]);
|
||||
const [clients, setClients] = useState<FederatedClient[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [srcReport, clientsResp] = await Promise.all([
|
||||
api.sources(),
|
||||
api.agentsFederatedRead(),
|
||||
]);
|
||||
setSources(srcReport.sources || []);
|
||||
setClients(clientsResp.clients || []);
|
||||
} catch (e: any) {
|
||||
setError(e.message || 'load failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => { load(); }, []);
|
||||
|
||||
// Reverse-lookup: for each source, which clients can read it?
|
||||
const readersBySource = (sourceId: string): string[] =>
|
||||
clients.filter((c) => c.federated_read.includes(sourceId)).map((c) => c.client_name);
|
||||
|
||||
// Reverse-lookup: which clients WRITE to this source (source_id == sourceId)?
|
||||
const writersBySource = (sourceId: string): string[] =>
|
||||
clients.filter((c) => c.source_id === sourceId).map((c) => c.client_name);
|
||||
|
||||
return (
|
||||
<div style={{ padding: 24, maxWidth: 1200 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
|
||||
<h1 style={{ fontSize: 24, margin: 0 }}>Sources</h1>
|
||||
<button
|
||||
onClick={load}
|
||||
style={{
|
||||
background: 'transparent',
|
||||
border: '1px solid var(--border)',
|
||||
color: 'var(--text-secondary)',
|
||||
padding: '6px 12px',
|
||||
borderRadius: 6,
|
||||
fontSize: 12,
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loading && <div style={{ color: 'var(--text-muted)' }}>Loading…</div>}
|
||||
{error && (
|
||||
<div style={{
|
||||
background: 'rgba(239,68,68,0.08)',
|
||||
border: '1px solid rgba(239,68,68,0.3)',
|
||||
color: '#ef4444',
|
||||
padding: 12,
|
||||
borderRadius: 6,
|
||||
marginBottom: 16,
|
||||
fontSize: 13,
|
||||
}}>
|
||||
Failed to load sources: {error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && sources.length === 0 && (
|
||||
<div style={{ color: 'var(--text-muted)', padding: 16 }}>
|
||||
No active sources with a local_path. Use{' '}
|
||||
<code style={{ background: 'var(--bg-elevated)', padding: '2px 6px', borderRadius: 4 }}>
|
||||
gbrain sources add <id> --path <dir>
|
||||
</code>{' '}
|
||||
to register one.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && sources.length > 0 && (
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
|
||||
<thead>
|
||||
<tr style={{ borderBottom: '1px solid var(--border)', textAlign: 'left', color: 'var(--text-muted)' }}>
|
||||
<th style={{ padding: '10px 12px' }}>ID</th>
|
||||
<th style={{ padding: '10px 12px', textAlign: 'right' }}>Pages</th>
|
||||
<th style={{ padding: '10px 12px', textAlign: 'right' }}>Chunks</th>
|
||||
<th style={{ padding: '10px 12px', textAlign: 'right' }}>Embed%</th>
|
||||
<th style={{ padding: '10px 12px' }}>Last Sync</th>
|
||||
<th style={{ padding: '10px 12px' }}>Writers</th>
|
||||
<th style={{ padding: '10px 12px' }}>Readers (federated)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sources.map((s) => {
|
||||
const readers = readersBySource(s.source_id);
|
||||
const writers = writersBySource(s.source_id);
|
||||
return (
|
||||
<tr key={s.source_id} style={{ borderBottom: '1px solid var(--border)' }}>
|
||||
<td style={{ padding: '10px 12px', fontFamily: 'JetBrains Mono, monospace' }}>
|
||||
<div>{s.source_id}</div>
|
||||
{s.name !== s.source_id && (
|
||||
<div style={{ fontSize: 11, color: 'var(--text-muted)', fontFamily: 'inherit' }}>{s.name}</div>
|
||||
)}
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px', textAlign: 'right', fontFamily: 'JetBrains Mono, monospace' }}>{s.pages.toLocaleString()}</td>
|
||||
<td style={{ padding: '10px 12px', textAlign: 'right', fontFamily: 'JetBrains Mono, monospace' }}>{s.chunks_total.toLocaleString()}</td>
|
||||
<td style={{ padding: '10px 12px', textAlign: 'right', color: coverageColor(s.embedding_coverage_pct), fontFamily: 'JetBrains Mono, monospace' }}>
|
||||
{s.embedding_coverage_pct.toFixed(0)}%
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px', color: s.local_path == null ? 'var(--text-muted)' : stalenessColor(s.staleness_class) }}>
|
||||
{s.local_path == null ? 'push-only' : timeAgo(s.last_sync_at)}
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px', fontSize: 12, color: 'var(--text-secondary)' }}>
|
||||
{writers.length === 0 ? <span style={{ color: 'var(--text-muted)' }}>none</span> : writers.join(', ')}
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px', fontSize: 12, color: 'var(--text-secondary)' }}>
|
||||
{readers.length === 0 ? <span style={{ color: 'var(--text-muted)' }}>none</span> : readers.join(', ')}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{
|
||||
marginTop: 24,
|
||||
padding: 12,
|
||||
background: 'var(--bg-elevated)',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: 6,
|
||||
fontSize: 12,
|
||||
color: 'var(--text-muted)',
|
||||
lineHeight: 1.6,
|
||||
}}>
|
||||
<strong style={{ color: 'var(--text-secondary)' }}>Two scopes per OAuth client:</strong>{' '}
|
||||
<em>Writers</em> = clients with this source as their <code>source_id</code> (write authority).{' '}
|
||||
<em>Readers</em> = clients with this source in their <code>federated_read</code> list (read access via federation).
|
||||
Manage federation per-client from the <a href="#agents" style={{ color: '#60a5fa' }}>Agents</a> tab using the
|
||||
"Manage reads" action.
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -131,7 +131,9 @@ into gbrain so other clients can scaffold it. Default behavior:
|
||||
`~/.gbrain/harvest-private-patterns.txt` plus built-in defaults
|
||||
(canonical private fork name, common email regex, Slack channel pattern). Any
|
||||
match → rollback (delete the harvested files) and exit non-zero.
|
||||
- `openclaw.plugin.json` updated with the new slug, sorted.
|
||||
- `openclaw.plugin.json` updated with the new slug, sorted. Harvest must preserve
|
||||
the top-level OpenClaw-native plugin fields (`id`, `configSchema`, `contracts`)
|
||||
because OpenClaw validates those before it can install the package.
|
||||
- `--no-lint` bypasses the linter (after a manual editorial scrub).
|
||||
|
||||
Use the `skillpack-harvest` skill (its companion editorial workflow)
|
||||
|
||||
@@ -233,13 +233,14 @@ keep it or `git checkout` to throw it away. Nothing is committed for you.
|
||||
|
||||
**For a skill that ships with gbrain** (anything under the gbrain repo's own
|
||||
`skills/`): SkillOpt refuses to overwrite it by default and writes the winner to
|
||||
`skills/<name>/skillopt/best.md` instead, so an optimization pass can never
|
||||
silently mutate a skill other people depend on. Two ways to handle that:
|
||||
`skills/<name>/skillopt/proposed.md` instead (while keeping `best.md` as the
|
||||
optimizer's current-best pointer), so an optimization pass can never silently
|
||||
mutate a skill other people depend on. Two ways to handle that:
|
||||
|
||||
```bash
|
||||
# See the proposed improvement without touching SKILL.md (works for ANY skill):
|
||||
gbrain skillopt meeting-prep --split 1:1:1 --no-mutate
|
||||
# → writes skills/meeting-prep/skillopt/best.md (the proposed rewrite), prints its path. Copy what you want.
|
||||
# → writes skills/meeting-prep/skillopt/proposed.md, updates best.md, and prints the proposal path.
|
||||
|
||||
# Actually rewrite a bundled skill (explicit opt-in + an independent held-out set):
|
||||
gbrain skillopt brain-ops --split 1:1:1 --allow-mutate-bundled \
|
||||
|
||||
+2
-2
@@ -1565,8 +1565,8 @@ GBrain is designed to be installed and operated by an AI agent. The fastest path
|
||||
|
||||
If you don't already have an AI agent platform running, start with one of these. Both are designed to read GBrain's install protocol and execute it:
|
||||
|
||||
- **[OpenClaw](https://github.com/openclawagents/openclaw)** — deploy [AlphaClaw on Render](https://render.com/deploy?repo=https://github.com/chrysb/alphaclaw) (one click, 8GB+ RAM)
|
||||
- **[Hermes](https://github.com/openclawagents/hermes)** — deploy on [Railway](https://github.com/praveen-ks-2001/hermes-agent-template) (one click)
|
||||
- **[OpenClaw](https://github.com/openclaw/openclaw)** — deploy [AlphaClaw on Render](https://render.com/deploy?repo=https://github.com/chrysb/alphaclaw) (one click, 8GB+ RAM)
|
||||
- **[Hermes](https://github.com/NousResearch/hermes-agent)** — deploy on [Railway](https://github.com/praveen-ks-2001/hermes-agent-template) (one click)
|
||||
|
||||
Then paste this into your agent:
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"id": "gbrain-context-engine",
|
||||
"name": "gbrain",
|
||||
"version": "0.32.3.0",
|
||||
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
|
||||
|
||||
@@ -266,4 +266,5 @@ editorial pass.
|
||||
(e.g. `src/commands/<slug>.ts` if the host SKILL.md declares it
|
||||
in frontmatter)
|
||||
- gbrain's `openclaw.plugin.json` — adds the slug to `skills:`
|
||||
array, sorted alphabetically
|
||||
array, sorted alphabetically, without removing OpenClaw-native plugin fields
|
||||
like `id`, `configSchema`, or `contracts`
|
||||
|
||||
@@ -57,6 +57,8 @@ This mode guarantees:
|
||||
- `skills/manifest.json` lists every skill directory
|
||||
- `skills/RESOLVER.md` references every skill in the manifest
|
||||
- `openclaw.plugin.json` `skills[]` round-trips with both
|
||||
- `openclaw.plugin.json` keeps OpenClaw install-required native plugin fields
|
||||
(`id`, object `configSchema`, and `contracts.contextEngines` when applicable)
|
||||
- No MECE violations (duplicate triggers across skills)
|
||||
|
||||
### Phases
|
||||
@@ -72,7 +74,7 @@ This mode guarantees:
|
||||
### Automation
|
||||
|
||||
```bash
|
||||
bun test test/skills-conformance.test.ts test/resolver.test.ts
|
||||
bun test test/skills-conformance.test.ts test/resolver.test.ts test/openclaw-plugin-manifest.test.ts
|
||||
```
|
||||
|
||||
The CI-gated check is the package.json `test` script.
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
// AUTO-GENERATED — do not edit by hand.
|
||||
// Run `bun run scripts/build-admin-embedded.ts` to regenerate.
|
||||
// Source: admin/dist/ at 2026-07-22.
|
||||
// Source: admin/dist/ at 2026-05-27.
|
||||
//
|
||||
// Bun resolves the file: imports to a path that works at runtime even
|
||||
// inside a compiled binary (`bun build --compile`). The manifest maps
|
||||
// the request path the express handler sees to (resolved-path, mime).
|
||||
|
||||
// @ts-ignore — type: 'file' is Bun ESM, not in lib.d.ts
|
||||
import A_0_assets_index_BpDk4NI4_js from '../admin/dist/assets/index-BpDk4NI4.js' with { type: 'file' };
|
||||
import A_0_assets_index_CoGEje3__js from '../admin/dist/assets/index-CoGEje3-.js' with { type: 'file' };
|
||||
// @ts-ignore — type: 'file' is Bun ESM, not in lib.d.ts
|
||||
import A_1_assets_index_GxkWX7v3_css from '../admin/dist/assets/index-GxkWX7v3.css' with { type: 'file' };
|
||||
// @ts-ignore — type: 'file' is Bun ESM, not in lib.d.ts
|
||||
@@ -19,7 +19,7 @@ export interface AdminAsset {
|
||||
}
|
||||
|
||||
export const ADMIN_ASSETS: Record<string, AdminAsset> = {
|
||||
"/admin/assets/index-BpDk4NI4.js": { path: A_0_assets_index_BpDk4NI4_js as unknown as string, mime: "application/javascript; charset=utf-8" },
|
||||
"/admin/assets/index-CoGEje3-.js": { path: A_0_assets_index_CoGEje3__js as unknown as string, mime: "application/javascript; charset=utf-8" },
|
||||
"/admin/assets/index-GxkWX7v3.css": { path: A_1_assets_index_GxkWX7v3_css as unknown as string, mime: "text/css; charset=utf-8" },
|
||||
"/admin/index.html": { path: A_2_index_html as unknown as string, mime: "text/html; charset=utf-8" },
|
||||
};
|
||||
|
||||
+8
-1
@@ -54,7 +54,7 @@ export function bigintToStringReplacer(_key: string, value: unknown): unknown {
|
||||
}
|
||||
|
||||
// CLI-only commands that bypass the operation layer
|
||||
export const CLI_ONLY = new Set(['init', 'reinit-pglite', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'extract-conversation-facts', 'enrich', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'sources', 'mounts', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'providers', 'storage', 'repos', 'code-def', 'code-refs', 'reindex', 'reindex-code', 'reindex-frontmatter', 'code-callers', 'code-callees', 'reconcile-links', 'frontmatter', 'auth', 'friction', 'claw-test', 'book-mirror', 'takes', 'think', 'salience', 'anomalies', 'calibration', 'transcripts', 'models', 'remote', 'recall', 'forget', 'edges-backfill', 'cache', 'ze-switch', 'founder', 'brainstorm', 'lsd', 'schema', 'capture', 'onboard', 'conversation-parser', 'status', 'connect', 'skillopt', 'quarantine', 'self-upgrade', 'advisor', 'watch', 'reindex-search-vector']);
|
||||
export const CLI_ONLY = new Set(['init', 'reinit-pglite', 'upgrade', 'post-upgrade', 'check-update', 'integrations', 'publish', 'check-backlinks', 'lint', 'report', 'import', 'export', 'files', 'embed', 'serve', 'call', 'config', 'doctor', 'migrate', 'eval', 'sync', 'extract', 'extract-conversation-facts', 'enrich', 'features', 'autopilot', 'graph-query', 'jobs', 'agent', 'apply-migrations', 'skillpack-check', 'skillpack', 'resolvers', 'integrity', 'repair-jsonb', 'orphans', 'maintain', 'sources', 'mounts', 'dream', 'check-resolvable', 'routing-eval', 'skillify', 'smoke-test', 'providers', 'storage', 'repos', 'code-def', 'code-refs', 'reindex', 'reindex-code', 'reindex-frontmatter', 'code-callers', 'code-callees', 'reconcile-links', 'frontmatter', 'auth', 'friction', 'claw-test', 'book-mirror', 'takes', 'think', 'salience', 'anomalies', 'calibration', 'transcripts', 'models', 'remote', 'recall', 'forget', 'edges-backfill', 'cache', 'ze-switch', 'founder', 'brainstorm', 'lsd', 'schema', 'capture', 'onboard', 'conversation-parser', 'status', 'connect', 'skillopt', 'quarantine', 'self-upgrade', 'advisor', 'watch', 'reindex-search-vector']);
|
||||
// CLI-only commands whose handlers print their own --help text. These are
|
||||
// excluded from the generic short-circuit so detailed per-command and
|
||||
// per-subcommand usage stays reachable.
|
||||
@@ -78,6 +78,8 @@ const CLI_ONLY_SELF_HELP = new Set([
|
||||
'capture',
|
||||
// v0.42 self-upgrade ships its own usage (flags + the agent-skill story).
|
||||
'self-upgrade',
|
||||
// maintain (#3015) prints its own usage block (modes + not-auto-applied list).
|
||||
'maintain',
|
||||
// v0.43 (#2095): watch ships WATCH_HELP (flags + the stdin-turn protocol).
|
||||
'watch',
|
||||
// v0.37 fix wave (Lane D.4 + CDX2-12): sync's --no-embed flag was
|
||||
@@ -1757,6 +1759,11 @@ async function handleCliOnly(command: string, args: string[]) {
|
||||
await runOrphans(engine, args);
|
||||
break;
|
||||
}
|
||||
case 'maintain': {
|
||||
const { runMaintain } = await import('./commands/maintain.ts');
|
||||
await runMaintain(engine, args);
|
||||
break;
|
||||
}
|
||||
// v0.32.7 CJK wave — post-upgrade markdown re-chunk sweep.
|
||||
// v0.36 Phase 3 wave — `gbrain reindex --multimodal` re-embeds content_chunks
|
||||
// into the unified Voyage multimodal-3 column.
|
||||
|
||||
+1
-586
@@ -24,8 +24,6 @@ import { loadConfig, toEngineConfig } from '../core/config.ts';
|
||||
import { createEngine } from '../core/engine-factory.ts';
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import { sqlQueryForEngine, executeRawJsonb, type SqlQuery } from '../core/sql-query.ts';
|
||||
import { pgArray } from '../core/oauth-provider.ts';
|
||||
import { assertValidSourceId } from '../core/source-id.ts';
|
||||
|
||||
function hashToken(token: string): string {
|
||||
return createHash('sha256').update(token).digest('hex');
|
||||
@@ -167,100 +165,6 @@ async function list() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* `gbrain auth list-clients [--json]` — read surface for OAuth 2.1 clients.
|
||||
*
|
||||
* The existing `gbrain auth list` shows LEGACY bearer tokens from
|
||||
* `access_tokens`; this is the parallel for v0.26+ OAuth clients. Separate
|
||||
* commands rather than merged output because the two models have different
|
||||
* field sets (legacy: lifecycle dates; OAuth: scopes + source_id +
|
||||
* federated_read).
|
||||
*
|
||||
* Human output is card-style (multi-line per client) instead of a fixed-
|
||||
* width table — federated_read can hold many ids per client and a wide
|
||||
* single-line layout truncates / wraps badly on terminals < 200 cols.
|
||||
* JSON output uses a `schema_version: 1` envelope; additive only.
|
||||
*/
|
||||
async function listClients(args: string[]) {
|
||||
const json = args.includes('--json');
|
||||
const includeDeleted = args.includes('--include-deleted');
|
||||
await withConfiguredSql(async (sql) => {
|
||||
// Codex finding #2 (medium): default-hide soft-deleted clients so admin
|
||||
// soft-deletes are honored by the CLI surface. Opt-in via flag.
|
||||
const rows = includeDeleted
|
||||
? await sql`
|
||||
SELECT client_id, client_name, scope, source_id, federated_read,
|
||||
grant_types, created_at, deleted_at
|
||||
FROM oauth_clients
|
||||
ORDER BY client_name
|
||||
`
|
||||
: await sql`
|
||||
SELECT client_id, client_name, scope, source_id, federated_read,
|
||||
grant_types, created_at, deleted_at
|
||||
FROM oauth_clients
|
||||
WHERE deleted_at IS NULL
|
||||
ORDER BY client_name
|
||||
`;
|
||||
if (json) {
|
||||
const clients = rows.map((r) => ({
|
||||
client_id: String(r.client_id),
|
||||
client_name: String(r.client_name),
|
||||
scope: r.scope == null ? null : String(r.scope),
|
||||
source_id: r.source_id == null ? null : String(r.source_id),
|
||||
federated_read: Array.isArray(r.federated_read)
|
||||
? (r.federated_read as string[]).map(String)
|
||||
: [],
|
||||
grant_types: Array.isArray(r.grant_types)
|
||||
? (r.grant_types as string[]).map(String)
|
||||
: [],
|
||||
created_at:
|
||||
r.created_at instanceof Date
|
||||
? r.created_at.toISOString()
|
||||
: r.created_at == null
|
||||
? null
|
||||
: String(r.created_at),
|
||||
deleted_at:
|
||||
r.deleted_at instanceof Date
|
||||
? r.deleted_at.toISOString()
|
||||
: r.deleted_at == null
|
||||
? null
|
||||
: String(r.deleted_at),
|
||||
}));
|
||||
process.stdout.write(JSON.stringify({ schema_version: 1, clients }, null, 2) + '\n');
|
||||
return;
|
||||
}
|
||||
if (rows.length === 0) {
|
||||
console.log(
|
||||
includeDeleted
|
||||
? 'No OAuth clients found (including deleted). Register one: gbrain auth register-client <name>'
|
||||
: 'No active OAuth clients found. Register one: gbrain auth register-client <name>'
|
||||
+ '\n(Use --include-deleted to also show soft-deleted clients.)',
|
||||
);
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < rows.length; i++) {
|
||||
const r = rows[i];
|
||||
const fed = Array.isArray(r.federated_read)
|
||||
? (r.federated_read as string[]).map(String)
|
||||
: [];
|
||||
const grants = Array.isArray(r.grant_types)
|
||||
? (r.grant_types as string[]).map(String)
|
||||
: [];
|
||||
const deletedAt = r.deleted_at;
|
||||
const status = deletedAt == null
|
||||
? ''
|
||||
: ` [SOFT-DELETED ${deletedAt instanceof Date ? deletedAt.toISOString() : String(deletedAt)}]`;
|
||||
console.log(`${sanitizeForTerminal(String(r.client_name))}${status}`);
|
||||
console.log(` client_id: ${sanitizeForTerminal(String(r.client_id))}`);
|
||||
console.log(` scope: ${r.scope == null ? '(none)' : sanitizeForTerminal(String(r.scope))}`);
|
||||
console.log(` grant types: ${grants.length ? sanitizeForTerminal(grants.join(', ')) : '(none)'}`);
|
||||
console.log(` write source: ${r.source_id == null ? '(none)' : sanitizeForTerminal(String(r.source_id))}`);
|
||||
console.log(` federated: ${fed.length ? sanitizeForTerminal(fed.join(', ')) : '(empty)'}`);
|
||||
if (i < rows.length - 1) console.log('');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function revoke(name: string) {
|
||||
if (!name) { console.error('Usage: auth revoke <name>'); process.exit(1); }
|
||||
await withConfiguredSql(async (sql) => {
|
||||
@@ -397,475 +301,6 @@ async function test(url: string, token: string) {
|
||||
console.log(`\n🧠 Your brain is live! (${elapsed}s)`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip ANSI escapes + C0/C1 control characters from a string before
|
||||
* printing it to the operator's terminal. Defense for the
|
||||
* codex-flagged terminal-control-injection class: a client_name or
|
||||
* source_id registered via DCR with `\x1b[2J` (clear-screen) or
|
||||
* `\x1b]0;TITLE\x07` (OSC title-change) would poison
|
||||
* `gbrain auth list-clients` output otherwise.
|
||||
*
|
||||
* Replaces unsafe bytes with their `\xNN` hex escape so the operator
|
||||
* sees that something weird is in the field, instead of silent
|
||||
* mutilation. Tab and newline are preserved as-is so legitimate
|
||||
* multi-line values render.
|
||||
*/
|
||||
export function sanitizeForTerminal(s: string): string {
|
||||
// ALL C0/C1 controls + DEL get escaped. Codex re-review caught that
|
||||
// preserving `\n` lets a DCR-registered client_name spoof additional
|
||||
// human-output lines in list-clients (a real attack — newline in the
|
||||
// name visually adds a fake row to the operator's terminal). Tab is
|
||||
// also escaped for the same reason — field-separator spoofing.
|
||||
// C0: 0x00-0x1F. DEL: 0x7F. C1: 0x80-0x9F.
|
||||
return s.replace(/[\x00-\x1f\x7f-\x9f]/g, (ch) =>
|
||||
`\\x${ch.charCodeAt(0).toString(16).padStart(2, '0')}`,
|
||||
);
|
||||
}
|
||||
|
||||
export interface ResolvedClient {
|
||||
client_id: string;
|
||||
client_name: string;
|
||||
source_id: string | null;
|
||||
federated_read: string[];
|
||||
deleted_at: Date | string | null;
|
||||
}
|
||||
|
||||
export type FederatedReadOutcome =
|
||||
| { kind: 'noop'; reason: 'already-granted' | 'not-present' | 'same-list'; client: ResolvedClient; current: string[] }
|
||||
| { kind: 'updated'; client: ResolvedClient; before: string[]; after: string[] };
|
||||
|
||||
/**
|
||||
* Resolve an OAuth client by client_id (exact) or client_name (unique).
|
||||
* Errors on no-match and on ambiguous client_name (>1 row). client_id
|
||||
* takes precedence — if a long hash is passed and matches, returns
|
||||
* immediately without ever querying by name.
|
||||
*
|
||||
* Legacy bearer tokens in `access_tokens` are NOT searched. Federated read
|
||||
* scope is an OAuth-client concept (oauth_clients.federated_read column);
|
||||
* legacy bearers have no source scope.
|
||||
*/
|
||||
/**
|
||||
* Resolve an OAuth client. Codex finding #2 (medium): default-hide
|
||||
* soft-deleted clients so admin-soft-deleted rows aren't mutated by the
|
||||
* CLI. The `includeDeleted` opt is reserved for future read-side surfaces;
|
||||
* grant/revoke/set ALWAYS filter active rows only.
|
||||
*/
|
||||
export async function resolveClient(
|
||||
sql: SqlQuery,
|
||||
nameOrId: string,
|
||||
opts: { includeDeleted?: boolean } = {},
|
||||
): Promise<ResolvedClient> {
|
||||
const allowDeleted = opts.includeDeleted === true;
|
||||
const byId = allowDeleted
|
||||
? await sql`
|
||||
SELECT client_id, client_name, source_id, federated_read, deleted_at
|
||||
FROM oauth_clients WHERE client_id = ${nameOrId} LIMIT 1
|
||||
`
|
||||
: await sql`
|
||||
SELECT client_id, client_name, source_id, federated_read, deleted_at
|
||||
FROM oauth_clients WHERE client_id = ${nameOrId} AND deleted_at IS NULL LIMIT 1
|
||||
`;
|
||||
if (byId.length === 1) return normalizeClientRow(byId[0]);
|
||||
const byName = allowDeleted
|
||||
? await sql`
|
||||
SELECT client_id, client_name, source_id, federated_read, deleted_at
|
||||
FROM oauth_clients WHERE client_name = ${nameOrId}
|
||||
`
|
||||
: await sql`
|
||||
SELECT client_id, client_name, source_id, federated_read, deleted_at
|
||||
FROM oauth_clients WHERE client_name = ${nameOrId} AND deleted_at IS NULL
|
||||
`;
|
||||
if (byName.length === 0) {
|
||||
throw new Error(
|
||||
`No active OAuth client found with name or id "${nameOrId}". ` +
|
||||
`Run \`gbrain auth register-client <name>\` to create one, ` +
|
||||
`or \`gbrain auth list-clients\` to see what exists. ` +
|
||||
`(Soft-deleted clients are hidden by default.)`,
|
||||
);
|
||||
}
|
||||
if (byName.length > 1) {
|
||||
const ids = byName.map((r) => ` ${String(r.client_id)}`).join('\n');
|
||||
throw new Error(
|
||||
`Multiple active OAuth clients named "${nameOrId}". Pass the full client_id instead:\n${ids}`,
|
||||
);
|
||||
}
|
||||
return normalizeClientRow(byName[0]);
|
||||
}
|
||||
|
||||
function normalizeClientRow(row: Record<string, unknown>): ResolvedClient {
|
||||
const fed = row.federated_read;
|
||||
return {
|
||||
client_id: String(row.client_id),
|
||||
client_name: String(row.client_name),
|
||||
source_id: row.source_id == null ? null : String(row.source_id),
|
||||
federated_read: Array.isArray(fed) ? (fed as string[]).map(String) : [],
|
||||
deleted_at: row.deleted_at == null
|
||||
? null
|
||||
: (row.deleted_at as Date | string),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the source_id shape AND DB existence. Codex finding #3 (medium):
|
||||
* a manually-INSERTed source row with weird chars (e.g. comma, quote)
|
||||
* would otherwise land in oauth_clients.federated_read as a never-deletable
|
||||
* malformed entry. Fail at the boundary before the existence query so
|
||||
* malformed input gets the validator's hint, not a "does not exist" hint
|
||||
* pointing at a non-creatable id.
|
||||
*/
|
||||
export async function assertSourceExists(sql: SqlQuery, sourceId: string): Promise<void> {
|
||||
assertValidSourceId(sourceId);
|
||||
const rows = await sql`SELECT id FROM sources WHERE id = ${sourceId} LIMIT 1`;
|
||||
if (rows.length === 0) {
|
||||
throw new Error(
|
||||
`Source "${sourceId}" does not exist. Run \`gbrain sources list\` to see registered sources, ` +
|
||||
`or \`gbrain sources add ${sourceId}\` to create it.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomic append: array_append + NOT-ANY guard so the row-lock fully
|
||||
* serializes concurrent grant/revoke against the same client. Codex
|
||||
* finding #1 (HIGH): the previous read-modify-write shape allowed a
|
||||
* concurrent revoke to be silently UNDONE by a racing grant.
|
||||
*
|
||||
* Returns the post-write federated_read array, or null when no rows
|
||||
* matched (already-granted, soft-deleted, or missing client). Callers
|
||||
* disambiguate via prior resolveClient + includes() check.
|
||||
*
|
||||
* `WHERE deleted_at IS NULL` is part of the atomic guard so a client
|
||||
* soft-deleted between resolveClient and the UPDATE can't be mutated.
|
||||
*/
|
||||
async function appendFederatedReadAtomic(
|
||||
sql: SqlQuery,
|
||||
clientId: string,
|
||||
sourceId: string,
|
||||
): Promise<string[] | null> {
|
||||
const rows = await sql`
|
||||
UPDATE oauth_clients
|
||||
SET federated_read = array_append(federated_read, ${sourceId})
|
||||
WHERE client_id = ${clientId}
|
||||
AND deleted_at IS NULL
|
||||
AND NOT (${sourceId} = ANY(federated_read))
|
||||
RETURNING federated_read
|
||||
`;
|
||||
if (rows.length === 0) return null;
|
||||
const fed = rows[0].federated_read;
|
||||
return Array.isArray(fed) ? (fed as string[]).map(String) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomic remove: array_remove + ANY guard. Same race-correctness story
|
||||
* as appendFederatedReadAtomic. Returns post-write array or null.
|
||||
*/
|
||||
async function removeFederatedReadAtomic(
|
||||
sql: SqlQuery,
|
||||
clientId: string,
|
||||
sourceId: string,
|
||||
): Promise<string[] | null> {
|
||||
const rows = await sql`
|
||||
UPDATE oauth_clients
|
||||
SET federated_read = array_remove(federated_read, ${sourceId})
|
||||
WHERE client_id = ${clientId}
|
||||
AND deleted_at IS NULL
|
||||
AND ${sourceId} = ANY(federated_read)
|
||||
RETURNING federated_read
|
||||
`;
|
||||
if (rows.length === 0) return null;
|
||||
const fed = rows[0].federated_read;
|
||||
return Array.isArray(fed) ? (fed as string[]).map(String) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Wholesale array overwrite for `set-federated-read`. Honors the
|
||||
* deleted_at filter. Last-writer-wins semantics under concurrent
|
||||
* `set` calls is acceptable — the user is asserting "this exact list"
|
||||
* intent; concurrent set+set just means whichever ran second wins.
|
||||
* Concurrent set+grant or set+revoke is also last-writer-wins, which
|
||||
* is the documented contract for `set`.
|
||||
*/
|
||||
async function replaceFederatedReadAtomic(
|
||||
sql: SqlQuery,
|
||||
clientId: string,
|
||||
next: string[],
|
||||
): Promise<string[] | null> {
|
||||
// TEXT[] binding via pgArray() string-literal escaping (see helper
|
||||
// for the security note). Our narrow SqlQuery surface
|
||||
// (src/core/sql-query.ts) doesn't bind JS arrays directly.
|
||||
const literal = pgArray(next);
|
||||
const rows = await sql`
|
||||
UPDATE oauth_clients
|
||||
SET federated_read = ${literal}
|
||||
WHERE client_id = ${clientId}
|
||||
AND deleted_at IS NULL
|
||||
RETURNING federated_read
|
||||
`;
|
||||
if (rows.length === 0) return null;
|
||||
const fed = rows[0].federated_read;
|
||||
return Array.isArray(fed) ? (fed as string[]).map(String) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure helper: dedupe a comma-separated source-id list while preserving
|
||||
* insertion order. Empty input → empty array. Exported so the CLI parser
|
||||
* and tests share one normalizer.
|
||||
*/
|
||||
export function parseSourceCsv(csv: string): string[] {
|
||||
const requested = csv.split(',').map((s) => s.trim()).filter(Boolean);
|
||||
const seen = new Set<string>();
|
||||
const out: string[] = [];
|
||||
for (const s of requested) {
|
||||
if (!seen.has(s)) {
|
||||
seen.add(s);
|
||||
out.push(s);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface FederatedReadOpts {
|
||||
/** When true, compute the outcome but skip the persisting UPDATE. */
|
||||
dryRun?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Core: append a source to the client's federated_read.
|
||||
*
|
||||
* Atomicity contract (Codex finding #1, HIGH):
|
||||
* The actual write goes through `appendFederatedReadAtomic` which
|
||||
* serializes at the row-lock so concurrent grant/revoke against the
|
||||
* same client cannot lose updates. The race vector that previously
|
||||
* silently restored revoked access is closed: under two operators
|
||||
* racing `revoke-read sensitive` + `grant-read harmless`, postgres
|
||||
* serializes the two UPDATEs and BOTH ops apply (sensitive removed,
|
||||
* harmless added), instead of one clobbering the other.
|
||||
*
|
||||
* The reported `before` is the snapshot at resolveClient time, which
|
||||
* may be stale relative to a concurrent racer. The `after` reflects
|
||||
* the post-UPDATE state from RETURNING (always fresh).
|
||||
*/
|
||||
export async function grantReadCore(
|
||||
sql: SqlQuery,
|
||||
nameOrId: string,
|
||||
sourceId: string,
|
||||
opts: FederatedReadOpts = {},
|
||||
): Promise<FederatedReadOutcome> {
|
||||
const client = await resolveClient(sql, nameOrId);
|
||||
await assertSourceExists(sql, sourceId);
|
||||
if (client.federated_read.includes(sourceId)) {
|
||||
return { kind: 'noop', reason: 'already-granted', client, current: client.federated_read };
|
||||
}
|
||||
if (opts.dryRun) {
|
||||
// Compute the would-be result without touching the row. Last-known
|
||||
// snapshot is best-effort under concurrent writes.
|
||||
const projected = [...client.federated_read, sourceId];
|
||||
return { kind: 'updated', client, before: client.federated_read, after: projected };
|
||||
}
|
||||
const after = await appendFederatedReadAtomic(sql, client.client_id, sourceId);
|
||||
if (after === null) {
|
||||
// Two equivalent failure modes: (a) racing grant-read already added
|
||||
// the source and the NOT-ANY guard suppressed our UPDATE, or
|
||||
// (b) the client was soft-deleted between resolveClient and UPDATE.
|
||||
// (a) is the more common path. Re-resolve to confirm + report.
|
||||
const reresolved = await resolveClient(sql, client.client_id, { includeDeleted: true });
|
||||
if (reresolved.deleted_at != null) {
|
||||
throw new Error(`Client "${client.client_name}" was soft-deleted before write could land.`);
|
||||
}
|
||||
return { kind: 'noop', reason: 'already-granted', client: reresolved, current: reresolved.federated_read };
|
||||
}
|
||||
return { kind: 'updated', client, before: client.federated_read, after };
|
||||
}
|
||||
|
||||
/**
|
||||
* Core: remove a source from the client's federated_read. Atomic via
|
||||
* array_remove + ANY-guard. Same race-correctness rationale as
|
||||
* grantReadCore — concurrent ops serialize at the row lock.
|
||||
*/
|
||||
export async function revokeReadCore(
|
||||
sql: SqlQuery,
|
||||
nameOrId: string,
|
||||
sourceId: string,
|
||||
opts: FederatedReadOpts = {},
|
||||
): Promise<FederatedReadOutcome> {
|
||||
const client = await resolveClient(sql, nameOrId);
|
||||
if (!client.federated_read.includes(sourceId)) {
|
||||
return { kind: 'noop', reason: 'not-present', client, current: client.federated_read };
|
||||
}
|
||||
if (opts.dryRun) {
|
||||
const projected = client.federated_read.filter((s) => s !== sourceId);
|
||||
return { kind: 'updated', client, before: client.federated_read, after: projected };
|
||||
}
|
||||
const after = await removeFederatedReadAtomic(sql, client.client_id, sourceId);
|
||||
if (after === null) {
|
||||
// Same disambiguation as grant: either a concurrent revoke already
|
||||
// removed the source (most common) or the client was soft-deleted.
|
||||
const reresolved = await resolveClient(sql, client.client_id, { includeDeleted: true });
|
||||
if (reresolved.deleted_at != null) {
|
||||
throw new Error(`Client "${client.client_name}" was soft-deleted before write could land.`);
|
||||
}
|
||||
return { kind: 'noop', reason: 'not-present', client: reresolved, current: reresolved.federated_read };
|
||||
}
|
||||
return { kind: 'updated', client, before: client.federated_read, after };
|
||||
}
|
||||
|
||||
/**
|
||||
* Core: replace the whole federated_read list. Idempotent on same list.
|
||||
*
|
||||
* Race semantics: wholesale-overwrite + deleted_at guard. Concurrent
|
||||
* set+set is last-writer-wins (documented contract for `set` — the
|
||||
* operator is asserting the exact list). Concurrent set+grant or
|
||||
* set+revoke is also last-writer-wins. If a strict-merge semantics is
|
||||
* needed, use grant-read / revoke-read individually.
|
||||
*/
|
||||
export async function setFederatedReadCore(
|
||||
sql: SqlQuery,
|
||||
nameOrId: string,
|
||||
sourceCsv: string,
|
||||
opts: FederatedReadOpts = {},
|
||||
): Promise<FederatedReadOutcome> {
|
||||
const next = parseSourceCsv(sourceCsv);
|
||||
const client = await resolveClient(sql, nameOrId);
|
||||
for (const s of next) {
|
||||
await assertSourceExists(sql, s);
|
||||
}
|
||||
const prev = client.federated_read;
|
||||
const same = prev.length === next.length && prev.every((v, i) => v === next[i]);
|
||||
if (same) {
|
||||
return { kind: 'noop', reason: 'same-list', client, current: prev };
|
||||
}
|
||||
if (opts.dryRun) {
|
||||
return { kind: 'updated', client, before: prev, after: next };
|
||||
}
|
||||
const after = await replaceFederatedReadAtomic(sql, client.client_id, next);
|
||||
if (after === null) {
|
||||
throw new Error(`Client "${client.client_name}" was soft-deleted before write could land.`);
|
||||
}
|
||||
return { kind: 'updated', client, before: prev, after };
|
||||
}
|
||||
|
||||
function printOutcome(
|
||||
verb: 'grant' | 'revoke' | 'set',
|
||||
sourceArg: string,
|
||||
outcome: FederatedReadOutcome,
|
||||
dryRun: boolean,
|
||||
): void {
|
||||
// Terminal-injection defense (Codex finding #5, low): a client_name
|
||||
// registered via DCR with ANSI escapes or control chars would
|
||||
// otherwise poison this output. Sanitize ALL strings that round-trip
|
||||
// from the DB before printing.
|
||||
const s = sanitizeForTerminal;
|
||||
const prefix = dryRun ? '[dry-run] ' : '';
|
||||
if (outcome.kind === 'noop') {
|
||||
const name = s(outcome.client.client_name);
|
||||
if (outcome.reason === 'already-granted') {
|
||||
console.log(`${prefix}No change: "${name}" already reads "${s(sourceArg)}".`);
|
||||
} else if (outcome.reason === 'not-present') {
|
||||
console.log(`${prefix}No change: "${name}" did not read "${s(sourceArg)}".`);
|
||||
} else {
|
||||
console.log(`${prefix}No change: "${name}" federated_read already matches.`);
|
||||
}
|
||||
console.log(` federated_read: ${outcome.current.map(s).join(', ') || '(empty)'}`);
|
||||
return;
|
||||
}
|
||||
const { client, before, after } = outcome;
|
||||
const name = s(client.client_name);
|
||||
const wouldOrDid = dryRun ? 'Would' : 'Did';
|
||||
if (verb === 'grant') {
|
||||
console.log(`${prefix}${wouldOrDid} grant: "${name}" can now read "${s(sourceArg)}".`);
|
||||
console.log(` federated_read: ${after.map(s).join(', ')}`);
|
||||
} else if (verb === 'revoke') {
|
||||
console.log(`${prefix}${wouldOrDid} revoke: "${name}" no longer reads "${s(sourceArg)}".`);
|
||||
console.log(` federated_read: ${after.map(s).join(', ') || '(empty — client has no federated reads)'}`);
|
||||
} else {
|
||||
console.log(`${prefix}${wouldOrDid} update "${name}" federated_read:`);
|
||||
console.log(` before: ${before.map(s).join(', ') || '(empty)'}`);
|
||||
console.log(` after: ${after.map(s).join(', ') || '(empty)'}`);
|
||||
}
|
||||
if (after.length === 0) {
|
||||
console.log(
|
||||
'Warning: client now reads no sources via federation. Queries through this ' +
|
||||
'client will only see content scoped explicitly via its write source.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip `--dry-run` from a positional-arg list. Returns the filtered list
|
||||
* plus the flag value. Kept positional-tolerant — the existing
|
||||
* `auth grant-read alice source` shape MUST keep working, AND
|
||||
* `auth grant-read alice source --dry-run` AND `auth grant-read --dry-run alice source`.
|
||||
*/
|
||||
export function extractDryRun(args: string[]): { dryRun: boolean; rest: string[] } {
|
||||
let dryRun = false;
|
||||
const rest: string[] = [];
|
||||
for (const a of args) {
|
||||
if (a === '--dry-run') {
|
||||
dryRun = true;
|
||||
continue;
|
||||
}
|
||||
rest.push(a);
|
||||
}
|
||||
return { dryRun, rest };
|
||||
}
|
||||
|
||||
async function grantRead(args: string[]): Promise<void> {
|
||||
const { dryRun, rest } = extractDryRun(args);
|
||||
const [nameOrId, sourceId] = rest;
|
||||
if (!nameOrId || !sourceId) {
|
||||
console.error('Usage: gbrain auth grant-read <client-name-or-id> <source-id> [--dry-run]');
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
await withConfiguredSql(async (sql) => {
|
||||
const outcome = await grantReadCore(sql, nameOrId, sourceId, { dryRun });
|
||||
printOutcome('grant', sourceId, outcome, dryRun);
|
||||
});
|
||||
} catch (e: any) {
|
||||
console.error('Error:', e.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeRead(args: string[]): Promise<void> {
|
||||
const { dryRun, rest } = extractDryRun(args);
|
||||
const [nameOrId, sourceId] = rest;
|
||||
if (!nameOrId || !sourceId) {
|
||||
console.error('Usage: gbrain auth revoke-read <client-name-or-id> <source-id> [--dry-run]');
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
await withConfiguredSql(async (sql) => {
|
||||
const outcome = await revokeReadCore(sql, nameOrId, sourceId, { dryRun });
|
||||
printOutcome('revoke', sourceId, outcome, dryRun);
|
||||
});
|
||||
} catch (e: any) {
|
||||
console.error('Error:', e.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function setFederatedRead(args: string[]): Promise<void> {
|
||||
const { dryRun, rest } = extractDryRun(args);
|
||||
const [nameOrId, sourceCsv] = rest;
|
||||
if (!nameOrId || sourceCsv === undefined) {
|
||||
console.error(
|
||||
'Usage: gbrain auth set-federated-read <client-name-or-id> <source-id1,source-id2,...> [--dry-run]',
|
||||
);
|
||||
console.error('Pass an empty string ("") to clear all federated reads.');
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
await withConfiguredSql(async (sql) => {
|
||||
const outcome = await setFederatedReadCore(sql, nameOrId, sourceCsv, { dryRun });
|
||||
printOutcome('set', sourceCsv, outcome, dryRun);
|
||||
});
|
||||
} catch (e: any) {
|
||||
console.error('Error:', e.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeClient(clientId: string) {
|
||||
if (!clientId) {
|
||||
console.error('Usage: auth revoke-client <client_id>');
|
||||
@@ -884,7 +319,7 @@ async function revokeClient(clientId: string) {
|
||||
console.error(`No client found with id "${clientId}"`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`OAuth client revoked: "${sanitizeForTerminal(String(rows[0].client_name))}" (${clientId})`);
|
||||
console.log(`OAuth client revoked: "${rows[0].client_name}" (${clientId})`);
|
||||
console.log('Tokens and authorization codes purged via cascade.');
|
||||
});
|
||||
} catch (e: any) {
|
||||
@@ -1005,15 +440,6 @@ export function parseRegisterClientArgs(args: string[]): RegisterClientArgs {
|
||||
if (!grantTypesSet && out.redirectUris.length > 0) {
|
||||
out.grantTypes = ['authorization_code', 'refresh_token'];
|
||||
}
|
||||
// Codex re-review (medium): validate source_id shape at the CLI boundary
|
||||
// so register-client can't seed malformed entries into source_id /
|
||||
// federated_read that subsequent grant/revoke/set commands can't manage.
|
||||
assertValidSourceId(out.sourceId);
|
||||
if (out.federatedRead) {
|
||||
for (const s of out.federatedRead) {
|
||||
assertValidSourceId(s);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -1131,10 +557,6 @@ export async function runAuth(args: string[]): Promise<void> {
|
||||
}
|
||||
case 'register-client': await registerClient(rest[0], rest.slice(1)); return;
|
||||
case 'revoke-client': await revokeClient(rest[0]); return;
|
||||
case 'list-clients': await listClients(rest); return;
|
||||
case 'grant-read': await grantRead(rest); return;
|
||||
case 'revoke-read': await revokeRead(rest); return;
|
||||
case 'set-federated-read': await setFederatedRead(rest); return;
|
||||
case 'test': {
|
||||
const tokenIdx = rest.indexOf('--token');
|
||||
const url = rest.find(a => !a.startsWith('--') && a !== rest[tokenIdx + 1]);
|
||||
@@ -1172,13 +594,6 @@ Usage:
|
||||
--bound-max-concurrent <n> Bound submit_agent concurrency (default: 1)
|
||||
--budget-usd-per-day <usd> Bound submit_agent daily spend cap
|
||||
gbrain auth revoke-client <client_id> Hard-delete an OAuth 2.1 client (cascades to tokens + codes)
|
||||
gbrain auth list-clients [--json] List OAuth 2.1 clients with scope + write source + federated_read.
|
||||
gbrain auth grant-read <name|client_id> <source-id> [--dry-run]
|
||||
Add a source to the client's federated_read list (idempotent).
|
||||
gbrain auth revoke-read <name|client_id> <source-id> [--dry-run]
|
||||
Remove a source from the client's federated_read list (idempotent).
|
||||
gbrain auth set-federated-read <name|client_id> "<id1,id2,...>" [--dry-run]
|
||||
Replace the client's whole federated_read list. Pass "" to clear.
|
||||
gbrain auth test <url> --token <token> Smoke-test a remote MCP server
|
||||
`);
|
||||
}
|
||||
|
||||
@@ -37,9 +37,19 @@ export async function findCodeDef(
|
||||
// trigger) are first-class definitions in the SQL sense. The chunker's
|
||||
// normalizeSymbolType maps create_table → 'table' etc, so adding the SQL
|
||||
// kinds here is what makes `gbrain code-def users` work against SQL.
|
||||
// Method-level + member definitions. normalizeSymbolType only canonicalizes
|
||||
// some node types; the rest fall through `type.replace(/_/g, ' ')`, so
|
||||
// tree-sitter's method_declaration → 'method declaration', struct_specifier →
|
||||
// 'struct specifier', protocol_declaration → 'protocol declaration', etc.
|
||||
// Without these, code-def is blind to every method, constructor, field, C
|
||||
// struct, and Swift protocol — which is most of an OO codebase. The plain
|
||||
// 'struct' entry above never matched for the same reason (C emits the
|
||||
// 'struct specifier' fallback form).
|
||||
const DEF_TYPES = [
|
||||
'function', 'class', 'interface', 'type', 'enum', 'struct', 'trait', 'module', 'contract',
|
||||
'table', 'view', 'index', 'procedure', 'schema', 'database', 'trigger',
|
||||
'method declaration', 'method definition', 'constructor declaration',
|
||||
'field declaration', 'field definition', 'struct specifier', 'protocol declaration',
|
||||
];
|
||||
const params: unknown[] = [symbol, limit];
|
||||
let whereLang = '';
|
||||
|
||||
+47
-10
@@ -1623,7 +1623,7 @@ export async function computeWedgedQueueCheck(engine: BrainEngine): Promise<Chec
|
||||
FROM minion_jobs
|
||||
GROUP BY queue`,
|
||||
);
|
||||
const wedged: string[] = [];
|
||||
const wedged: Array<{ queue: string; label: string }> = [];
|
||||
for (const r of rows) {
|
||||
const activeHealthy = Number(r.active_healthy ?? 0);
|
||||
const waiting = Number(r.waiting ?? 0);
|
||||
@@ -1631,21 +1631,59 @@ export async function computeWedgedQueueCheck(engine: BrainEngine): Promise<Chec
|
||||
// Conservative: only flag stale-after-progress (non-null mins past
|
||||
// threshold). The null-completions case is the supervisor's job.
|
||||
if (activeHealthy === 0 && waiting > 0 && mins !== null && mins > thresholdMin) {
|
||||
wedged.push(`'${r.queue}' (${waiting} waiting, 0 active, ${Math.round(mins)}m since last completion)`);
|
||||
wedged.push({
|
||||
queue: r.queue,
|
||||
label: `'${r.queue}' (${waiting} waiting, 0 active, ${Math.round(mins)}m since last completion)`,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (wedged.length === 0) {
|
||||
return { name: 'wedged_queue', status: 'ok', message: 'No wedged queues' };
|
||||
}
|
||||
return {
|
||||
name: 'wedged_queue',
|
||||
status: 'fail',
|
||||
message:
|
||||
`Wedged queue(s) — worker alive but not claiming work: ${wedged.join('; ')}. ` +
|
||||
// #3063: split the diagnosis on worker liveness. The wedged-pool message
|
||||
// ("worker alive but not claiming work → restart to rebuild the DB pool")
|
||||
// only applies when a supervisor actually holds a live singleton lock.
|
||||
// With no live holder the worker is simply not running — telling the
|
||||
// operator to blame the DB pool sends them down the wrong path.
|
||||
const alive: string[] = [];
|
||||
const noWorker: string[] = [];
|
||||
for (const w of wedged) {
|
||||
let hasLiveWorker = false;
|
||||
try {
|
||||
const { supervisorLockId } = await import('../core/minions/supervisor.ts');
|
||||
const lockRows = await engine.executeRaw<{ live: boolean }>(
|
||||
`SELECT (ttl_expires_at > now()) AS live FROM gbrain_cycle_locks WHERE id = $1`,
|
||||
[supervisorLockId(w.queue)],
|
||||
);
|
||||
hasLiveWorker = lockRows.length > 0 && lockRows[0].live === true;
|
||||
} catch {
|
||||
// Lock table unreadable → can't prove absence; keep the
|
||||
// conservative wedged-pool message.
|
||||
hasLiveWorker = true;
|
||||
}
|
||||
(hasLiveWorker ? alive : noWorker).push(w.label);
|
||||
}
|
||||
const parts: string[] = [];
|
||||
if (noWorker.length > 0) {
|
||||
parts.push(
|
||||
`Queue(s) with waiting jobs and no worker running: ${noWorker.join('; ')}. ` +
|
||||
`Start the worker: \`gbrain jobs supervisor start\` ` +
|
||||
`(or restart the autopilot unit if installed).`,
|
||||
);
|
||||
}
|
||||
if (alive.length > 0) {
|
||||
parts.push(
|
||||
`Wedged queue(s) — worker alive but not claiming work: ${alive.join('; ')}. ` +
|
||||
`Restart the worker so it rebuilds a fresh DB pool: ` +
|
||||
`\`gbrain jobs supervisor stop && gbrain jobs supervisor start\`, ` +
|
||||
`then \`gbrain jobs retry <id>\` on any dead-lettered jobs.`,
|
||||
details: { wedged_queues: wedged.length, threshold_minutes: thresholdMin },
|
||||
);
|
||||
}
|
||||
return {
|
||||
name: 'wedged_queue',
|
||||
status: 'fail',
|
||||
message: parts.join(' '),
|
||||
details: { wedged_queues: wedged.length, no_worker_queues: noWorker.length, threshold_minutes: thresholdMin },
|
||||
};
|
||||
} catch (e) {
|
||||
// Pre-migration brains / transient errors: advisory check stays ok.
|
||||
@@ -4963,8 +5001,7 @@ export async function buildChecks(
|
||||
message:
|
||||
`${unmatched}/${sample.length} conversation pages (${unmatchedPct.toFixed(1)}%) match NO built-in pattern. ` +
|
||||
`Breakdown: ${breakdown}. ` +
|
||||
`Investigate: gbrain conversation-parser scan <slug> | ` +
|
||||
`Enable LLM fallback (opt-in): gbrain config set conversation_parser.llm_fallback_enabled true`,
|
||||
`Investigate: gbrain conversation-parser scan <slug>`,
|
||||
});
|
||||
} else {
|
||||
checks.push({
|
||||
|
||||
+34
-4
@@ -581,7 +581,7 @@ async function embedPage(
|
||||
for (let j = 0; j < toEmbed.length; j++) {
|
||||
embeddingMap.set(toEmbed[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
const updated: ChunkInput[] = chunks.map(c => ({
|
||||
const updated: ChunkInput[] = chunks.map(c => preserveCodeMetadata(c, {
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
@@ -605,6 +605,31 @@ async function embedPage(
|
||||
slog(`${slug}: embedded ${toEmbed.length} chunks`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Carry code-chunk metadata (language, symbol_name, symbol_type, line range,
|
||||
* parent scope, doc comment, qualified name) from a loaded Chunk back into a
|
||||
* ChunkInput destined for upsertChunks.
|
||||
*
|
||||
* Issue #769: every re-embed used to strip these fields, and upsertChunks
|
||||
* overwrites (does not COALESCE) the metadata columns from EXCLUDED, so
|
||||
* each pass clobbered code-def's primary index to NULL. Pulling the
|
||||
* preservation into one helper keeps the three re-embed call sites
|
||||
* (embedPage, embedAll non-stale, embedAllStale) in lock-step.
|
||||
*/
|
||||
function preserveCodeMetadata(loaded: any, base: ChunkInput): ChunkInput {
|
||||
return {
|
||||
...base,
|
||||
language: loaded.language ?? undefined,
|
||||
symbol_name: loaded.symbol_name ?? undefined,
|
||||
symbol_type: loaded.symbol_type ?? undefined,
|
||||
start_line: loaded.start_line ?? undefined,
|
||||
end_line: loaded.end_line ?? undefined,
|
||||
parent_symbol_path: loaded.parent_symbol_path ?? undefined,
|
||||
doc_comment: loaded.doc_comment ?? undefined,
|
||||
symbol_name_qualified: loaded.symbol_name_qualified ?? undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function embedAll(
|
||||
engine: BrainEngine,
|
||||
staleOnly: boolean,
|
||||
@@ -717,8 +742,10 @@ async function embedAll(
|
||||
for (let j = 0; j < toEmbed.length; j++) {
|
||||
embeddingMap.set(toEmbed[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
// Preserve ALL chunks, only update embeddings for stale ones
|
||||
const updated: ChunkInput[] = chunks.map(c => ({
|
||||
// Preserve ALL chunks, only update embeddings for stale ones.
|
||||
// preserveCodeMetadata threads code-chunk metadata (#769) so re-embed
|
||||
// doesn't clobber language/symbol_name/symbol_type to NULL.
|
||||
const updated: ChunkInput[] = chunks.map(c => preserveCodeMetadata(c, {
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
@@ -1012,7 +1039,10 @@ async function embedAllStale(
|
||||
for (let j = 0; j < stale.length; j++) {
|
||||
staleIdxToEmbedding.set(stale[j].chunk_index, embeddings[j]);
|
||||
}
|
||||
const merged: ChunkInput[] = existing.map(c => ({
|
||||
// preserveCodeMetadata threads code-chunk metadata (#769) so the
|
||||
// autopilot --stale path doesn't clobber language/symbol_name/etc
|
||||
// to NULL on every cycle.
|
||||
const merged: ChunkInput[] = existing.map(c => preserveCodeMetadata(c, {
|
||||
chunk_index: c.chunk_index,
|
||||
chunk_text: c.chunk_text,
|
||||
chunk_source: c.chunk_source,
|
||||
|
||||
+13
-2
@@ -1651,7 +1651,7 @@ async function extractTimelineFromDB(
|
||||
* make re-extraction idempotent). EVERY processed page is stamped, including
|
||||
* zero-link pages — they WERE processed.
|
||||
*/
|
||||
async function extractStaleFromDB(
|
||||
export async function extractStaleFromDB(
|
||||
engine: BrainEngine,
|
||||
opts: {
|
||||
dryRun: boolean;
|
||||
@@ -1743,7 +1743,18 @@ async function extractStaleFromDB(
|
||||
// `page.updated_at.toISOString()` — the JS Date is ms-truncated, so the
|
||||
// µs-precision DB updated_at stayed strictly greater and the page never
|
||||
// cleared on Postgres. Stamping the exact value makes them equal.
|
||||
processedRefs.push({ slug: page.slug, source_id: page.source_id, extractedAt: page.updated_at_iso });
|
||||
//
|
||||
// BUT the stamp must also clear the version-staleness clause
|
||||
// (`links_extracted_at < versionTs`). A page whose updated_at predates
|
||||
// versionTs would otherwise be stamped below the threshold and read as
|
||||
// stale forever — a permanent re-extract loop that never clears the lag.
|
||||
// GREATEST(updated_at, versionTs) preserves the race semantics (a real
|
||||
// future edit advances updated_at > versionTs >= stamp → re-extracts)
|
||||
// while lifting old pages to the threshold so they clear.
|
||||
const stampIso = page.updated_at.getTime() >= Date.parse(versionTs)
|
||||
? page.updated_at_iso
|
||||
: versionTs;
|
||||
processedRefs.push({ slug: page.slug, source_id: page.source_id, extractedAt: stampIso });
|
||||
}
|
||||
|
||||
// Flush NON-swallowing (CDX-4): a throw here propagates out of the sweep so
|
||||
|
||||
@@ -98,8 +98,17 @@ export function findBareTweetHits(compiledTruth: string, slug: string): BareTwee
|
||||
}
|
||||
// If the line already contains a tweet URL, it's cited — skip
|
||||
if (URL_NEARBY_RE.test(line)) continue;
|
||||
// If the line carries an explicit source citation (e.g.
|
||||
// "[Source: X, @handle, 2026-05-28]"), it's already attributed — skip.
|
||||
// Catches instructional/example lines in recipe docs that demonstrate
|
||||
// the CORRECT citation format. (v0.42.x)
|
||||
if (/\[\s*source:/i.test(line)) continue;
|
||||
// Strip inline-code spans (`...`) before matching: phrases shown as
|
||||
// inline-code templates in docs are examples, not bare claims. The
|
||||
// fenced-code skip above only covers ``` blocks, not inline backticks.
|
||||
const lineForMatch = line.replace(/`[^`]*`/g, '');
|
||||
for (const re of BARE_TWEET_PHRASES) {
|
||||
const m = line.match(re);
|
||||
const m = lineForMatch.match(re);
|
||||
if (m) {
|
||||
hits.push({ slug, line: i + 1, rawLine: line.trim(), phrase: m[0] });
|
||||
break; // one finding per line is enough
|
||||
|
||||
@@ -1664,7 +1664,13 @@ export async function registerBuiltinHandlers(
|
||||
|
||||
worker.register('backlinks', async (job) => {
|
||||
const { runBacklinksCore } = await import('./backlinks.ts');
|
||||
const action: 'check' | 'fix' = job.data.action === 'check' ? 'check' : 'fix';
|
||||
// Default to 'check', not 'fix': backlinks jobs submitted with an empty
|
||||
// payload (e.g. the sync→embed→backlinks chains enqueued after ingestion)
|
||||
// must never rewrite tracked brain pages with generated "Referenced in"
|
||||
// timeline bullets. Mirrors the documented intent in src/core/cycle.ts
|
||||
// (runPhaseBacklinks). The filesystem fixer stays available explicitly
|
||||
// via '{"action":"fix"}' or `gbrain check-backlinks fix`.
|
||||
const action: 'check' | 'fix' = job.data.action === 'fix' ? 'fix' : 'check';
|
||||
const dir = typeof job.data.dir === 'string'
|
||||
? job.data.dir
|
||||
: (await engine.getConfig('sync.repo_path')) ?? '.';
|
||||
|
||||
@@ -127,7 +127,12 @@ export function lintContent(content: string, filePath: string, opts: LintContent
|
||||
}
|
||||
|
||||
// Rule: Wrapping code fences (```markdown ... ```)
|
||||
if (content.match(/^```(?:markdown|md)\s*\n/m) && content.match(/\n```\s*$/m)) {
|
||||
// Detector intentionally has NO /m flag so ^/$ match start/end of the whole
|
||||
// file, not inner lines. Keeps detector in sync with fixContent() below,
|
||||
// which also has no /m flag. Without this, lint reports "fixable" false
|
||||
// positives on any page that simply contains a ```markdown code block, but
|
||||
// fixContent can never strip them (its regex only matches whole-file wrappers).
|
||||
if (content.match(/^```(?:markdown|md)\s*\n/) && content.match(/\n```\s*$/)) {
|
||||
issues.push({
|
||||
file: filePath, line: 1, rule: 'code-fence-wrap',
|
||||
message: 'Page wrapped in ```markdown code fences (LLM artifact)',
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
/**
|
||||
* gbrain maintain — conservative self-healing maintenance.
|
||||
*
|
||||
* This command automates the safe parts of the operator runbook:
|
||||
* - stale link/timeline extraction
|
||||
* - stale per-source dream cycles when doctor reports cycle_freshness
|
||||
*
|
||||
* It deliberately does NOT mutate source files, apply schema-pack upgrades, or
|
||||
* invent semantic hub links. Those need review or a separate command with an
|
||||
* auditable proposal surface.
|
||||
*/
|
||||
|
||||
import { existsSync } from 'fs';
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import type { BrainHealth } from '../core/types.ts';
|
||||
import { buildChecks, computeDoctorReport, type DoctorReport, type Check } from './doctor.ts';
|
||||
import { extractStaleFromDB } from './extract.ts';
|
||||
import { runCycle, type CycleReport } from '../core/cycle.ts';
|
||||
|
||||
type ActionStatus = 'ok' | 'would_apply' | 'applied' | 'blocked' | 'skipped';
|
||||
|
||||
export interface MaintenanceAction {
|
||||
name: string;
|
||||
status: ActionStatus;
|
||||
message: string;
|
||||
details?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface MaintainOptions {
|
||||
json: boolean;
|
||||
safe: boolean;
|
||||
dryRun: boolean;
|
||||
help: boolean;
|
||||
}
|
||||
|
||||
export interface MaintainReport {
|
||||
mode: 'dry-run' | 'safe';
|
||||
before: {
|
||||
health: BrainHealth;
|
||||
doctor: DoctorReport;
|
||||
};
|
||||
actions: MaintenanceAction[];
|
||||
after: {
|
||||
health: BrainHealth;
|
||||
doctor: DoctorReport;
|
||||
};
|
||||
}
|
||||
|
||||
export function parseMaintainArgs(args: string[]): MaintainOptions {
|
||||
const safe = args.includes('--safe');
|
||||
return {
|
||||
json: args.includes('--json'),
|
||||
safe,
|
||||
dryRun: args.includes('--dry-run') || !safe,
|
||||
help: args.includes('--help') || args.includes('-h'),
|
||||
};
|
||||
}
|
||||
|
||||
export function extractCycleFreshnessSourceIds(checks: Check[]): string[] {
|
||||
const ids = new Set<string>();
|
||||
for (const check of checks) {
|
||||
if (check.name !== 'cycle_freshness' || check.status === 'ok') continue;
|
||||
const re = /Source '([^']+)' last cycled/g;
|
||||
for (const match of check.message.matchAll(re)) {
|
||||
const id = match[1]?.trim();
|
||||
if (id) ids.add(id);
|
||||
}
|
||||
}
|
||||
return [...ids].sort();
|
||||
}
|
||||
|
||||
async function buildDoctorReport(engine: BrainEngine): Promise<DoctorReport> {
|
||||
const checks = await buildChecks(engine, ['--json', '--scope=brain']);
|
||||
return computeDoctorReport(checks);
|
||||
}
|
||||
|
||||
async function runStaleExtraction(
|
||||
engine: BrainEngine,
|
||||
beforeHealth: BrainHealth,
|
||||
dryRun: boolean,
|
||||
): Promise<MaintenanceAction> {
|
||||
if (beforeHealth.stale_pages <= 0) {
|
||||
return { name: 'extract_stale', status: 'ok', message: 'No stale pages.' };
|
||||
}
|
||||
|
||||
if (dryRun) {
|
||||
return {
|
||||
name: 'extract_stale',
|
||||
status: 'would_apply',
|
||||
message: `Would run DB-backed stale extraction for ${beforeHealth.stale_pages} page(s).`,
|
||||
details: { stale_pages: beforeHealth.stale_pages },
|
||||
};
|
||||
}
|
||||
|
||||
const result = await extractStaleFromDB(engine, {
|
||||
dryRun: false,
|
||||
jsonMode: false,
|
||||
includeFrontmatter: false,
|
||||
catchUp: false,
|
||||
});
|
||||
|
||||
return {
|
||||
name: 'extract_stale',
|
||||
status: 'applied',
|
||||
message: `Processed ${result.pagesProcessed} stale page(s); ${result.staleRemaining} remain.`,
|
||||
details: {
|
||||
links_created: result.linksCreated,
|
||||
timeline_created: result.timelineCreated,
|
||||
pages_processed: result.pagesProcessed,
|
||||
stale_remaining: result.staleRemaining,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function runCycleFreshnessMaintenance(
|
||||
engine: BrainEngine,
|
||||
beforeDoctor: DoctorReport,
|
||||
dryRun: boolean,
|
||||
): Promise<MaintenanceAction[]> {
|
||||
const sourceIds = extractCycleFreshnessSourceIds(beforeDoctor.checks);
|
||||
if (sourceIds.length === 0) {
|
||||
return [{ name: 'cycle_freshness', status: 'ok', message: 'All sources cycled recently.' }];
|
||||
}
|
||||
|
||||
if (dryRun) {
|
||||
return sourceIds.map((sourceId) => ({
|
||||
name: 'cycle_freshness',
|
||||
status: 'would_apply',
|
||||
message: `Would run source-scoped dream cycle for ${sourceId}.`,
|
||||
details: { source_id: sourceId },
|
||||
}));
|
||||
}
|
||||
|
||||
const sources = await engine.listAllSources();
|
||||
const actions: MaintenanceAction[] = [];
|
||||
|
||||
for (const sourceId of sourceIds) {
|
||||
const source = sources.find((s) => s.id === sourceId);
|
||||
const localPath = source?.local_path ?? null;
|
||||
const brainDir = localPath && existsSync(localPath) ? localPath : null;
|
||||
const report: CycleReport = await runCycle(engine, {
|
||||
brainDir,
|
||||
dryRun: false,
|
||||
pull: false,
|
||||
sourceId,
|
||||
});
|
||||
actions.push({
|
||||
name: 'cycle_freshness',
|
||||
status: report.status === 'failed' ? 'blocked' : 'applied',
|
||||
message: `Ran source-scoped dream cycle for ${sourceId}: ${report.status}.`,
|
||||
details: {
|
||||
source_id: sourceId,
|
||||
brain_dir: brainDir,
|
||||
cycle_status: report.status,
|
||||
phases: report.phases.map((p) => ({ phase: p.phase, status: p.status })),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return actions;
|
||||
}
|
||||
|
||||
export async function runMaintain(engine: BrainEngine, args: string[]): Promise<MaintainReport | void> {
|
||||
const opts = parseMaintainArgs(args);
|
||||
if (opts.help) {
|
||||
console.log(`Usage: gbrain maintain [--safe] [--dry-run] [--json]
|
||||
|
||||
Conservative self-healing maintenance.
|
||||
|
||||
Modes:
|
||||
--dry-run Preview safe actions without writes. Default when --safe is absent.
|
||||
--safe Apply safe actions: stale extraction and source cycle freshness.
|
||||
--json Emit a structured before/action/after report.
|
||||
|
||||
Not auto-applied:
|
||||
source-file frontmatter fixes, schema-pack upgrades, atom-pack changes,
|
||||
semantic hub-link guesses, and destructive cleanup.
|
||||
`);
|
||||
return;
|
||||
}
|
||||
|
||||
const beforeHealth = await engine.getHealth();
|
||||
const beforeDoctor = await buildDoctorReport(engine);
|
||||
const actions: MaintenanceAction[] = [];
|
||||
|
||||
actions.push(await runStaleExtraction(engine, beforeHealth, opts.dryRun));
|
||||
actions.push(...await runCycleFreshnessMaintenance(engine, beforeDoctor, opts.dryRun));
|
||||
|
||||
const afterHealth = await engine.getHealth();
|
||||
const afterDoctor = await buildDoctorReport(engine);
|
||||
const report: MaintainReport = {
|
||||
mode: opts.dryRun ? 'dry-run' : 'safe',
|
||||
before: { health: beforeHealth, doctor: beforeDoctor },
|
||||
actions,
|
||||
after: { health: afterHealth, doctor: afterDoctor },
|
||||
};
|
||||
|
||||
if (opts.json) {
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
} else {
|
||||
printMaintainReport(report);
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
function printMaintainReport(report: MaintainReport): void {
|
||||
console.log(`GBrain maintain (${report.mode})`);
|
||||
console.log(
|
||||
`Before: brain_score=${Math.round(report.before.health.brain_score)}/100 ` +
|
||||
`stale=${report.before.health.stale_pages} islands=${report.before.health.orphan_pages} ` +
|
||||
`doctor=${report.before.doctor.status}`,
|
||||
);
|
||||
for (const action of report.actions) {
|
||||
console.log(` ${action.status}: ${action.name} — ${action.message}`);
|
||||
}
|
||||
console.log(
|
||||
`After: brain_score=${Math.round(report.after.health.brain_score)}/100 ` +
|
||||
`stale=${report.after.health.stale_pages} islands=${report.after.health.orphan_pages} ` +
|
||||
`doctor=${report.after.doctor.status}`,
|
||||
);
|
||||
if (report.mode === 'dry-run') {
|
||||
console.log('Run `gbrain maintain --safe` to apply safe actions.');
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -536,7 +536,20 @@ function shouldSkipProvider(modelStr: string, skip: string[]): boolean {
|
||||
|
||||
export async function runModels(engine: BrainEngine, args: string[]): Promise<void> {
|
||||
const json = args.includes('--json');
|
||||
const sub = args[1] === 'doctor' ? 'doctor' : args[1] === 'help' || args.includes('--help') || args.includes('-h') ? 'help' : 'read';
|
||||
// args is `subArgs` from cli.ts `handleCliOnly` — the leading 'models'
|
||||
// token has already been stripped. The subcommand is at args[0], NOT
|
||||
// args[1]. Pre-fix this check was `args[1]`, so `gbrain models doctor`
|
||||
// silently fell through to the read view. The doctor probe path was
|
||||
// unreachable from the CLI.
|
||||
//
|
||||
// --help honored FIRST so `gbrain models doctor --help` shows usage
|
||||
// instead of running network probes (which would spend tokens or
|
||||
// exit nonzero when the user only asked for help). Pre-fix the
|
||||
// args[1] ternary happened to dodge this by always falling through
|
||||
// to the args.includes('--help') branch; the args[0] rewrite needs
|
||||
// explicit ordering to preserve that behavior.
|
||||
const hasHelp = args.includes('--help') || args.includes('-h') || args[0] === 'help';
|
||||
const sub = hasHelp ? 'help' : args[0] === 'doctor' ? 'doctor' : 'read';
|
||||
|
||||
if (sub === 'help') {
|
||||
process.stdout.write(
|
||||
|
||||
+10
-55
@@ -15,6 +15,11 @@
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import { createProgress, startHeartbeat } from '../core/progress.ts';
|
||||
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
|
||||
import {
|
||||
shouldExcludeFromOrphanReporting,
|
||||
loadOrphanPolicyOverrides,
|
||||
type OrphanPolicyOverrides,
|
||||
} from '../core/orphan-policy.ts';
|
||||
|
||||
// --- Types ---
|
||||
|
||||
@@ -32,65 +37,14 @@ export interface OrphanResult {
|
||||
excluded: number;
|
||||
}
|
||||
|
||||
// --- Filter constants ---
|
||||
|
||||
/** Slug suffixes that are always auto-generated root files */
|
||||
const AUTO_SUFFIX_PATTERNS = ['/_index', '/log'];
|
||||
|
||||
/** Page slugs that are pseudo-pages by convention */
|
||||
const PSEUDO_SLUGS = new Set(['_atlas', '_index', '_stats', '_orphans', '_scratch', 'claude']);
|
||||
|
||||
/** Slug segment that marks raw sources */
|
||||
const RAW_SEGMENT = '/raw/';
|
||||
|
||||
/** Slug prefixes where no inbound links is expected */
|
||||
const DENY_PREFIXES = [
|
||||
'output/',
|
||||
'dashboards/',
|
||||
'scripts/',
|
||||
'templates/',
|
||||
'openclaw/config/',
|
||||
];
|
||||
|
||||
/** First slug segments where no inbound links is expected */
|
||||
const FIRST_SEGMENT_EXCLUSIONS = new Set([
|
||||
'scratch',
|
||||
'thoughts',
|
||||
'catalog',
|
||||
'entities',
|
||||
'raw',
|
||||
'atoms',
|
||||
'skills',
|
||||
]);
|
||||
|
||||
// --- Filter logic ---
|
||||
|
||||
/**
|
||||
* Returns true if a slug should be excluded from orphan reporting by default.
|
||||
* These are pages where having no inbound links is expected / not a content problem.
|
||||
*/
|
||||
export function shouldExclude(slug: string): boolean {
|
||||
// Pseudo-pages (exact match)
|
||||
if (PSEUDO_SLUGS.has(slug)) return true;
|
||||
|
||||
// Auto-generated suffix patterns
|
||||
for (const suffix of AUTO_SUFFIX_PATTERNS) {
|
||||
if (slug.endsWith(suffix)) return true;
|
||||
}
|
||||
|
||||
// Raw source slugs
|
||||
if (slug.includes(RAW_SEGMENT)) return true;
|
||||
|
||||
// Deny-prefix slugs
|
||||
for (const prefix of DENY_PREFIXES) {
|
||||
if (slug.startsWith(prefix)) return true;
|
||||
}
|
||||
|
||||
// First-segment exclusions
|
||||
const firstSegment = slug.split('/')[0];
|
||||
if (FIRST_SEGMENT_EXCLUSIONS.has(firstSegment)) return true;
|
||||
|
||||
return false;
|
||||
export function shouldExclude(slug: string, overrides?: OrphanPolicyOverrides): boolean {
|
||||
return shouldExcludeFromOrphanReporting(slug, overrides);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -156,6 +110,7 @@ export async function findOrphans(
|
||||
let allOrphans: { slug: string; title: string; domain: string | null }[];
|
||||
let total: number;
|
||||
let excludedAll: number;
|
||||
const overrides = includePseudo ? undefined : await loadOrphanPolicyOverrides(engine);
|
||||
try {
|
||||
allOrphans = await engine.findOrphanPages(
|
||||
sourceIds ? { sourceIds } : sourceId ? { sourceId } : undefined,
|
||||
@@ -184,7 +139,7 @@ export async function findOrphans(
|
||||
total = liveRows.length;
|
||||
excludedAll = includePseudo
|
||||
? 0
|
||||
: liveRows.reduce((n, r) => n + (shouldExclude(r.slug) ? 1 : 0), 0);
|
||||
: liveRows.reduce((n, r) => n + (shouldExclude(r.slug, overrides) ? 1 : 0), 0);
|
||||
} finally {
|
||||
stopHb();
|
||||
progress.finish();
|
||||
@@ -192,7 +147,7 @@ export async function findOrphans(
|
||||
|
||||
const filtered = includePseudo
|
||||
? allOrphans
|
||||
: allOrphans.filter(row => !shouldExclude(row.slug));
|
||||
: allOrphans.filter(row => !shouldExclude(row.slug, overrides));
|
||||
|
||||
const orphans: OrphanPage[] = filtered.map(row => ({
|
||||
slug: row.slug,
|
||||
|
||||
+17
-143
@@ -365,42 +365,6 @@ export interface AgentClientSpend {
|
||||
inflight_count: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* `/admin/api/sources` source list — the input rows for buildSyncStatusReport.
|
||||
*
|
||||
* Queries the JSONB config column directly (listSources doesn't carry it,
|
||||
* but buildSyncStatusReport needs syncEnabled / strategy fields).
|
||||
*
|
||||
* Deliberately does NOT filter on local_path: in a push-only deployment
|
||||
* (content arrives via MCP put_page / capture / ingest, not `gbrain sync`
|
||||
* of a server checkout) every source has a null local_path — filtering on
|
||||
* it would empty both the Sources tab AND the federation source-picker.
|
||||
* buildSyncStatusReport does no disk I/O, so null-local_path sources
|
||||
* report fine (pages/chunks from SQL, staleness 'unknown' / never-synced).
|
||||
*/
|
||||
export async function queryAdminSources(engine: BrainEngine): Promise<
|
||||
Array<{ id: string; name: string; local_path: string | null; config: Record<string, unknown> }>
|
||||
> {
|
||||
const rows = await engine.executeRaw<{
|
||||
id: string;
|
||||
name: string;
|
||||
local_path: string | null;
|
||||
config: Record<string, unknown> | string | null;
|
||||
}>(
|
||||
`SELECT id, name, local_path, config FROM sources
|
||||
WHERE archived IS NOT TRUE
|
||||
ORDER BY id`,
|
||||
);
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
local_path: r.local_path,
|
||||
config: typeof r.config === 'string'
|
||||
? (JSON.parse(r.config) as Record<string, unknown>)
|
||||
: (r.config ?? {}),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function queryAgentClientSpend(engine: BrainEngine): Promise<AgentClientSpend[]> {
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const rows = await sql`
|
||||
@@ -879,6 +843,21 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
// reverse proxies / tunnels; default to localhost for dev.
|
||||
const issuerUrl = new URL(publicUrl || `http://localhost:${port}`);
|
||||
|
||||
// MCP authorization spec (2025-06-18 draft §5.1) and RFC 9728 require the
|
||||
// protected resource server to return its discovery metadata URL in the
|
||||
// WWW-Authenticate header on 401 responses:
|
||||
//
|
||||
// WWW-Authenticate: Bearer resource_metadata="<URL>"
|
||||
//
|
||||
// Clients (claude.ai, Cursor, every other MCP-aware OAuth client) use that
|
||||
// URL to find the authorization-server discovery doc + token endpoint
|
||||
// without the user having to paste those URLs manually. Pre-fix the header
|
||||
// shipped `Bearer error="invalid_token", ...` with no resource_metadata
|
||||
// parameter, so MCP clients couldn't begin the OAuth flow from a fresh
|
||||
// 401 — they would silently fail to connect with a generic "couldn't
|
||||
// reach the MCP server" error.
|
||||
const resourceMetadataUrl = `${issuerUrl.toString().replace(/\/$/, '')}/.well-known/oauth-protected-resource`;
|
||||
|
||||
// F9: cookie `secure` flag honors both the request's TLS state (req.secure
|
||||
// is set when express trust-proxy lands an X-Forwarded-Proto: https) AND
|
||||
// the operator's declared issuer protocol (so a Cloudflare-tunnel deploy
|
||||
@@ -1547,111 +1526,6 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sources tab — read-only view of registered sources with sync + embed
|
||||
// coverage stats. Drives the admin SPA's `Sources` page.
|
||||
//
|
||||
// Returns the same shape `gbrain sources status --json` prints, so the
|
||||
// SPA stays in lockstep with the CLI surface.
|
||||
// ---------------------------------------------------------------------------
|
||||
app.get('/admin/api/sources', requireAdmin, async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const { buildSyncStatusReport } = await import('./sync.ts');
|
||||
const report = await buildSyncStatusReport(engine, await queryAdminSources(engine));
|
||||
res.json(report);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
res.status(503).json({ error: 'service_unavailable', detail: msg });
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Federated-read management (admin-side counterparts of the CLI commands
|
||||
// `gbrain auth grant-read / revoke-read / set-federated-read`). All three
|
||||
// route through the same *Core helpers as the CLI so race-safety,
|
||||
// soft-delete filter, and source-id shape validation apply uniformly.
|
||||
//
|
||||
// The admin SPA's `Agents` page renders "Manage reads" actions per
|
||||
// client backed by these endpoints.
|
||||
// ---------------------------------------------------------------------------
|
||||
app.get('/admin/api/agents/federated-read', requireAdmin, async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const rows = await sql`
|
||||
SELECT client_id, client_name, source_id, federated_read
|
||||
FROM oauth_clients
|
||||
WHERE deleted_at IS NULL
|
||||
ORDER BY client_name
|
||||
`;
|
||||
const clients = rows.map((r) => ({
|
||||
client_id: String(r.client_id),
|
||||
client_name: String(r.client_name),
|
||||
source_id: r.source_id == null ? null : String(r.source_id),
|
||||
federated_read: Array.isArray(r.federated_read)
|
||||
? (r.federated_read as string[]).map(String)
|
||||
: [],
|
||||
}));
|
||||
res.json({ clients });
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
res.status(503).json({ error: 'service_unavailable', detail: msg });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/admin/api/agents/:clientId/grant-read', requireAdmin, express.json(), async (req: Request, res: Response) => {
|
||||
const clientId = String(req.params.clientId ?? '');
|
||||
const sourceId = String(req.body?.source_id ?? '').trim();
|
||||
if (!clientId || !sourceId) {
|
||||
res.status(400).json({ error: 'invalid_request', detail: 'clientId path param + source_id body required' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { grantReadCore } = await import('./auth.ts');
|
||||
const outcome = await grantReadCore(sql, clientId, sourceId);
|
||||
res.json({ outcome });
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
res.status(400).json({ error: 'mutation_failed', detail: msg });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/admin/api/agents/:clientId/revoke-read', requireAdmin, express.json(), async (req: Request, res: Response) => {
|
||||
const clientId = String(req.params.clientId ?? '');
|
||||
const sourceId = String(req.body?.source_id ?? '').trim();
|
||||
if (!clientId || !sourceId) {
|
||||
res.status(400).json({ error: 'invalid_request', detail: 'clientId path param + source_id body required' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { revokeReadCore } = await import('./auth.ts');
|
||||
const outcome = await revokeReadCore(sql, clientId, sourceId);
|
||||
res.json({ outcome });
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
res.status(400).json({ error: 'mutation_failed', detail: msg });
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/admin/api/agents/:clientId/set-federated-read', requireAdmin, express.json(), async (req: Request, res: Response) => {
|
||||
const clientId = String(req.params.clientId ?? '');
|
||||
const rawIds = req.body?.source_ids;
|
||||
if (!clientId || !Array.isArray(rawIds)) {
|
||||
res.status(400).json({ error: 'invalid_request', detail: 'clientId path param + source_ids[] body required' });
|
||||
return;
|
||||
}
|
||||
// Encode the array as CSV so the same setFederatedReadCore signature
|
||||
// (string CSV input) the CLI uses applies here. Empty array → empty
|
||||
// string → clears the list.
|
||||
const csv = rawIds.map((s) => String(s).trim()).filter(Boolean).join(',');
|
||||
try {
|
||||
const { setFederatedReadCore } = await import('./auth.ts');
|
||||
const outcome = await setFederatedReadCore(sql, clientId, csv);
|
||||
res.json({ outcome });
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
res.status(400).json({ error: 'mutation_failed', detail: msg });
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SSE live activity feed
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1742,7 +1616,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
res.status(405).json({ jsonrpc: '2.0', error: { code: -32000, message: 'Method not allowed' }, id: null });
|
||||
});
|
||||
|
||||
app.post('/mcp', requireBearerAuth({ verifier: oauthProvider }), async (req: Request, res: Response) => {
|
||||
app.post('/mcp', requireBearerAuth({ verifier: oauthProvider, resourceMetadataUrl }), async (req: Request, res: Response) => {
|
||||
const startTime = Date.now();
|
||||
const authInfo = (req as any).auth as AuthInfo;
|
||||
|
||||
@@ -2085,7 +1959,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
app.post(
|
||||
'/ingest',
|
||||
ingestRateLimiter,
|
||||
requireBearerAuth({ verifier: oauthProvider, requiredScopes: ['write'] }),
|
||||
requireBearerAuth({ verifier: oauthProvider, requiredScopes: ['write'], resourceMetadataUrl }),
|
||||
express.raw({ type: '*/*', limit: ingestMaxBytes }),
|
||||
async (req: Request, res: Response) => {
|
||||
const startTime = Date.now();
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* degrades to gather-only output with a warning if missing.
|
||||
*/
|
||||
import type { BrainEngine } from '../core/engine.ts';
|
||||
import { runThink, persistSynthesis } from '../core/think/index.ts';
|
||||
import { runThink, persistSynthesis, stripGapsSection } from '../core/think/index.ts';
|
||||
import { loadConfig, isThinClient } from '../core/config.ts';
|
||||
import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';
|
||||
|
||||
@@ -157,7 +157,7 @@ prints what would have been the input (exit 0).
|
||||
|
||||
// Human-readable output
|
||||
console.log(`# ${question}\n`);
|
||||
console.log(result.answer);
|
||||
console.log(stripGapsSection(result.answer));
|
||||
console.log('');
|
||||
if (result.gaps.length > 0) {
|
||||
console.log('## Gaps');
|
||||
|
||||
@@ -263,6 +263,15 @@ export function dimsProviderOptions(
|
||||
if (modelId === 'text-embedding-v3' || modelId === 'embedding-3') {
|
||||
return { openaiCompatible: { dimensions: dims } };
|
||||
}
|
||||
// Qwen3-Embedding family on Ollama (and any other openai-compatible
|
||||
// provider serving it) supports Matryoshka truncation via `dimensions`.
|
||||
// Native sizes: 0.6B=1024, 4B=2560, 8B=4096. Without `dimensions`,
|
||||
// Ollama returns the native size and brains configured for narrower
|
||||
// widths hard-fail with a dim-mismatch error. Pattern match the bare
|
||||
// model name + any `:tag` (e.g. `qwen3-embedding:4b`, `qwen3-embedding:0.6b`).
|
||||
if (modelId === 'qwen3-embedding' || modelId.startsWith('qwen3-embedding:')) {
|
||||
return { openaiCompatible: { dimensions: dims } };
|
||||
}
|
||||
// MiniMax embo-01 takes a `type: 'db' | 'query'` field for asymmetric
|
||||
// retrieval. Today still hardcoded to 'db' for back-compat — opting
|
||||
// into the new inputType seam is a follow-up (see plan's deferred
|
||||
|
||||
+27
-1
@@ -599,6 +599,8 @@ function warnRecipesMissingBatchTokens(): void {
|
||||
// LiteLLM proxy, llama-server) — they ship without a static cap because
|
||||
// the cap depends on a user-launched server. Warning is noise for them.
|
||||
if (embedding.no_batch_cap === true) continue;
|
||||
// A declared item-count cap is a real batch cap — no warning needed.
|
||||
if (embedding.max_batch_items !== undefined) continue;
|
||||
if (_warnedRecipes.has(recipe.id)) continue;
|
||||
_warnedRecipes.add(recipe.id);
|
||||
// eslint-disable-next-line no-console
|
||||
@@ -1517,10 +1519,17 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32A
|
||||
|
||||
// Pre-split is gated on max_batch_tokens. Recipes without it (e.g. OpenAI)
|
||||
// ride the fast path: one embedMany call, no recursion safety net.
|
||||
const batches = maxBatchTokens
|
||||
const tokenBatches = maxBatchTokens
|
||||
? splitByTokenBudget(truncated, Math.floor(maxBatchTokens * effectiveSafetyFactor(recipe)), charsPerToken)
|
||||
: [truncated];
|
||||
|
||||
// Hard COUNT cap (e.g. llama-server's "maximum allowed batch size 32").
|
||||
// Token budget can't bound item count, so re-split any oversized batch.
|
||||
const maxBatchItems = embedding?.max_batch_items;
|
||||
const batches = maxBatchItems
|
||||
? tokenBatches.flatMap(b => capBatchItems(b, maxBatchItems))
|
||||
: tokenBatches;
|
||||
|
||||
const allEmbeddings: Float32Array[] = [];
|
||||
let _embedThrew = false;
|
||||
try {
|
||||
@@ -1596,6 +1605,23 @@ export function splitByTokenBudget(
|
||||
return batches;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a batch into sub-batches of at most `maxItems` inputs. Enforces a
|
||||
* hard COUNT cap that the token-budget split can't (many tiny inputs fit
|
||||
* under any token budget). Used for endpoints like llama.cpp's llama-server
|
||||
* that reject requests exceeding their launch batch size.
|
||||
*
|
||||
* @internal exported for tests; not part of the public gateway API.
|
||||
*/
|
||||
export function capBatchItems(texts: string[], maxItems: number): string[][] {
|
||||
if (maxItems <= 0 || texts.length <= maxItems) return [texts];
|
||||
const batches: string[][] = [];
|
||||
for (let i = 0; i < texts.length; i += maxItems) {
|
||||
batches.push(texts.slice(i, i + maxItems));
|
||||
}
|
||||
return batches;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the error looks like a provider batch-token-limit error.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { Recipe } from '../types.ts';
|
||||
|
||||
/**
|
||||
* Alibaba DashScope (灵积) reranker. DashScope's OpenAI-compatible surface
|
||||
* splits by capability: embeddings live under `/compatible-mode/v1` (see the
|
||||
* sibling `dashscope` recipe) while rerank lives under `/compatible-api/v1`
|
||||
* with a PLURAL leaf — `POST {base}/reranks`. Wire shape matches ZeroEntropy:
|
||||
* request `{model, query, documents, top_n?}`, response
|
||||
* `{results: [{index, relevance_score}]}` — so it rides gateway.rerank()'s
|
||||
* native path with only the recipe-pluggable `path` override (v0.40.6.1).
|
||||
*
|
||||
* This is a SEPARATE recipe rather than a reranker touchpoint on `dashscope`
|
||||
* because the two capabilities need different base URLs (`compatible-mode`
|
||||
* vs `compatible-api`) and `provider_base_urls` is keyed by recipe id — one
|
||||
* recipe can't point embeddings and rerank at different prefixes. Same
|
||||
* topology precedent as llama-server vs llama-server-reranker.
|
||||
*
|
||||
* Live-verified against the China endpoint (2026-07): `/reranks` with
|
||||
* `qwen3-rerank` → 200 `results[].relevance_score`; `/rerank` (singular)
|
||||
* → 404; `gte-rerank-v2` → 404 "Unsupported model for OpenAI compatibility
|
||||
* mode" (native-API only, so it is deliberately NOT listed here).
|
||||
*
|
||||
* Note: the international endpoint requires a region-aware DASHSCOPE_API_KEY.
|
||||
* China-region users point at https://dashscope.aliyuncs.com/compatible-api/v1
|
||||
* via `provider_base_urls['dashscope-rerank']`, mirroring the embedding
|
||||
* recipe's convention.
|
||||
*/
|
||||
export const dashscopeRerank: Recipe = {
|
||||
id: 'dashscope-rerank',
|
||||
name: 'Alibaba DashScope (灵积, reranker)',
|
||||
tier: 'openai-compat',
|
||||
implementation: 'openai-compatible',
|
||||
base_url_default: 'https://dashscope-intl.aliyuncs.com/compatible-api/v1',
|
||||
auth_env: {
|
||||
required: ['DASHSCOPE_API_KEY'],
|
||||
setup_url: 'https://help.aliyun.com/zh/model-studio/getting-started/',
|
||||
},
|
||||
touchpoints: {
|
||||
reranker: {
|
||||
// Only the model verified live on the OpenAI-compat /reranks surface.
|
||||
// gte-rerank-v2 exists on DashScope's native API but the compat path
|
||||
// rejects it ("Unsupported model for OpenAI compatibility mode").
|
||||
models: ['qwen3-rerank'],
|
||||
default_model: 'qwen3-rerank',
|
||||
// Mirror ZE's defensive per-request ceiling; gateway.rerank()
|
||||
// pre-flights body size and fails open.
|
||||
max_payload_bytes: 5_000_000,
|
||||
// PLURAL leaf under compatible-api — the whole reason this recipe
|
||||
// exists. `${base_url}${path}` → `…/compatible-api/v1/reranks`.
|
||||
path: '/reranks',
|
||||
// Hosted API: no local warmup, but cross-region latency can exceed
|
||||
// the 5s gateway default (same rationale as llama-server-reranker).
|
||||
default_timeout_ms: 30_000,
|
||||
},
|
||||
},
|
||||
setup_hint:
|
||||
'Get an API key at https://help.aliyun.com/zh/model-studio/getting-started/, then ' +
|
||||
'`export DASHSCOPE_API_KEY=...` and `gbrain config set search.reranker.model ' +
|
||||
'dashscope-rerank:qwen3-rerank`. China-region accounts: `gbrain config set ' +
|
||||
'provider_base_urls.dashscope-rerank https://dashscope.aliyuncs.com/compatible-api/v1`.',
|
||||
};
|
||||
@@ -19,6 +19,7 @@ import { together } from './together.ts';
|
||||
import { llamaServer } from './llama-server.ts';
|
||||
import { minimax } from './minimax.ts';
|
||||
import { dashscope } from './dashscope.ts';
|
||||
import { dashscopeRerank } from './dashscope-rerank.ts';
|
||||
import { zhipu } from './zhipu.ts';
|
||||
import { azureOpenAI } from './azure-openai.ts';
|
||||
import { zeroentropyai } from './zeroentropyai.ts';
|
||||
@@ -42,6 +43,7 @@ const ALL: Recipe[] = [
|
||||
llamaServerReranker,
|
||||
minimax,
|
||||
dashscope,
|
||||
dashscopeRerank,
|
||||
zhipu,
|
||||
azureOpenAI,
|
||||
zeroentropyai,
|
||||
|
||||
@@ -35,9 +35,12 @@ export const llamaServer: Recipe = {
|
||||
trust_custom_dims: true, // #2271: user knows the launched model's native dim
|
||||
cost_per_1m_tokens_usd: 0,
|
||||
price_last_verified: '2026-05-10',
|
||||
// llama-server's batch capacity is set by `--ctx-size` at launch
|
||||
// time; no static cap to declare. v0.32 (#779).
|
||||
no_batch_cap: true,
|
||||
// llama-server enforces a hard request-COUNT cap equal to its launch
|
||||
// batch size (`--batch-size`, default 32): it rejects requests with
|
||||
// more inputs with `batch size N > maximum allowed batch size 32`.
|
||||
// The token-budget split can't bound item count, so cap it here. A
|
||||
// server launched with a larger `-b` can raise this. v0.32 (#779).
|
||||
max_batch_items: 32,
|
||||
},
|
||||
},
|
||||
/**
|
||||
|
||||
@@ -54,6 +54,16 @@ export interface EmbeddingTouchpoint {
|
||||
* `max_batch_tokens` is also set.
|
||||
*/
|
||||
safety_factor?: number;
|
||||
/**
|
||||
* Maximum number of inputs per embedding request. Some endpoints enforce a
|
||||
* hard COUNT cap independent of token budget — notably llama.cpp's
|
||||
* `llama-server`, which rejects requests with more inputs than its launch
|
||||
* batch size (e.g. `batch size 100 > maximum allowed batch size 32`). The
|
||||
* token-budget pre-split cannot bound item count (many tiny chunks fit under
|
||||
* any token budget), so this is enforced as a separate hard re-split after
|
||||
* the token split. When unset, no count cap is applied.
|
||||
*/
|
||||
max_batch_items?: number;
|
||||
/**
|
||||
* v0.27.1: when true, at least one model in this recipe accepts image
|
||||
* inputs via a multimodal embedding endpoint (e.g. Voyage's
|
||||
|
||||
@@ -217,9 +217,19 @@ export function parseResolverEntries(resolverContent: string): ResolverEntry[] {
|
||||
// `skillsDir/*/SKILL.md` when manifest.json is missing — the scenario
|
||||
// needed for AGENTS.md-only OpenClaw deployments. See D-CX-12 / F-ENG-1.
|
||||
|
||||
/** Simple YAML frontmatter parser — extracts triggers array if present. */
|
||||
function extractTriggers(skillContent: string): string[] {
|
||||
const fmMatch = skillContent.match(/^---\n([\s\S]*?)\n---/);
|
||||
/**
|
||||
* Simple YAML frontmatter parser — extracts triggers array if present.
|
||||
*
|
||||
* Normalizes CRLF → LF before parsing so Windows checkouts (where
|
||||
* `core.autocrlf=true` is the default) parse correctly. Without this,
|
||||
* the `^---\n` and `^triggers:\s*\n` regexes never match because the
|
||||
* file content is `---\r\n` / `triggers:\r\n`, and every skill on
|
||||
* Windows is reported as `mece_gap` regardless of its actual content.
|
||||
* CI runs on Ubuntu-only so the bug only surfaces in user environments.
|
||||
*/
|
||||
export function extractTriggers(skillContent: string): string[] {
|
||||
const content = skillContent.replace(/\r\n/g, '\n');
|
||||
const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
|
||||
if (!fmMatch) return [];
|
||||
const fm = fmMatch[1];
|
||||
const triggersMatch = fm.match(/^triggers:\s*\n((?:\s+-\s+.+\n?)*)/m);
|
||||
|
||||
@@ -168,6 +168,15 @@ export interface CodeChunkOptions {
|
||||
largeChunkThresholdTokens?: number;
|
||||
fallbackChunkSizeWords?: number;
|
||||
fallbackOverlapWords?: number;
|
||||
/**
|
||||
* Hard upper bound (estimated tokens) on any single emitted chunk. A node
|
||||
* the AST splitter can't break up (a giant object/array literal, a single
|
||||
* huge assignment, a massive template literal) would otherwise be emitted
|
||||
* whole and rejected by the embedder ("input exceeds context length").
|
||||
* Chunks over this budget are recursively re-split. Default 2000 fits the
|
||||
* smallest common embedder context (e.g. nomic-embed-text, 2048).
|
||||
*/
|
||||
maxChunkTokens?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -549,6 +558,7 @@ export function parseWithTimeout(
|
||||
}
|
||||
|
||||
const DEFAULT_CHUNKER_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_CHUNK_TOKENS = 2000;
|
||||
|
||||
function resolveChunkerTimeoutMs(): number {
|
||||
const raw = process.env.GBRAIN_CHUNKER_TIMEOUT_MS;
|
||||
@@ -706,9 +716,9 @@ export async function chunkCodeTextFull(
|
||||
}
|
||||
|
||||
if (chunks.length === 0) {
|
||||
return { chunks: fallbackChunks(source, filePath, language, opts), edges: rawEdges };
|
||||
return { chunks: capOversizedChunks(fallbackChunks(source, filePath, language, opts), filePath, language, opts), edges: rawEdges };
|
||||
}
|
||||
return { chunks: mergeSmallSiblings(chunks, chunkTarget), edges: rawEdges };
|
||||
return { chunks: capOversizedChunks(mergeSmallSiblings(chunks, chunkTarget), filePath, language, opts), edges: rawEdges };
|
||||
} catch {
|
||||
return { chunks: fallbackChunks(source, filePath, language, opts), edges: [] };
|
||||
} finally {
|
||||
@@ -814,6 +824,73 @@ function buildMergedChunk(group: CodeChunk[], index: number): CodeChunk {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Final safety net: guarantee no emitted chunk exceeds the embedder's context
|
||||
* budget. tree-sitter splitting (splitLargeNode) can only break up a node that
|
||||
* exposes a `body` with >= 2 named children. A node without one — a giant
|
||||
* object/array literal, a single huge assignment, a massive template literal —
|
||||
* is emitted whole, producing a chunk far larger than the embedder accepts.
|
||||
* The embedder then rejects it ("input exceeds context length") and the chunk
|
||||
* is never embedded. Recursively re-split any over-budget chunk; fall back to a
|
||||
* hard character split for pathological no-whitespace content (e.g. a minified
|
||||
* one-liner) where word/line splitting can't get under budget.
|
||||
*/
|
||||
function capOversizedChunks(
|
||||
chunks: CodeChunk[],
|
||||
filePath: string,
|
||||
language: SupportedCodeLanguage,
|
||||
opts: CodeChunkOptions,
|
||||
): CodeChunk[] {
|
||||
const cap = opts.maxChunkTokens ?? DEFAULT_MAX_CHUNK_TOKENS;
|
||||
if (!chunks.some((c) => estimateTokens(c.text) > cap)) return chunks;
|
||||
const out: CodeChunk[] = [];
|
||||
for (const c of chunks) {
|
||||
if (estimateTokens(c.text) <= cap) {
|
||||
out.push({ ...c, index: out.length });
|
||||
continue;
|
||||
}
|
||||
// Strip the structured header ("[Lang] path:N-M symbol\n\n") so the splitter
|
||||
// works on the raw body; buildChunk re-adds a header to each piece.
|
||||
const body = c.text.replace(/^\[[^\]]+\] [^\n]+\n\n/, '');
|
||||
for (const piece of splitToTokenBudget(body, cap, opts)) {
|
||||
if (!piece.trim()) continue;
|
||||
out.push(buildChunk({
|
||||
body: piece,
|
||||
filePath,
|
||||
language,
|
||||
symbolName: c.metadata.symbolName,
|
||||
symbolType: c.metadata.symbolType,
|
||||
startLine: c.metadata.startLine,
|
||||
endLine: c.metadata.endLine,
|
||||
index: out.length,
|
||||
parentSymbolPath: c.metadata.parentSymbolPath,
|
||||
}));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Split `text` into pieces each estimated <= cap tokens. Word/line-aware
|
||||
* (recursiveChunk) first; a hard character split is the last resort for
|
||||
* content with no whitespace to break on. */
|
||||
function splitToTokenBudget(text: string, cap: number, opts: CodeChunkOptions): string[] {
|
||||
const out: string[] = [];
|
||||
const pieces = recursiveChunk(text, {
|
||||
chunkSize: opts.fallbackChunkSizeWords ?? 300,
|
||||
chunkOverlap: opts.fallbackOverlapWords ?? 50,
|
||||
}).map((p) => p.text);
|
||||
for (const piece of pieces) {
|
||||
if (estimateTokens(piece) <= cap) {
|
||||
out.push(piece);
|
||||
continue;
|
||||
}
|
||||
// ~3.5 chars/token is a conservative cl100k estimate for source text.
|
||||
const charBudget = Math.max(1, Math.floor(cap * 3.5));
|
||||
for (let i = 0; i < piece.length; i += charBudget) out.push(piece.slice(i, i + charBudget));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------- Internals ----------
|
||||
|
||||
function fallbackChunks(
|
||||
|
||||
+33
-1
@@ -620,7 +620,10 @@ export function loadConfig(): GBrainConfig | null {
|
||||
* size the schema and must be stable across engine connect.
|
||||
*/
|
||||
export async function loadConfigWithEngine(
|
||||
engine: { getConfig(key: string): Promise<string | null | undefined> },
|
||||
engine: {
|
||||
getConfig(key: string): Promise<string | null | undefined>;
|
||||
listConfigKeys?(prefix: string): Promise<string[]>;
|
||||
},
|
||||
base?: GBrainConfig | null,
|
||||
): Promise<GBrainConfig | null> {
|
||||
// Codex /ship finding #3: when there's no file config AND no env DB URL,
|
||||
@@ -657,11 +660,31 @@ export async function loadConfigWithEngine(
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
async function dbPrefixMap(prefix: string): Promise<Record<string, string> | undefined> {
|
||||
if (typeof engine.listConfigKeys !== 'function') return undefined;
|
||||
let keys: string[];
|
||||
try {
|
||||
keys = await engine.listConfigKeys(prefix);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const out: Record<string, string> = {};
|
||||
for (const key of keys.sort()) {
|
||||
if (!key.startsWith(prefix)) continue;
|
||||
const leaf = key.slice(prefix.length);
|
||||
if (!leaf) continue;
|
||||
const value = await dbStr(key);
|
||||
if (value !== undefined) out[leaf] = value;
|
||||
}
|
||||
return Object.keys(out).length > 0 ? out : undefined;
|
||||
}
|
||||
|
||||
const dbMultimodal = await dbBool('embedding_multimodal');
|
||||
const dbMultimodalModel = await dbStr('embedding_multimodal_model');
|
||||
const dbOcr = await dbBool('embedding_image_ocr');
|
||||
const dbOcrModel = await dbStr('embedding_image_ocr_model');
|
||||
const dbProviderBaseUrls = await dbPrefixMap('provider_base_urls.');
|
||||
// v0.36 (D7) — embedding-column registry merge. Stored as JSON string in
|
||||
// the config table. Parse + shape-check here; full registry validation
|
||||
// (regex on keys, type/dim/provider field shapes) runs in the resolver at
|
||||
@@ -685,6 +708,15 @@ export async function loadConfigWithEngine(
|
||||
if (merged.embedding_image_ocr_model === undefined && dbOcrModel !== undefined) {
|
||||
merged.embedding_image_ocr_model = dbOcrModel;
|
||||
}
|
||||
if (dbProviderBaseUrls !== undefined) {
|
||||
const next = { ...(merged.provider_base_urls ?? {}) };
|
||||
for (const [providerId, baseUrl] of Object.entries(dbProviderBaseUrls)) {
|
||||
if (next[providerId] === undefined) next[providerId] = baseUrl;
|
||||
}
|
||||
if (Object.keys(next).length > 0) {
|
||||
merged.provider_base_urls = next;
|
||||
}
|
||||
}
|
||||
if (merged.embedding_columns === undefined && dbEmbeddingColumns !== undefined) {
|
||||
try {
|
||||
const parsed = JSON.parse(dbEmbeddingColumns);
|
||||
|
||||
@@ -45,7 +45,6 @@ import { embedBatch } from './embedding.ts';
|
||||
import { resolveContextualRetrievalMode } from './contextual-retrieval-resolver.ts';
|
||||
import {
|
||||
buildContextualPrefix,
|
||||
extractFirstTwoSentences,
|
||||
modeRequiresHaiku,
|
||||
modeRequiresWrapper,
|
||||
sanitizeTitle,
|
||||
@@ -54,12 +53,11 @@ import {
|
||||
import {
|
||||
generatePerChunkSynopsis,
|
||||
SYNOPSIS_PROMPT_VERSION,
|
||||
SYNOPSIS_DOC_MAX_CHARS,
|
||||
type GeneratePerChunkSynopsisResult,
|
||||
} from './page-summary.ts';
|
||||
import {
|
||||
logSynopsisFailure,
|
||||
type SynopsisFailureKind,
|
||||
} from './audit-synopsis.ts';
|
||||
import type { SynopsisFailureKind } from './audit-synopsis.ts';
|
||||
import { runSlidingPool } from './worker-pool.ts';
|
||||
import type { BrainEngine } from './engine.ts';
|
||||
import type { ChunkInput, CRMode, Page } from './types.ts';
|
||||
import type { SourceRow } from './sources-ops.ts';
|
||||
@@ -72,6 +70,24 @@ import type { SourceRow } from './sources-ops.ts';
|
||||
* corpus_generation hash.
|
||||
*/
|
||||
export const TITLE_WRAPPER_VERSION = 1;
|
||||
const DEFAULT_HAIKU_MODEL = 'anthropic:claude-haiku-4-5-20251001';
|
||||
export const DEFAULT_CONTEXTUAL_CHUNK_CONCURRENCY = 4;
|
||||
export const MAX_CONTEXTUAL_CHUNK_CONCURRENCY = 16;
|
||||
|
||||
export function resolveContextualChunkConcurrency(
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
): number {
|
||||
const raw = env.GBRAIN_CONTEXTUAL_CHUNK_CONCURRENCY;
|
||||
if (raw === undefined || raw.trim() === '') return DEFAULT_CONTEXTUAL_CHUNK_CONCURRENCY;
|
||||
const n = Number(raw);
|
||||
if (!Number.isFinite(n)) return DEFAULT_CONTEXTUAL_CHUNK_CONCURRENCY;
|
||||
return clampContextualChunkConcurrency(n);
|
||||
}
|
||||
|
||||
function clampContextualChunkConcurrency(n: number): number {
|
||||
if (!Number.isFinite(n)) return DEFAULT_CONTEXTUAL_CHUNK_CONCURRENCY;
|
||||
return Math.max(1, Math.min(MAX_CONTEXTUAL_CHUNK_CONCURRENCY, Math.trunc(n)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Embedding model placeholder. The actual model name lands here from
|
||||
@@ -103,8 +119,17 @@ function getEmbeddingModelTag(): string {
|
||||
export function computeCorpusGeneration(args: {
|
||||
crMode: CRMode;
|
||||
haikuModel: string;
|
||||
/**
|
||||
* Resolved `SYNOPSIS_DOC_MAX_CHARS` for per_chunk_synopsis runs. When
|
||||
* present, folded into the hash so changes to
|
||||
* `GBRAIN_SYNOPSIS_DOC_MAX_CHARS` invalidate the prior cache cleanly.
|
||||
* Omit for `crMode !== 'per_chunk_synopsis'` — title / none modes
|
||||
* don't consult the cap and the field stays out of the hash for
|
||||
* back-compat with pre-cap embeddings.
|
||||
*/
|
||||
synopsisDocMaxChars?: number;
|
||||
}): string {
|
||||
return createHash('sha256')
|
||||
const h = createHash('sha256')
|
||||
.update(args.crMode)
|
||||
.update('|')
|
||||
.update(String(SYNOPSIS_PROMPT_VERSION))
|
||||
@@ -113,9 +138,11 @@ export function computeCorpusGeneration(args: {
|
||||
.update('|')
|
||||
.update(String(TITLE_WRAPPER_VERSION))
|
||||
.update('|')
|
||||
.update(getEmbeddingModelTag())
|
||||
.digest('hex')
|
||||
.slice(0, 16);
|
||||
.update(getEmbeddingModelTag());
|
||||
if (args.synopsisDocMaxChars !== undefined) {
|
||||
h.update('|doc_cap=').update(String(args.synopsisDocMaxChars));
|
||||
}
|
||||
return h.digest('hex').slice(0, 16);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -196,12 +223,16 @@ export interface ReembedPageArgs {
|
||||
* src/core/minions/rate-leases.ts here; inline callers (import-file,
|
||||
* reindex command) pass undefined and rely on gateway-level retry.
|
||||
*/
|
||||
acquireSynopsisLease?: () => Promise<void>;
|
||||
releaseSynopsisLease?: () => Promise<void>;
|
||||
acquireSynopsisLease?: () => Promise<unknown>;
|
||||
releaseSynopsisLease?: (lease?: unknown) => Promise<void>;
|
||||
/**
|
||||
* Intra-page per-chunk synopsis concurrency. 1 preserves the legacy
|
||||
* sequential loop exactly; higher values only parallelize Haiku synopsis
|
||||
* calls. Embedding remains one batch after all synopses succeed.
|
||||
*/
|
||||
chunkConcurrency?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_HAIKU_MODEL = 'anthropic:claude-haiku-4-5-20251001';
|
||||
|
||||
/**
|
||||
* Re-embed one page through the active CR mode. Implements the D26 P0-2
|
||||
* two-phase build pattern.
|
||||
@@ -253,7 +284,11 @@ export async function reembedPageWithContextualRetrieval(
|
||||
args.pageSlug,
|
||||
args.sourceId,
|
||||
resolution.mode,
|
||||
computeCorpusGeneration({ crMode: resolution.mode, haikuModel: args.haikuModel ?? DEFAULT_HAIKU_MODEL }),
|
||||
computeCorpusGeneration({
|
||||
crMode: resolution.mode,
|
||||
haikuModel: args.haikuModel ?? DEFAULT_HAIKU_MODEL,
|
||||
synopsisDocMaxChars: resolution.mode === 'per_chunk_synopsis' ? SYNOPSIS_DOC_MAX_CHARS : undefined,
|
||||
}),
|
||||
);
|
||||
return { kind: 'skipped', reason: 'no_chunks' };
|
||||
}
|
||||
@@ -282,6 +317,7 @@ export async function reembedPageWithContextualRetrieval(
|
||||
const corpus_generation = computeCorpusGeneration({
|
||||
crMode: attemptMode,
|
||||
haikuModel,
|
||||
synopsisDocMaxChars: attemptMode === 'per_chunk_synopsis' ? SYNOPSIS_DOC_MAX_CHARS : undefined,
|
||||
});
|
||||
|
||||
// ── PHASE 2: single DB transaction ───────────────────────────
|
||||
@@ -415,82 +451,41 @@ async function tryBuildPhase1(opts: {
|
||||
}
|
||||
|
||||
// per_chunk_synopsis path. Read source text via fallback chain,
|
||||
// generate synopsis per chunk sequentially within this page (D10),
|
||||
// generate synopsis per chunk through a bounded sliding pool, then
|
||||
// batch embed at the end (D27 P2-2).
|
||||
const sourceText = readSourceTextWithFallback(page, chunks);
|
||||
const wrappedTexts: string[] = [];
|
||||
const wrappedTexts: string[] = new Array(chunks.length);
|
||||
const chunkConcurrency = clampContextualChunkConcurrency(
|
||||
args.chunkConcurrency ?? resolveContextualChunkConcurrency(),
|
||||
);
|
||||
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
const c = chunks[i];
|
||||
|
||||
// Code chunks always bypass the wrapper (D20-T4) — pass through.
|
||||
if (c.chunk_source === 'fenced_code') {
|
||||
wrappedTexts.push(c.chunk_text);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Acquire rate-lease per chunk (D26 P0-3). Inline callers pass no
|
||||
// hooks; only the Minion handler wires through rate-leases.ts.
|
||||
if (args.acquireSynopsisLease) {
|
||||
await args.acquireSynopsisLease();
|
||||
}
|
||||
|
||||
let synopsisResult: GeneratePerChunkSynopsisResult;
|
||||
try {
|
||||
synopsisResult = await generatePerChunkSynopsis({
|
||||
documentText: sourceText,
|
||||
chunkText: c.chunk_text,
|
||||
pageTitle: page.title,
|
||||
pageSlug: args.pageSlug,
|
||||
sourceId: args.sourceId,
|
||||
chunkIndex: c.chunk_index,
|
||||
model: haikuModel,
|
||||
abortSignal: args.abortSignal,
|
||||
const poolResult = await runSlidingPool({
|
||||
items: chunks,
|
||||
workers: chunkConcurrency,
|
||||
signal: args.abortSignal,
|
||||
onError: 'abort',
|
||||
failureLabel: (c) => String(c.chunk_index),
|
||||
onItem: async (c, i) => {
|
||||
wrappedTexts[i] = await buildWrappedChunkText({
|
||||
chunk: c,
|
||||
sourceText,
|
||||
safeTitle,
|
||||
page,
|
||||
args,
|
||||
haikuModel,
|
||||
});
|
||||
} finally {
|
||||
if (args.releaseSynopsisLease) {
|
||||
try {
|
||||
await args.releaseSynopsisLease();
|
||||
} catch {
|
||||
// Lease release failure shouldn't abort the page; surfacing it
|
||||
// would race with the synopsis result. Audit-only.
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (synopsisResult.kind === 'success') {
|
||||
const prefix = buildContextualPrefix(safeTitle, synopsisResult.synopsis);
|
||||
wrappedTexts.push(
|
||||
wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source),
|
||||
);
|
||||
continue;
|
||||
if (poolResult.failures.length > 0) {
|
||||
const failure = [...poolResult.failures].sort((a, b) => a.idx - b.idx)[0].error;
|
||||
if (failure instanceof ChunkSynopsisPhase1Error) {
|
||||
return failure.result;
|
||||
}
|
||||
|
||||
// Failure classification per D27 P1-2:
|
||||
// refusal | empty | malformed → page-level fall-back to title-only
|
||||
// auth_failure → permanent (won't fix with retry)
|
||||
// rate_limit | timeout | network | provider_5xx → transient
|
||||
// source_missing → walked into fallback already; would be 'malformed'
|
||||
// from generatePerChunkSynopsis if we ever propagated it here
|
||||
if (
|
||||
synopsisResult.kind === 'refusal' ||
|
||||
synopsisResult.kind === 'empty' ||
|
||||
synopsisResult.kind === 'malformed'
|
||||
) {
|
||||
return { kind: 'page_level_fallback_requested', cause: synopsisResult.kind };
|
||||
}
|
||||
if (synopsisResult.kind === 'auth_failure') {
|
||||
return {
|
||||
kind: 'permanent',
|
||||
cause: synopsisResult.kind,
|
||||
detail: synopsisResult.detail ?? 'auth failure',
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: 'transient',
|
||||
cause: synopsisResult.kind,
|
||||
detail: synopsisResult.detail ?? 'transient',
|
||||
};
|
||||
throw failure;
|
||||
}
|
||||
if (poolResult.aborted || args.abortSignal?.aborted) {
|
||||
return { kind: 'transient', cause: 'timeout', detail: 'aborted' };
|
||||
}
|
||||
|
||||
// All chunks synthesized successfully. Single batch embed (D27 P2-2).
|
||||
@@ -511,6 +506,113 @@ async function tryBuildPhase1(opts: {
|
||||
}
|
||||
}
|
||||
|
||||
class ChunkSynopsisPhase1Error extends Error {
|
||||
constructor(readonly result: Exclude<Phase1Result, Phase1Success>) {
|
||||
super(`chunk synopsis failed: ${result.kind}`);
|
||||
this.name = 'ChunkSynopsisPhase1Error';
|
||||
}
|
||||
}
|
||||
|
||||
async function buildWrappedChunkText(opts: {
|
||||
chunk: ChunkInput;
|
||||
sourceText: string;
|
||||
safeTitle: string;
|
||||
page: Page;
|
||||
args: ReembedPageArgs;
|
||||
haikuModel: string;
|
||||
}): Promise<string> {
|
||||
const { chunk: c, sourceText, safeTitle, page, args, haikuModel } = opts;
|
||||
|
||||
// Code chunks always bypass the wrapper (D20-T4) — pass through.
|
||||
if (c.chunk_source === 'fenced_code') {
|
||||
return c.chunk_text;
|
||||
}
|
||||
|
||||
// Acquire rate-lease per chunk (D26 P0-3). Inline callers pass no
|
||||
// hooks; only the Minion handler wires through rate-leases.ts.
|
||||
let lease: unknown;
|
||||
let leaseAcquired = false;
|
||||
let synopsisResult: GeneratePerChunkSynopsisResult;
|
||||
try {
|
||||
if (args.acquireSynopsisLease) {
|
||||
try {
|
||||
lease = await args.acquireSynopsisLease();
|
||||
} catch (err) {
|
||||
if (args.abortSignal?.aborted || isAbortError(err)) {
|
||||
throw new ChunkSynopsisPhase1Error({
|
||||
kind: 'transient',
|
||||
cause: 'timeout',
|
||||
detail: 'aborted',
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
leaseAcquired = true;
|
||||
}
|
||||
synopsisResult = await generatePerChunkSynopsis({
|
||||
documentText: sourceText,
|
||||
chunkText: c.chunk_text,
|
||||
pageTitle: page.title,
|
||||
pageSlug: args.pageSlug,
|
||||
sourceId: args.sourceId,
|
||||
chunkIndex: c.chunk_index,
|
||||
model: haikuModel,
|
||||
abortSignal: args.abortSignal,
|
||||
});
|
||||
} finally {
|
||||
if (leaseAcquired && args.releaseSynopsisLease) {
|
||||
try {
|
||||
await args.releaseSynopsisLease(lease);
|
||||
} catch {
|
||||
// Lease release failure shouldn't abort the page; surfacing it
|
||||
// would race with the synopsis result. Audit-only.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (synopsisResult.kind === 'success') {
|
||||
const prefix = buildContextualPrefix(safeTitle, synopsisResult.synopsis);
|
||||
return wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source);
|
||||
}
|
||||
|
||||
// Failure classification per D27 P1-2:
|
||||
// refusal | empty | malformed → page-level fall-back to title-only
|
||||
// auth_failure → permanent (won't fix with retry)
|
||||
// rate_limit | timeout | network | provider_5xx → transient
|
||||
// source_missing → walked into fallback already; would be 'malformed'
|
||||
// from generatePerChunkSynopsis if we ever propagated it here
|
||||
if (
|
||||
synopsisResult.kind === 'refusal' ||
|
||||
synopsisResult.kind === 'empty' ||
|
||||
synopsisResult.kind === 'malformed'
|
||||
) {
|
||||
throw new ChunkSynopsisPhase1Error({
|
||||
kind: 'page_level_fallback_requested',
|
||||
cause: synopsisResult.kind,
|
||||
});
|
||||
}
|
||||
if (synopsisResult.kind === 'auth_failure') {
|
||||
throw new ChunkSynopsisPhase1Error({
|
||||
kind: 'permanent',
|
||||
cause: synopsisResult.kind,
|
||||
detail: synopsisResult.detail ?? 'auth failure',
|
||||
});
|
||||
}
|
||||
throw new ChunkSynopsisPhase1Error({
|
||||
kind: 'transient',
|
||||
cause: synopsisResult.kind,
|
||||
detail: synopsisResult.detail ?? 'transient',
|
||||
});
|
||||
}
|
||||
|
||||
function isAbortError(err: unknown): boolean {
|
||||
return (
|
||||
typeof err === 'object' &&
|
||||
err !== null &&
|
||||
(err as { name?: unknown }).name === 'AbortError'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Source-text fallback chain per D11:
|
||||
* 1. read page.source_path from disk (truest "document")
|
||||
|
||||
@@ -101,21 +101,20 @@ export async function runNightlyQualityProbe(deps: NightlyProbeDeps): Promise<Ni
|
||||
return { outcome: 'disabled', exit_code: 0, detail: 'feature flag off' };
|
||||
}
|
||||
|
||||
// 24h rate limit — skip + audit "rate_limited".
|
||||
// 24h rate limit — skip quietly (no audit row).
|
||||
// #3064: gate only on events from ATTEMPTED runs. The skip path used to log
|
||||
// its own 'rate_limited' audit row, and autopilot ticks every ~5 min — each
|
||||
// skip re-armed the 24h window, so the probe ran exactly once and then
|
||||
// self-muted forever. Filter defends against historical skip rows already
|
||||
// sitting in the audit files of pre-fix brains.
|
||||
const now = deps.now();
|
||||
const recent = readRecentQualityProbeEvents(2, now); // 2-day window is enough for 24h check
|
||||
const decision = shouldRunNightly(now, recent);
|
||||
const decision = shouldRunNightly(now, recent.filter((e) => e.outcome !== 'rate_limited'));
|
||||
if (!decision.run) {
|
||||
logQualityProbeEvent({
|
||||
outcome: 'rate_limited',
|
||||
exit_code: 0,
|
||||
pass_count: 0,
|
||||
fail_count: 0,
|
||||
inconclusive_count: 0,
|
||||
error_count: 0,
|
||||
est_cost_usd: 0,
|
||||
detail: 'already ran within 24h window',
|
||||
});
|
||||
// #3064: do NOT log an audit row here. Autopilot ticks every ~5 min, so
|
||||
// the skip fires ~288x/day between real runs — logging each one spammed
|
||||
// the audit JSONL and permanently tripped doctor's
|
||||
// nightly_quality_probe_health warn (rate_limited counts as non-PASS).
|
||||
return { outcome: 'rate_limited', exit_code: 0, detail: 'already ran within 24h' };
|
||||
}
|
||||
|
||||
|
||||
@@ -1218,11 +1218,21 @@ export interface BrainEngine {
|
||||
*
|
||||
* Uses the `%` trigram operator (GIN-indexed) + the standard `similarity()`
|
||||
* function. Both engines support pg_trgm (PGLite 0.3+, Postgres always).
|
||||
*
|
||||
* `sourceId` constrains the search to a single source and filters out
|
||||
* soft-deleted pages. Mirrors the same filters `tryFuzzyMatch` in
|
||||
* `src/core/entities/resolve.ts` got via #1436 (v0.41.13.0). Omit for the
|
||||
* historical unscoped behavior — live-mode callers that already know
|
||||
* the source should pass it to avoid cross-source slug suggestions that
|
||||
* get silently dropped at the FK filter downstream. Batch-mode callers
|
||||
* (e.g. `gbrain extract`) intentionally omit it to build a cross-source
|
||||
* resolution map.
|
||||
*/
|
||||
findByTitleFuzzy(
|
||||
name: string,
|
||||
dirPrefix?: string,
|
||||
minSimilarity?: number,
|
||||
sourceId?: string,
|
||||
): Promise<{ slug: string; similarity: number } | null>;
|
||||
/**
|
||||
* v0.34.1 (#861 — P0 leak seal): `opts.sourceId` / `opts.sourceIds`
|
||||
|
||||
@@ -34,11 +34,12 @@
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, appendFileSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
import type { BrainEngine, NewFact, FactVisibility } from '../engine.ts';
|
||||
import { resolvePageFilePath } from '../markdown.ts';
|
||||
import { withPageLock } from '../page-lock.ts';
|
||||
import { isWriteTargetContained } from '../path-confine.ts';
|
||||
import { gbrainPath } from '../config.ts';
|
||||
import { upsertFactRow, parseFactsFence } from '../facts-fence.ts';
|
||||
import { extractFactsFromFenceText } from './extract-from-fence.ts';
|
||||
@@ -172,17 +173,75 @@ export async function writeFactsToFence(
|
||||
// the put_page write-through and dream-cycle reverse-render compute. The
|
||||
// bare join wrote main-source fences to the repo ROOT (the default source's
|
||||
// tree), polluting ~/brain with stray root-level fence files.
|
||||
const filePath = resolvePageFilePath(target.localPath, target.slug, target.sourceId);
|
||||
const tmpPath = `${filePath}.tmp`;
|
||||
let filePath = resolvePageFilePath(target.localPath, target.slug, target.sourceId);
|
||||
|
||||
return withPageLock(
|
||||
target.slug,
|
||||
async () => {
|
||||
// 1. Read existing body or stub-create.
|
||||
let body: string;
|
||||
let body: string | null = null;
|
||||
if (existsSync(filePath)) {
|
||||
body = readFileSync(filePath, 'utf-8');
|
||||
} else {
|
||||
// #3069: the slug-derived path missed, but the page may still exist
|
||||
// on disk under a different basename — vault files like
|
||||
// `10-people/First Last.md` import with slug `10-people/first-last`,
|
||||
// so `<root>/<slug>.md` doesn't exist even though the page does.
|
||||
// Stub-creating next to the real file (a) duplicates the page and
|
||||
// (b) restarts fence row_num at 1 on the empty stub, colliding with
|
||||
// the real page's existing DB rows on idx_facts_fence_key. Resolve
|
||||
// via the page row (sync stamps source_path + import_filename)
|
||||
// before concluding the page doesn't exist.
|
||||
let pageRow: { source_path: string | null; import_filename: string | null } | null = null;
|
||||
try {
|
||||
const rows = await engine.executeRaw<{ source_path: string | null; import_filename: string | null }>(
|
||||
`SELECT source_path, import_filename FROM pages WHERE slug = $1 AND source_id = $2 AND deleted_at IS NULL LIMIT 1`,
|
||||
[target.slug, target.sourceId],
|
||||
);
|
||||
pageRow = rows[0] ?? null;
|
||||
} catch {
|
||||
// Lookup failed (pre-migration schema, transient) — fall through
|
||||
// to the pre-#3069 stub path rather than dropping the facts.
|
||||
}
|
||||
if (pageRow !== null) {
|
||||
const candidates: string[] = [];
|
||||
if (pageRow.source_path) {
|
||||
candidates.push(join(target.localPath!, pageRow.source_path));
|
||||
}
|
||||
if (pageRow.import_filename) {
|
||||
const name = pageRow.import_filename.endsWith('.md')
|
||||
? pageRow.import_filename
|
||||
: `${pageRow.import_filename}.md`;
|
||||
candidates.push(join(dirname(filePath), name));
|
||||
}
|
||||
// Containment guard (same threat class write-through covers with
|
||||
// isWriteTargetContained, #1647-slug): source_path/import_filename
|
||||
// come from the DB, not from a validated slug — a hostile or
|
||||
// corrupt page row with `../` must not steer the fence write (read
|
||||
// + rename-over) outside the source tree.
|
||||
const hit = candidates.find(
|
||||
(c) => isWriteTargetContained(c, target.localPath!) && existsSync(c),
|
||||
);
|
||||
if (hit !== undefined) {
|
||||
filePath = hit;
|
||||
body = readFileSync(filePath, 'utf-8');
|
||||
} else {
|
||||
// A page row exists but its backing file can't be located.
|
||||
// Refuse to stub-create (the empty stub's fence would restart
|
||||
// row_num at 1 → unique violation against the row's existing
|
||||
// facts, and a later sync would import the stub OVER the real
|
||||
// page content). Route to the legacy DB-only path instead so
|
||||
// the facts aren't dropped.
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(
|
||||
`[facts] page row exists for slug=${target.slug} (source=${target.sourceId}) but its backing file was not found on disk — refusing to stub-create a duplicate page; routing to legacy DB-only path.`,
|
||||
);
|
||||
return { inserted: 0, ids: [], stubGuardBlocked: true };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (body === null) {
|
||||
// No page row for this slug — genuinely new entity page.
|
||||
// Stub-creation guard. Phantom entity pages at the brain root were
|
||||
// being spawned when resolveEntitySlug fell through to a bare
|
||||
// slugify because pg_trgm scored too low on short bare names. The
|
||||
@@ -238,6 +297,7 @@ export async function writeFactsToFence(
|
||||
}
|
||||
|
||||
// 3. Atomic write: .tmp first, then parse-validate, then rename.
|
||||
const tmpPath = `${filePath}.tmp`;
|
||||
writeFileSync(tmpPath, body, 'utf-8');
|
||||
|
||||
// 4. Parse-before-rename: re-read the .tmp content and verify the
|
||||
|
||||
@@ -36,7 +36,7 @@ import {
|
||||
} from './embedding-context.ts';
|
||||
import { loadSearchModeConfig, resolveSearchMode } from './search/mode.ts';
|
||||
import { normalizeAliasList } from './search/alias-normalize.ts';
|
||||
import { isUndefinedTableError, warnOncePerProcess } from './utils.ts';
|
||||
import { isUndefinedTableError, validateSlug, warnOncePerProcess } from './utils.ts';
|
||||
import { computeCorpusGeneration } from './contextual-retrieval-service.ts';
|
||||
import { runGuardrails } from './guardrails.ts';
|
||||
|
||||
@@ -314,6 +314,7 @@ export async function importFromContent(
|
||||
};
|
||||
}
|
||||
|
||||
slug = validateSlug(slug);
|
||||
const parsed = parseMarkdown(content, slug + '.md', { activePack: opts.activePack });
|
||||
|
||||
// v0.42 (#1699 trust boundary): strip gate-owned markers from UNTRUSTED
|
||||
@@ -733,6 +734,11 @@ export async function importFromContent(
|
||||
: computeCorpusGeneration({
|
||||
crMode: effectiveCRMode,
|
||||
haikuModel: 'anthropic:claude-haiku-4-5-20251001',
|
||||
// Inline import-file path never uses per_chunk_synopsis (refuses
|
||||
// upstream); pass undefined so the doc-cap field stays out of
|
||||
// the hash here. Per_chunk_synopsis runs through the Minion
|
||||
// backfill handler which threads SYNOPSIS_DOC_MAX_CHARS through
|
||||
// the service layer.
|
||||
});
|
||||
|
||||
// Transaction wraps all DB writes. Every per-page tx call carries the
|
||||
|
||||
@@ -489,7 +489,22 @@ export async function extractPageLinks(
|
||||
// text inside `[[...]]` before any `|`), NOT the display alias
|
||||
// (ref.name = match[2]). `[[struktura|the project]]` must resolve
|
||||
// `struktura`, not "the project". The display text is for context only.
|
||||
const matches = await resolver.resolveBasenameMatches(ref.slug);
|
||||
//
|
||||
// The literal may be path-qualified (`[[notes/struktura]]`). The FS
|
||||
// path (resolveSlugAll) strips the dirname before its basename lookup,
|
||||
// but this path passed the raw literal to an index keyed by final
|
||||
// segments only — so every slash-containing wikilink outside
|
||||
// DIR_PATTERN silently resolved to nothing. Query by the final
|
||||
// segment, then use the written path as a disambiguation filter
|
||||
// (the analogue of the FS ancestor walk honoring the written path):
|
||||
// a match must end with the literal, so `[[notes/struktura]]` can
|
||||
// resolve to `vault/notes/struktura` but never to `wiki/struktura`.
|
||||
const slashIdx = ref.slug.lastIndexOf('/');
|
||||
const basename = slashIdx === -1 ? ref.slug : ref.slug.slice(slashIdx + 1);
|
||||
let matches = await resolver.resolveBasenameMatches(basename);
|
||||
if (slashIdx !== -1) {
|
||||
matches = matches.filter(m => m === ref.slug || m.endsWith(`/${ref.slug}`));
|
||||
}
|
||||
if (matches.length === 0) continue;
|
||||
const idx = content.indexOf(ref.slug);
|
||||
const context = idx >= 0 ? excerpt(content, idx, 240) : ref.name;
|
||||
@@ -965,10 +980,14 @@ export function makeResolver(
|
||||
|
||||
// Step 3: pg_trgm fuzzy title match — both modes. Tries each hint in
|
||||
// order; first hint with a ≥0.55 similarity match wins. If no hints,
|
||||
// try the whole pages table.
|
||||
// try the whole pages table. When opts.sourceId is set, the fuzzy
|
||||
// search is constrained to that source (and skips soft-deleted pages)
|
||||
// so cross-source slug suggestions don't get silently dropped at the
|
||||
// FK filter downstream. Mirrors the same scope fix `tryFuzzyMatch` got
|
||||
// via #1436.
|
||||
const searchHints = hints.length > 0 ? hints : [undefined];
|
||||
for (const hint of searchHints) {
|
||||
const match = await engine.findByTitleFuzzy(trimmed, hint, 0.55);
|
||||
const match = await engine.findByTitleFuzzy(trimmed, hint, 0.55, opts.sourceId);
|
||||
if (match) {
|
||||
cache.set(cacheKey, match.slug);
|
||||
return match.slug;
|
||||
|
||||
@@ -40,6 +40,7 @@ import { UnrecoverableError } from '../types.ts';
|
||||
import type { BrainEngine } from '../../engine.ts';
|
||||
import {
|
||||
reembedPageWithContextualRetrieval,
|
||||
resolveContextualChunkConcurrency,
|
||||
type ReembedPageResult,
|
||||
} from '../../contextual-retrieval-service.ts';
|
||||
import {
|
||||
@@ -132,7 +133,7 @@ export function makeContextualReindexHandler(opts: MakeContextualReindexHandlerO
|
||||
// call inside the service acquires/releases a lease against the
|
||||
// shared key across all worker processes.
|
||||
const maxConcurrent = resolveMaxConcurrent();
|
||||
let currentLeaseId: number | null = null;
|
||||
const chunkConcurrency = resolveContextualChunkConcurrency();
|
||||
|
||||
const result: ReembedPageResult = await reembedPageWithContextualRetrieval({
|
||||
engine,
|
||||
@@ -141,32 +142,32 @@ export function makeContextualReindexHandler(opts: MakeContextualReindexHandlerO
|
||||
globalMode,
|
||||
killSwitchDisabled,
|
||||
abortSignal: ctx.signal,
|
||||
chunkConcurrency,
|
||||
acquireSynopsisLease: async () => {
|
||||
// Poll-acquire with brief backoff. The service's per-chunk loop
|
||||
// is sequential within a page; this guards against the cross-
|
||||
// worker pile-up.
|
||||
// is bounded within a page; this guards against the cross-worker
|
||||
// pile-up and remains the global rate governor.
|
||||
let attempts = 0;
|
||||
const maxAttempts = 60; // ~1 min max wait per chunk before giving up
|
||||
while (attempts < maxAttempts) {
|
||||
if (ctx.signal.aborted) throw abortError();
|
||||
const res = await acquireLease(engine, RATE_LEASE_KEY, ctx.id, maxConcurrent, {
|
||||
ttlMs: 60_000,
|
||||
});
|
||||
if (res.acquired && res.leaseId != null) {
|
||||
currentLeaseId = res.leaseId;
|
||||
return;
|
||||
return res.leaseId;
|
||||
}
|
||||
attempts++;
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
await sleepWithAbort(1000, ctx.signal);
|
||||
}
|
||||
throw new Error(
|
||||
`Failed to acquire ${RATE_LEASE_KEY} lease after ${maxAttempts} attempts; ` +
|
||||
`Haiku rate limit pile-up too deep.`,
|
||||
);
|
||||
},
|
||||
releaseSynopsisLease: async () => {
|
||||
if (currentLeaseId != null) {
|
||||
await releaseLease(engine, currentLeaseId);
|
||||
currentLeaseId = null;
|
||||
releaseSynopsisLease: async (lease) => {
|
||||
if (typeof lease === 'number') {
|
||||
await releaseLease(engine, lease);
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -218,6 +219,26 @@ async function tryLoadPageAcrossSources(
|
||||
return null;
|
||||
}
|
||||
|
||||
function sleepWithAbort(ms: number, signal: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal.aborted) {
|
||||
reject(abortError());
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(resolve, ms);
|
||||
signal.addEventListener('abort', () => {
|
||||
clearTimeout(timer);
|
||||
reject(abortError());
|
||||
}, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
function abortError(): Error {
|
||||
const err = new Error('aborted');
|
||||
err.name = 'AbortError';
|
||||
return err;
|
||||
}
|
||||
|
||||
function classifyResult(
|
||||
pageSlug: string,
|
||||
result: ReembedPageResult,
|
||||
|
||||
@@ -87,6 +87,11 @@ function walkMarkdownAndMdxFiles(
|
||||
for (const entry of entries) {
|
||||
if (truncated) return;
|
||||
if (entry.startsWith('.')) continue;
|
||||
// Skip heavy non-content dirs so the walk doesn't exhaust the time
|
||||
// budget on dependency/build trees (node_modules can be 50k+ files
|
||||
// with zero .md). These are never gbrain page sources.
|
||||
if (entry === 'node_modules' || entry === 'dist' || entry === 'build' ||
|
||||
entry === '.next' || entry === 'vendor' || entry === 'target') continue;
|
||||
const full = join(d, entry);
|
||||
let isDir = false;
|
||||
try {
|
||||
@@ -95,6 +100,9 @@ function walkMarkdownAndMdxFiles(
|
||||
continue;
|
||||
}
|
||||
if (isDir) {
|
||||
// Time check on directory descent too, so a deep dependency-free
|
||||
// tree still respects the deadline even before any .md is found.
|
||||
if (Date.now() >= deadlineMs) { truncated = true; return; }
|
||||
walk(full);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ export interface AgentClientBindings {
|
||||
* `redirect_uri` containing `,`) would be parsed by Postgres as MULTIPLE
|
||||
* array elements, smuggling values past validation. See CSO finding #5.
|
||||
*/
|
||||
export function pgArray(arr: string[]): string {
|
||||
function pgArray(arr: string[]): string {
|
||||
if (!arr || arr.length === 0) return '{}';
|
||||
const escaped = arr.map(s => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`);
|
||||
return `{${escaped.join(',')}}`;
|
||||
|
||||
@@ -1153,7 +1153,11 @@ async function runAutoLink(
|
||||
|
||||
// Live-mode resolver: per-put throwaway cache, pg_trgm + optional search.
|
||||
// Issue #972 (codex [P1]): pass sourceId so basename resolution stays
|
||||
// within this page's source — no cross-source basename edges.
|
||||
// within this page's source — no cross-source basename edges. Also scopes
|
||||
// the fuzzy fallback (findByTitleFuzzy) to the same source the put_page is
|
||||
// targeting — without it, cross-source slug suggestions get silently dropped
|
||||
// at the FK filter and the link looks like it failed to resolve. Twin of
|
||||
// #1436's `tryFuzzyMatch` fix.
|
||||
const resolver = makeResolver(engine, { mode: 'live', sourceId: opts?.sourceId });
|
||||
// Issue #972: opt-in bare-wikilink basename resolution. Off by default.
|
||||
const globalBasename = await isGlobalBasenameEnabled(engine);
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* Shared orphan-reporting exclusion policy.
|
||||
*
|
||||
* These are pages where "no inbound links" is expected and should not count
|
||||
* against health. Keep this in core so the CLI orphan report and engine health
|
||||
* dashboard cannot drift.
|
||||
*
|
||||
* Defaults are GBrain-wide conventions only. Brain-specific exclusions
|
||||
* (private folder names, one-off fixture slugs) belong in the brain's own
|
||||
* config, not here:
|
||||
*
|
||||
* gbrain config set orphans.exclude_prefixes "my-private-folder/,archive/"
|
||||
* gbrain config set orphans.exclude_slugs "some-one-off-page"
|
||||
*/
|
||||
|
||||
const AUTO_SUFFIX_PATTERNS = ['/_index', '/log'];
|
||||
|
||||
const PSEUDO_SLUGS = new Set(['_atlas', '_index', '_stats', '_orphans', '_scratch', 'claude']);
|
||||
|
||||
const RAW_SEGMENT = '/raw/';
|
||||
|
||||
const DENY_PREFIXES = [
|
||||
'output/',
|
||||
'dashboards/',
|
||||
'scripts/',
|
||||
'templates/',
|
||||
'_templates/',
|
||||
'openclaw/config/',
|
||||
'extracts/',
|
||||
];
|
||||
|
||||
const FIRST_SEGMENT_EXCLUSIONS = new Set([
|
||||
'scratch',
|
||||
'thoughts',
|
||||
'catalog',
|
||||
'entities',
|
||||
'raw',
|
||||
'atoms',
|
||||
'skills',
|
||||
'dreaming',
|
||||
'daily',
|
||||
]);
|
||||
|
||||
const ROOT_DATE_SLUG = /^\d{4}-\d{2}-\d{2}(?:-.+)?$/;
|
||||
|
||||
function isAgentWorkspaceConvention(slug: string): boolean {
|
||||
if (!slug.startsWith('agents/')) return false;
|
||||
if (slug.includes('/memory/dreaming/')) return true;
|
||||
return /^agents\/[^/]+\/(?:agents|identity|soul|tools|user|heartbeat|dreams|dormant)$/.test(slug);
|
||||
}
|
||||
|
||||
/** Per-brain additions to the convention defaults (from config). */
|
||||
export interface OrphanPolicyOverrides {
|
||||
excludePrefixes?: string[];
|
||||
excludeSlugs?: string[];
|
||||
}
|
||||
|
||||
/** Config keys for per-brain orphan exclusions (comma-separated values). */
|
||||
export const ORPHAN_EXCLUDE_PREFIXES_KEY = 'orphans.exclude_prefixes';
|
||||
export const ORPHAN_EXCLUDE_SLUGS_KEY = 'orphans.exclude_slugs';
|
||||
|
||||
function parseList(value: string | null): string[] {
|
||||
if (!value) return [];
|
||||
return value.split(',').map(s => s.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load per-brain orphan exclusions from the brain config table. Callers with
|
||||
* an engine in hand (getHealth, `gbrain orphans`) pass the result as the
|
||||
* second argument to shouldExcludeFromOrphanReporting.
|
||||
*/
|
||||
export async function loadOrphanPolicyOverrides(
|
||||
engine: { getConfig(key: string): Promise<string | null> },
|
||||
): Promise<OrphanPolicyOverrides> {
|
||||
const [prefixes, slugs] = await Promise.all([
|
||||
engine.getConfig(ORPHAN_EXCLUDE_PREFIXES_KEY),
|
||||
engine.getConfig(ORPHAN_EXCLUDE_SLUGS_KEY),
|
||||
]);
|
||||
return { excludePrefixes: parseList(prefixes), excludeSlugs: parseList(slugs) };
|
||||
}
|
||||
|
||||
export function shouldExcludeFromOrphanReporting(
|
||||
slug: string,
|
||||
overrides?: OrphanPolicyOverrides,
|
||||
): boolean {
|
||||
if (PSEUDO_SLUGS.has(slug)) return true;
|
||||
|
||||
for (const suffix of AUTO_SUFFIX_PATTERNS) {
|
||||
if (slug.endsWith(suffix)) return true;
|
||||
}
|
||||
|
||||
if (slug.includes(RAW_SEGMENT)) return true;
|
||||
if (slug.includes('/daily/')) return true;
|
||||
|
||||
for (const prefix of DENY_PREFIXES) {
|
||||
if (slug.startsWith(prefix)) return true;
|
||||
}
|
||||
|
||||
const firstSegment = slug.split('/')[0];
|
||||
if (FIRST_SEGMENT_EXCLUSIONS.has(firstSegment)) return true;
|
||||
|
||||
if (ROOT_DATE_SLUG.test(slug)) return true;
|
||||
|
||||
if (slug.startsWith('_brain-')) return true;
|
||||
|
||||
if (isAgentWorkspaceConvention(slug)) return true;
|
||||
|
||||
if (overrides) {
|
||||
if (overrides.excludeSlugs?.includes(slug)) return true;
|
||||
for (const prefix of overrides.excludePrefixes ?? []) {
|
||||
if (slug.startsWith(prefix)) return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -44,6 +44,33 @@ const HAIKU_MAX_TOKENS = 200;
|
||||
/** Default model when caller doesn't override. Resolves through the gateway. */
|
||||
const DEFAULT_SYNOPSIS_MODEL = 'anthropic:claude-haiku-4-5-20251001';
|
||||
|
||||
/**
|
||||
* Hard cap on `documentText` length (chars) before send.
|
||||
*
|
||||
* 2026-05-25 fix wave: small local chat models (Gemma 4 E2B, Qwen3 4B) get
|
||||
* dramatically slower on long contexts even with 131K-token windows declared.
|
||||
* A 73K-char page synopsis on Gemma 4 E2B takes 60-120s, exceeding the
|
||||
* worker's default 30s `lockDuration` and tripping `lock-lost` errors.
|
||||
*
|
||||
* Truncate to a budget that fits a small model's effective throughput while
|
||||
* preserving enough document context for the synopsis to be useful. Truncates
|
||||
* the TAIL because the head (title, frontmatter, intro) carries the
|
||||
* document-level anchor the synopsis needs.
|
||||
*
|
||||
* Override per workload via `GBRAIN_SYNOPSIS_DOC_MAX_CHARS`. Default 32768
|
||||
* (~8K tokens at 4 chars/tok) keeps small-model synopsis under ~30s.
|
||||
* Anthropic Haiku is unaffected at this cap; bump higher when running
|
||||
* frontier models if you want richer document anchoring.
|
||||
*/
|
||||
export const SYNOPSIS_DOC_MAX_CHARS = (() => {
|
||||
const env = process.env.GBRAIN_SYNOPSIS_DOC_MAX_CHARS;
|
||||
if (env && /^\d+$/.test(env)) {
|
||||
const n = parseInt(env, 10);
|
||||
if (n >= 512 && n <= 1_048_576) return n;
|
||||
}
|
||||
return 32768;
|
||||
})();
|
||||
|
||||
/**
|
||||
* Synopsis prompt version. Folded into corpus_generation so prompt edits
|
||||
* invalidate prior embeddings via the v0.40.3.0 query_cache.page_generations
|
||||
@@ -188,11 +215,19 @@ function buildUserPrompt(
|
||||
documentText: string,
|
||||
chunkText: string,
|
||||
): string {
|
||||
// Tail-truncate `documentText` to `SYNOPSIS_DOC_MAX_CHARS` so small local
|
||||
// chat models don't stall on >100KB pages. Head preserved (title block,
|
||||
// frontmatter, intro paragraphs carry the document-level anchor).
|
||||
let trimmedDoc = documentText;
|
||||
if (documentText.length > SYNOPSIS_DOC_MAX_CHARS) {
|
||||
trimmedDoc = documentText.slice(0, SYNOPSIS_DOC_MAX_CHARS) +
|
||||
`\n\n[... ${documentText.length - SYNOPSIS_DOC_MAX_CHARS} chars truncated for synopsis budget ...]`;
|
||||
}
|
||||
return [
|
||||
`<page_title>${pageTitle}</page_title>`,
|
||||
'',
|
||||
'<full_document>',
|
||||
documentText,
|
||||
trimmedDoc,
|
||||
'</full_document>',
|
||||
'',
|
||||
'<chunk>',
|
||||
|
||||
+76
-30
@@ -57,6 +57,8 @@ import { finalizeLastSeen } from './chronicle/last-seen.ts';
|
||||
import { computeAnomaliesFromBuckets } from './cycle/anomaly.ts';
|
||||
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
|
||||
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildRecencyComponentSql, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery } from './search/sql-ranking.ts';
|
||||
import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';
|
||||
import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';
|
||||
import {
|
||||
normalizeEngineColumn,
|
||||
buildVectorCastFragment,
|
||||
@@ -1058,6 +1060,16 @@ export class PGLiteEngine implements BrainEngine {
|
||||
RETURNING id, source_id, slug, type, title, compiled_truth, timeline, frontmatter, content_hash, created_at, updated_at, effective_date, effective_date_source, import_filename, source_kind, source_uri, ingested_via, ingested_at`,
|
||||
[sourceId, slug, page.type, pageKind, page.title, page.compiled_truth, page.timeline || '', JSON.stringify(frontmatter), hash, effectiveDate, effectiveDateSource, importFilename, chunkerVersion, sourcePath, sourceKind, sourceUri, ingestedVia, ingestedAt]
|
||||
);
|
||||
// PGLite can return zero rows from INSERT ... ON CONFLICT DO UPDATE ...
|
||||
// RETURNING in no-op/trigger edge cases, which made rowToPage(undefined)
|
||||
// throw "undefined is not an object (evaluating 'row.deleted_at')" and
|
||||
// skip the file during sync. The row WAS written, so re-read instead of
|
||||
// crashing.
|
||||
if (rows.length === 0) {
|
||||
const reread = await this.getPage(slug, { sourceId });
|
||||
if (reread) return reread;
|
||||
throw new Error(`putPage: RETURNING produced no row for ${sourceId}/${slug}`);
|
||||
}
|
||||
return rowToPage(rows[0] as Record<string, unknown>);
|
||||
}
|
||||
|
||||
@@ -2322,6 +2334,10 @@ export class PGLiteEngine implements BrainEngine {
|
||||
// v0.40.3.0 D24 NULL→non-NULL race fix mirrors postgres-engine.ts. Two writers
|
||||
// racing on the same chunk previously raced last-write-wins; the fix lets the
|
||||
// fresher `embedded_at` win in the text-unchanged branch.
|
||||
//
|
||||
// Code-chunk metadata columns follow the same chunk_text-gated CASE pattern as `embedding`
|
||||
// (#769). Re-chunk trusts EXCLUDED outright; pure re-embed COALESCEs so a caller carrying
|
||||
// only embedding-shaped fields doesn't clobber metadata to NULL.
|
||||
await this.db.query(
|
||||
`INSERT INTO content_chunks ${cols} VALUES ${rowParts.join(', ')}
|
||||
ON CONFLICT (page_id, chunk_index) DO UPDATE SET
|
||||
@@ -2345,14 +2361,14 @@ export class PGLiteEngine implements BrainEngine {
|
||||
THEN EXCLUDED.embedded_at
|
||||
ELSE content_chunks.embedded_at
|
||||
END,
|
||||
language = EXCLUDED.language,
|
||||
symbol_name = EXCLUDED.symbol_name,
|
||||
symbol_type = EXCLUDED.symbol_type,
|
||||
start_line = EXCLUDED.start_line,
|
||||
end_line = EXCLUDED.end_line,
|
||||
parent_symbol_path = EXCLUDED.parent_symbol_path,
|
||||
doc_comment = EXCLUDED.doc_comment,
|
||||
symbol_name_qualified = EXCLUDED.symbol_name_qualified,
|
||||
language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END,
|
||||
symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END,
|
||||
symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END,
|
||||
start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END,
|
||||
end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END,
|
||||
parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END,
|
||||
doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END,
|
||||
symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END,
|
||||
modality = EXCLUDED.modality,
|
||||
embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)`,
|
||||
params
|
||||
@@ -2906,22 +2922,41 @@ export class PGLiteEngine implements BrainEngine {
|
||||
name: string,
|
||||
dirPrefix?: string,
|
||||
minSimilarity: number = 0.55,
|
||||
sourceId?: string,
|
||||
): Promise<{ slug: string; similarity: number } | null> {
|
||||
// Inline threshold comparison instead of `SET LOCAL pg_trgm.similarity_threshold`.
|
||||
// The GUC only scopes to the current transaction and pglite auto-commits each
|
||||
// .query() call, so the SET LOCAL would be a no-op. Using similarity() >= $N
|
||||
// directly gives predictable behavior. Tie-breaker: sort by slug so re-runs
|
||||
// pick the same winner.
|
||||
//
|
||||
// `sourceId` + `deleted_at IS NULL` mirror the filters `tryFuzzyMatch` in
|
||||
// `src/core/entities/resolve.ts` got via #1436 (v0.41.13.0). Without them,
|
||||
// fuzzy resolution could suggest cross-source slugs that the caller then
|
||||
// silently drops at the FK filter — making it look like the match failed
|
||||
// when in fact it picked the wrong page.
|
||||
const prefixPattern = dirPrefix ? `${dirPrefix}/%` : '%';
|
||||
const { rows } = await this.db.query(
|
||||
`SELECT slug, similarity(title, $1) AS sim
|
||||
FROM pages
|
||||
WHERE similarity(title, $1) >= $3
|
||||
AND slug LIKE $2
|
||||
ORDER BY sim DESC, slug ASC
|
||||
LIMIT 1`,
|
||||
[name, prefixPattern, minSimilarity]
|
||||
);
|
||||
const { rows } = sourceId
|
||||
? await this.db.query(
|
||||
`SELECT slug, similarity(title, $1) AS sim
|
||||
FROM pages
|
||||
WHERE similarity(title, $1) >= $3
|
||||
AND slug LIKE $2
|
||||
AND source_id = $4
|
||||
AND deleted_at IS NULL
|
||||
ORDER BY sim DESC, slug ASC
|
||||
LIMIT 1`,
|
||||
[name, prefixPattern, minSimilarity, sourceId]
|
||||
)
|
||||
: await this.db.query(
|
||||
`SELECT slug, similarity(title, $1) AS sim
|
||||
FROM pages
|
||||
WHERE similarity(title, $1) >= $3
|
||||
AND slug LIKE $2
|
||||
ORDER BY sim DESC, slug ASC
|
||||
LIMIT 1`,
|
||||
[name, prefixPattern, minSimilarity]
|
||||
);
|
||||
if (rows.length === 0) return null;
|
||||
const row = rows[0] as { slug: string; sim: number };
|
||||
return { slug: row.slug, similarity: row.sim };
|
||||
@@ -5201,21 +5236,16 @@ export class PGLiteEngine implements BrainEngine {
|
||||
// dashboard, v0.10.3 metrics give entity-page-level granularity.
|
||||
const { rows: [h] } = await this.db.query(`
|
||||
WITH entity_pages AS (
|
||||
SELECT id, slug FROM pages WHERE type IN ('person', 'company')
|
||||
SELECT id, slug FROM pages WHERE type IN ('entity', 'person', 'company')
|
||||
)
|
||||
SELECT
|
||||
(SELECT count(*) FROM pages) as page_count,
|
||||
(SELECT count(*) FROM content_chunks WHERE embedded_at IS NOT NULL)::float /
|
||||
GREATEST((SELECT count(*) FROM content_chunks), 1)::float as embed_coverage,
|
||||
(SELECT count(*) FROM pages p
|
||||
WHERE p.updated_at < (SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id)
|
||||
) as stale_pages,
|
||||
-- Bug 11 — orphan = islanded (no inbound AND no outbound).
|
||||
-- See BrainHealth.orphan_pages docstring; docs updated to match this.
|
||||
(SELECT count(*) FROM pages p
|
||||
WHERE NOT EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)
|
||||
AND NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id)
|
||||
) as orphan_pages,
|
||||
0 as stale_pages,
|
||||
-- Bug 11 — orphan = islanded (no inbound AND no outbound). The raw
|
||||
-- list is filtered in TS using the shared orphan-reporting policy.
|
||||
0 as orphan_pages,
|
||||
(SELECT count(*) FROM links l
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id = l.to_page_id)
|
||||
) as dead_links,
|
||||
@@ -5235,15 +5265,25 @@ export class PGLiteEngine implements BrainEngine {
|
||||
SELECT p.slug,
|
||||
(SELECT count(*) FROM links l WHERE l.from_page_id = p.id OR l.to_page_id = p.id)::int as link_count
|
||||
FROM pages p
|
||||
WHERE p.type IN ('person', 'company')
|
||||
WHERE p.type IN ('entity', 'person', 'company')
|
||||
ORDER BY link_count DESC
|
||||
LIMIT 5
|
||||
`);
|
||||
|
||||
const { rows: islandedRows } = await this.db.query(`
|
||||
SELECT p.slug
|
||||
FROM pages p
|
||||
WHERE NOT EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)
|
||||
AND NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id)
|
||||
`);
|
||||
|
||||
const r = h as Record<string, unknown>;
|
||||
const pageCount = Number(r.page_count);
|
||||
const embedCoverage = Number(r.embed_coverage);
|
||||
const orphanPages = Number(r.orphan_pages);
|
||||
const stalePages = await this.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS });
|
||||
const orphanOverrides = await loadOrphanPolicyOverrides(this);
|
||||
const orphanPages = (islandedRows as { slug: string }[])
|
||||
.filter(row => !shouldExcludeFromOrphanReporting(row.slug, orphanOverrides)).length;
|
||||
const deadLinks = Number(r.dead_links);
|
||||
const linkCount = Number(r.link_count);
|
||||
const pagesWithTimeline = Number(r.pages_with_timeline);
|
||||
@@ -5271,7 +5311,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
return {
|
||||
page_count: pageCount,
|
||||
embed_coverage: embedCoverage,
|
||||
stale_pages: Number(r.stale_pages),
|
||||
stale_pages: stalePages,
|
||||
orphan_pages: orphanPages,
|
||||
missing_embeddings: Number(r.missing_embeddings),
|
||||
brain_score: brainScore,
|
||||
@@ -5826,6 +5866,11 @@ export class PGLiteEngine implements BrainEngine {
|
||||
params.push(escaped);
|
||||
prefixCondition = `AND p.slug LIKE $${params.length} ESCAPE '\\'`;
|
||||
}
|
||||
// TIM-37: exclude briefing pages from their own Brain Pulse. See the
|
||||
// matching block in postgres-engine.ts getRecentSalience() for context.
|
||||
const excludeBriefings = !(slugPrefix && slugPrefix.startsWith('briefings'))
|
||||
? `AND p.slug NOT LIKE 'briefings/%'`
|
||||
: '';
|
||||
params.push(limit);
|
||||
const limitParam = `$${params.length}`;
|
||||
|
||||
@@ -5861,6 +5906,7 @@ export class PGLiteEngine implements BrainEngine {
|
||||
LEFT JOIN takes t ON t.page_id = p.id AND t.active = TRUE
|
||||
WHERE GREATEST(p.updated_at, COALESCE(p.salience_touched_at, p.updated_at)) >= $1::timestamptz
|
||||
${prefixCondition}
|
||||
${excludeBriefings}
|
||||
GROUP BY p.id
|
||||
ORDER BY score DESC
|
||||
LIMIT ${limitParam}`,
|
||||
|
||||
+31
-16
@@ -108,6 +108,35 @@ function isProcessAlive(pid: number): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function formatLockTimestamp(value: unknown): string {
|
||||
return typeof value === 'number' && Number.isFinite(value)
|
||||
? new Date(value).toISOString()
|
||||
: 'unknown time';
|
||||
}
|
||||
|
||||
function pgliteLockTimeoutError(lockDir: string): Error {
|
||||
const lockPath = join(lockDir, LOCK_FILE);
|
||||
try {
|
||||
const lockData = JSON.parse(readFileSync(lockPath, 'utf-8'));
|
||||
const pid = String(lockData.pid ?? 'unknown');
|
||||
const command = String(lockData.command ?? 'unknown');
|
||||
const serveHint = command.includes('gbrain serve')
|
||||
? ' The holder looks like `gbrain serve`, so this is probably serve↔sync contention from an MCP/HTTP server; stop that server/client and rerun the command.'
|
||||
: '';
|
||||
|
||||
return new Error(
|
||||
`GBrain: Timed out waiting for PGLite data-dir lock. Process ${pid} has held it since ${formatLockTimestamp(lockData.acquired_at)} (command: ${command}). ` +
|
||||
`Lock directory: ${lockDir}. If that process is dead, remove the lock directory and try again. ` +
|
||||
`This is a PGLite data-dir lock, not the \`gbrain-sync:*\` advisory lock; \`gbrain sync --break-lock\` will not clear a live PGLite holder.` +
|
||||
serveHint,
|
||||
);
|
||||
} catch {
|
||||
return new Error(
|
||||
`GBrain: Timed out waiting for PGLite lock. Remove ${lockDir} and try again.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to acquire an exclusive lock on the PGLite data directory.
|
||||
* Returns { acquired: true } if the lock was obtained, { acquired: false } otherwise.
|
||||
@@ -177,28 +206,14 @@ export async function acquireLock(dataDir: string | undefined, opts?: { timeoutM
|
||||
// mkdir failed — someone else grabbed it between our check and mkdir
|
||||
// This is fine, we'll retry
|
||||
if (Date.now() - startTime >= timeoutMs) {
|
||||
// Timeout — report which process holds the lock
|
||||
const lockPath = join(lockDir, LOCK_FILE);
|
||||
try {
|
||||
const lockData = JSON.parse(readFileSync(lockPath, 'utf-8'));
|
||||
throw new Error(
|
||||
`GBrain: Timed out waiting for PGLite lock. Process ${lockData.pid} has held it since ${new Date(lockData.acquired_at).toISOString()} (command: ${lockData.command}). ` +
|
||||
`If that process is dead, remove ${lockDir} and try again.`
|
||||
);
|
||||
} catch (readErr) {
|
||||
if (readErr instanceof Error && readErr.message.startsWith('GBrain')) throw readErr;
|
||||
throw new Error(
|
||||
`GBrain: Timed out waiting for PGLite lock. Remove ${lockDir} and try again.`
|
||||
);
|
||||
}
|
||||
throw pgliteLockTimeoutError(lockDir);
|
||||
}
|
||||
// Brief wait before retry
|
||||
await new Promise(r => setTimeout(r, 500));
|
||||
}
|
||||
}
|
||||
|
||||
// Should not reach here, but just in case
|
||||
throw new Error(`GBrain: Timed out waiting for PGLite lock.`);
|
||||
throw pgliteLockTimeoutError(lockDir);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+70
-32
@@ -67,6 +67,8 @@ import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
|
||||
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildRecencyComponentSql, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery } from './search/sql-ranking.ts';
|
||||
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
|
||||
import { DELETE_BATCH_SIZE } from './engine-constants.ts';
|
||||
import { shouldExcludeFromOrphanReporting, loadOrphanPolicyOverrides } from './orphan-policy.ts';
|
||||
import { LINK_EXTRACTOR_VERSION_TS } from './link-extraction.ts';
|
||||
|
||||
function escapeSqlStringLiteral(value: string): string {
|
||||
return value.replace(/'/g, "''");
|
||||
@@ -2473,6 +2475,13 @@ export class PostgresEngine implements BrainEngine {
|
||||
// - new is fresher (embedded_at > existing.embedded_at) → take new
|
||||
// - otherwise → keep existing (slower writer with stale embedding loses)
|
||||
// Mirrored in pglite-engine.ts; pinned by test/e2e/concurrent-embed-race.test.ts.
|
||||
//
|
||||
// Code-chunk metadata columns (language / symbol_name / symbol_type / line range /
|
||||
// parent_symbol_path / doc_comment / symbol_name_qualified) follow the SAME chunk_text-gated
|
||||
// CASE pattern as `embedding` (#769). Re-chunk (chunk_text changed) trusts EXCLUDED outright;
|
||||
// pure re-embed (chunk_text unchanged) COALESCEs so a caller that only carries embedding
|
||||
// doesn't clobber metadata to NULL. Without this, every embed --stale pass nuked code-def's
|
||||
// primary index for thousands of chunks at once.
|
||||
await sql.unsafe(
|
||||
`INSERT INTO content_chunks ${cols} VALUES ${rows.join(', ')}
|
||||
ON CONFLICT (page_id, chunk_index) DO UPDATE SET
|
||||
@@ -2496,14 +2505,14 @@ export class PostgresEngine implements BrainEngine {
|
||||
THEN EXCLUDED.embedded_at
|
||||
ELSE content_chunks.embedded_at
|
||||
END,
|
||||
language = EXCLUDED.language,
|
||||
symbol_name = EXCLUDED.symbol_name,
|
||||
symbol_type = EXCLUDED.symbol_type,
|
||||
start_line = EXCLUDED.start_line,
|
||||
end_line = EXCLUDED.end_line,
|
||||
parent_symbol_path = EXCLUDED.parent_symbol_path,
|
||||
doc_comment = EXCLUDED.doc_comment,
|
||||
symbol_name_qualified = EXCLUDED.symbol_name_qualified,
|
||||
language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END,
|
||||
symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END,
|
||||
symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END,
|
||||
start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END,
|
||||
end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END,
|
||||
parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END,
|
||||
doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END,
|
||||
symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END,
|
||||
modality = EXCLUDED.modality,
|
||||
embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)`,
|
||||
params as Parameters<typeof sql.unsafe>[1],
|
||||
@@ -3073,6 +3082,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
name: string,
|
||||
dirPrefix?: string,
|
||||
minSimilarity: number = 0.55,
|
||||
sourceId?: string,
|
||||
): Promise<{ slug: string; similarity: number } | null> {
|
||||
const sql = this.sql;
|
||||
// Use the `similarity()` function directly with an explicit threshold
|
||||
@@ -3085,15 +3095,33 @@ export class PostgresEngine implements BrainEngine {
|
||||
// Tie-breaker: sort by slug after similarity so re-runs return the
|
||||
// same winner when multiple pages score equally (prevents churn
|
||||
// in put_page auto-link reconciliation).
|
||||
//
|
||||
// `sourceId` + `deleted_at IS NULL` mirror the filters `tryFuzzyMatch`
|
||||
// in `src/core/entities/resolve.ts` got via #1436 (v0.41.13.0). Without
|
||||
// them, fuzzy resolution could suggest cross-source slugs that the
|
||||
// caller then silently drops at the FK filter in
|
||||
// `operations.ts:reconcileLinks` (the `allSlugs` filter) — making it
|
||||
// look like the match failed when in fact it picked the wrong page.
|
||||
const prefixPattern = dirPrefix ? `${dirPrefix}/%` : '%';
|
||||
const rows = await sql`
|
||||
SELECT slug, similarity(title, ${name}) AS sim
|
||||
FROM pages
|
||||
WHERE similarity(title, ${name}) >= ${minSimilarity}
|
||||
AND slug LIKE ${prefixPattern}
|
||||
ORDER BY sim DESC, slug ASC
|
||||
LIMIT 1
|
||||
`;
|
||||
const rows = sourceId
|
||||
? await sql`
|
||||
SELECT slug, similarity(title, ${name}) AS sim
|
||||
FROM pages
|
||||
WHERE similarity(title, ${name}) >= ${minSimilarity}
|
||||
AND slug LIKE ${prefixPattern}
|
||||
AND source_id = ${sourceId}
|
||||
AND deleted_at IS NULL
|
||||
ORDER BY sim DESC, slug ASC
|
||||
LIMIT 1
|
||||
`
|
||||
: await sql`
|
||||
SELECT slug, similarity(title, ${name}) AS sim
|
||||
FROM pages
|
||||
WHERE similarity(title, ${name}) >= ${minSimilarity}
|
||||
AND slug LIKE ${prefixPattern}
|
||||
ORDER BY sim DESC, slug ASC
|
||||
LIMIT 1
|
||||
`;
|
||||
if (rows.length === 0) return null;
|
||||
const row = rows[0] as { slug: string; sim: number };
|
||||
return { slug: row.slug, similarity: row.sim };
|
||||
@@ -5313,26 +5341,19 @@ export class PostgresEngine implements BrainEngine {
|
||||
async getHealth(): Promise<BrainHealth> {
|
||||
const sql = this.sql;
|
||||
// Bug 11 doc-drift fix — orphan_pages means "islanded" (no inbound AND
|
||||
// no outbound links), aligning both engines with the user-facing
|
||||
// definition. The type comment previously said "no inbound" but the
|
||||
// SQL required both — docs now match code so users can trust the
|
||||
// number. A hub page that links out to many but has no back-references
|
||||
// is working as intended, not an orphan.
|
||||
// no outbound links). The raw islanded list is filtered through the same
|
||||
// policy as `gbrain orphans` so convention pages do not count against
|
||||
// dashboard health.
|
||||
const [h] = await sql`
|
||||
WITH entity_pages AS (
|
||||
SELECT id, slug FROM pages WHERE type IN ('person', 'company')
|
||||
SELECT id, slug FROM pages WHERE type IN ('entity', 'person', 'company')
|
||||
)
|
||||
SELECT
|
||||
(SELECT count(*) FROM pages) as page_count,
|
||||
(SELECT count(*) FROM content_chunks WHERE embedded_at IS NOT NULL)::float /
|
||||
GREATEST((SELECT count(*) FROM content_chunks), 1)::float as embed_coverage,
|
||||
(SELECT count(*) FROM pages p
|
||||
WHERE p.updated_at < (SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id)
|
||||
) as stale_pages,
|
||||
(SELECT count(*) FROM pages p
|
||||
WHERE NOT EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)
|
||||
AND NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id)
|
||||
) as orphan_pages,
|
||||
0 as stale_pages,
|
||||
0 as orphan_pages,
|
||||
(SELECT count(*) FROM links l
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id = l.to_page_id)
|
||||
) as dead_links,
|
||||
@@ -5351,14 +5372,23 @@ export class PostgresEngine implements BrainEngine {
|
||||
SELECT p.slug,
|
||||
(SELECT count(*) FROM links l WHERE l.from_page_id = p.id OR l.to_page_id = p.id)::int as link_count
|
||||
FROM pages p
|
||||
WHERE p.type IN ('person', 'company')
|
||||
WHERE p.type IN ('entity', 'person', 'company')
|
||||
ORDER BY link_count DESC
|
||||
LIMIT 5
|
||||
`;
|
||||
|
||||
const islandedRows = await sql<{ slug: string }[]>`
|
||||
SELECT p.slug
|
||||
FROM pages p
|
||||
WHERE NOT EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)
|
||||
AND NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id)
|
||||
`;
|
||||
|
||||
const pageCount = Number(h.page_count);
|
||||
const embedCoverage = Number(h.embed_coverage);
|
||||
const orphanPages = Number(h.orphan_pages);
|
||||
const stalePages = await this.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS });
|
||||
const orphanOverrides = await loadOrphanPolicyOverrides(this);
|
||||
const orphanPages = islandedRows.filter(row => !shouldExcludeFromOrphanReporting(row.slug, orphanOverrides)).length;
|
||||
const deadLinks = Number(h.dead_links);
|
||||
const linkCount = Number(h.link_count);
|
||||
const pagesWithTimeline = Number(h.pages_with_timeline);
|
||||
@@ -5386,7 +5416,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
return {
|
||||
page_count: pageCount,
|
||||
embed_coverage: embedCoverage,
|
||||
stale_pages: Number(h.stale_pages),
|
||||
stale_pages: stalePages,
|
||||
orphan_pages: orphanPages,
|
||||
missing_embeddings: Number(h.missing_embeddings),
|
||||
brain_score: brainScore,
|
||||
@@ -6142,6 +6172,13 @@ export class PostgresEngine implements BrainEngine {
|
||||
const prefixCondition = slugPrefix
|
||||
? sql`AND p.slug LIKE ${slugPrefix.replace(/[\\%_]/g, (c) => '\\' + c) + '%'} ESCAPE '\\'`
|
||||
: sql``;
|
||||
// TIM-37: exclude briefing pages from their own Brain Pulse. The cron
|
||||
// briefing writes to 90_Briefings/, gets re-ingested, and would otherwise
|
||||
// top tomorrow's salience as pure self-reference. Suppress unless the
|
||||
// caller explicitly asked for the briefings/ prefix.
|
||||
const excludeBriefings = !(slugPrefix && slugPrefix.startsWith('briefings'))
|
||||
? sql`AND p.slug NOT LIKE 'briefings/%'`
|
||||
: sql``;
|
||||
// v0.29.1: third score term via buildRecencyComponentSql. Default
|
||||
// 'flat' = v0.29.0 behavior (1 / (1 + days_old)). 'on' opts into the
|
||||
// per-prefix decay map (concepts/ evergreen, daily/ aggressive, etc.).
|
||||
@@ -6175,6 +6212,7 @@ export class PostgresEngine implements BrainEngine {
|
||||
LEFT JOIN takes t ON t.page_id = p.id AND t.active = TRUE
|
||||
WHERE GREATEST(p.updated_at, COALESCE(p.salience_touched_at, p.updated_at)) >= ${boundaryIso}::timestamptz
|
||||
${prefixCondition}
|
||||
${excludeBriefings}
|
||||
GROUP BY p.id
|
||||
ORDER BY score DESC
|
||||
LIMIT ${limit}
|
||||
|
||||
@@ -93,7 +93,13 @@ import { resolveLrSchedule } from './lr-schedule.ts';
|
||||
import { preflight, formatPreflightReport } from './preflight.ts';
|
||||
import { isRejected, loadRejectedBuffer, makeRejectedEntry, saveRejectedBuffer } from './rejected-buffer.ts';
|
||||
import { runReflect, runOneShotRewrite, describeJudges } from './reflect.ts';
|
||||
import { acceptCandidate, bestPath, revertAllPending, skillPath, writeProposed } from './version-store.ts';
|
||||
import {
|
||||
acceptCandidate,
|
||||
proposedPath as proposedFilePath,
|
||||
revertAllPending,
|
||||
skillPath,
|
||||
writeProposed,
|
||||
} from './version-store.ts';
|
||||
import { runValidationGate, scoreSkillOnTasks } from './validate-gate.ts';
|
||||
import { ROLLOUT_SUCCESS_THRESHOLD } from './types.ts';
|
||||
import type { SkillOptOpts, EditOp, RunReceipt, BenchmarkTask } from './types.ts';
|
||||
@@ -702,9 +708,9 @@ async function runOptimizationLoop(
|
||||
// to the catch's assignment values only (it can't prove the async callback ran).
|
||||
const finalOutcome = outcome as 'accepted' | 'no_improvement' | 'aborted' | 'errored';
|
||||
if (!mutateDecision.mutate && finalOutcome === 'accepted') {
|
||||
// best.md was written by writeProposed() in the accept branch (no-mutate
|
||||
// path); it doubles as proposed.md for human review. SKILL.md untouched.
|
||||
proposedPath = bestPath(skillsDir, skillName);
|
||||
// writeProposed() emitted both the best pointer and the stable review
|
||||
// artifact in the accept branch. SKILL.md remains untouched.
|
||||
proposedPath = proposedFilePath(skillsDir, skillName);
|
||||
} else if (mutateDecision.mutate) {
|
||||
mutatedSkillFile = finalOutcome === 'accepted';
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
*
|
||||
* history.json
|
||||
* best.md
|
||||
* proposed.md
|
||||
* versions/
|
||||
* v0001_e1_s1.md
|
||||
* v0002_e1_s2.md
|
||||
@@ -52,6 +53,10 @@ export function bestPath(skillsDir: string, skillName: string): string {
|
||||
return path.join(skilloptDir(skillsDir, skillName), 'best.md');
|
||||
}
|
||||
|
||||
export function proposedPath(skillsDir: string, skillName: string): string {
|
||||
return path.join(skilloptDir(skillsDir, skillName), 'proposed.md');
|
||||
}
|
||||
|
||||
export function skillPath(skillsDir: string, skillName: string): string {
|
||||
return path.join(skillsDir, skillName, 'SKILL.md');
|
||||
}
|
||||
@@ -171,17 +176,18 @@ export function acceptCandidate(input: AcceptInput): AcceptResult {
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the candidate to `best.md` (which doubles as `proposed.md`) WITHOUT
|
||||
* touching SKILL.md or the history ledger. Used by the `--no-mutate` /
|
||||
* bundled-without-allow paths: the optimizer found a better candidate but the
|
||||
* caller opted out of in-place mutation, so we surface it for human review.
|
||||
* Returns the path written. Atomic (.tmp + rename).
|
||||
* Write the candidate to both `best.md` and `proposed.md` WITHOUT touching
|
||||
* SKILL.md or the history ledger. `best.md` remains the optimizer's current
|
||||
* best pointer; `proposed.md` is the stable human-review artifact promised by
|
||||
* `--no-mutate`. Returns the proposal path. Each write is atomic (.tmp + rename).
|
||||
*/
|
||||
export function writeProposed(skillsDir: string, skillName: string, candidateText: string): string {
|
||||
const p = bestPath(skillsDir, skillName);
|
||||
fs.mkdirSync(path.dirname(p), { recursive: true });
|
||||
atomicWrite(p, candidateText);
|
||||
return p;
|
||||
const best = bestPath(skillsDir, skillName);
|
||||
const proposed = proposedPath(skillsDir, skillName);
|
||||
fs.mkdirSync(path.dirname(best), { recursive: true });
|
||||
atomicWrite(best, candidateText);
|
||||
atomicWrite(proposed, candidateText);
|
||||
return proposed;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+35
-1
@@ -553,6 +553,40 @@ export async function runThink(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip a "## Gaps" section from an answer body.
|
||||
*
|
||||
* `think` returns gaps in the structured `gaps` array, which the CLI and the
|
||||
* persisted synthesis page render exactly once. The system prompt also used to
|
||||
* ask for a "Gaps" section inside the answer prose, so a model that still emits
|
||||
* one would make the output show "## Gaps" twice — once from the prose, once
|
||||
* from the structured array. This removes the prose section so the structured
|
||||
* array stays the single source of truth.
|
||||
*
|
||||
* Matches a heading line `## Gaps` (level 2-6, case-insensitive) and removes it
|
||||
* through the next heading of the same-or-higher level, or end of string.
|
||||
* Returns the input unchanged when there is no such section.
|
||||
*/
|
||||
export function stripGapsSection(answer: string): string {
|
||||
if (!answer) return answer;
|
||||
const lines = answer.split('\n');
|
||||
let start = -1;
|
||||
let level = 0;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const m = /^(#{2,6})\s+gaps\s*$/i.exec(lines[i]);
|
||||
if (m) { start = i; level = m[1].length; break; }
|
||||
}
|
||||
if (start === -1) return answer;
|
||||
let end = lines.length;
|
||||
for (let i = start + 1; i < lines.length; i++) {
|
||||
const h = /^(#{1,6})\s+\S/.exec(lines[i]);
|
||||
if (h && h[1].length <= level) { end = i; break; }
|
||||
}
|
||||
const kept = [...lines.slice(0, start), ...lines.slice(end)].join('\n');
|
||||
// Drop trailing blank lines left by removing a trailing section.
|
||||
return kept.replace(/\s+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist a synthesis page + its evidence. Returns the saved slug.
|
||||
* Synthesis pages are written under `synthesis/<slugified-question>-<date>.md`.
|
||||
@@ -582,7 +616,7 @@ export async function persistSynthesis(
|
||||
const body = [
|
||||
`# ${result.question}`,
|
||||
'',
|
||||
result.answer,
|
||||
stripGapsSection(result.answer),
|
||||
'',
|
||||
result.gaps.length > 0 ? '## Gaps\n\n' + result.gaps.map(g => `- ${g}`).join('\n') : '',
|
||||
].filter(Boolean).join('\n');
|
||||
|
||||
@@ -52,19 +52,19 @@ Hard rules:
|
||||
rather than asserting it as established. Confidence is part of the data.
|
||||
- If two takes contradict (different holders, opposite claims), surface BOTH in a "Conflicts"
|
||||
section. Never silently pick one.
|
||||
- If you cannot answer because the brain doesn't contain the relevant data, say so in the
|
||||
"Gaps" section. List the specific missing pieces. Do not make up answers.
|
||||
- If the brain doesn't contain data needed to answer, do NOT make it up. Record each
|
||||
missing piece in the structured "gaps" array (below), not as a section in the answer prose.
|
||||
- Never instruct the user (no "you should" / "I recommend X"). The brain reports; the user decides.
|
||||
- Output MUST be valid JSON matching the schema below. No prose outside JSON.
|
||||
|
||||
Output schema:
|
||||
{
|
||||
"answer": "<markdown body. Inline citations like [slug#row] or [slug]. Sections: Answer, Conflicts (optional), Gaps>",
|
||||
"answer": "<markdown body. Inline citations like [slug#row] or [slug]. Sections: Answer, Conflicts (optional). Do NOT add a Gaps section here — gaps belong in the gaps array.>",
|
||||
"citations": [
|
||||
{"page_slug": "people/alice-example", "row_num": 3, "citation_index": 1},
|
||||
{"page_slug": "companies/acme-example", "row_num": null, "citation_index": 2}
|
||||
],
|
||||
"gaps": ["specific missing data point 1", "specific missing data point 2"]
|
||||
"gaps": ["a specific, self-contained missing-or-stale data point, citing the [slug] where relevant", "another specific gap"]
|
||||
}
|
||||
|
||||
The "row_num" field is required for take citations and MUST be null for page-only citations.`;
|
||||
@@ -83,7 +83,7 @@ export function buildThinkSystemPrompt(opts: ThinkSystemPromptOpts = {}): string
|
||||
lines.push(`\nThis is a temporal question. Order key claims chronologically when it helps the reader.`);
|
||||
}
|
||||
if (opts.willSave) {
|
||||
lines.push(`\nThis synthesis will be persisted as a brain page. Aim for completeness — cover Answer, Conflicts, and Gaps thoroughly.`);
|
||||
lines.push(`\nThis synthesis will be persisted as a brain page. Aim for completeness — cover the Answer and any Conflicts thoroughly, and list every missing piece in the structured "gaps" array.`);
|
||||
}
|
||||
if (opts.withCalibration) {
|
||||
lines.push(
|
||||
@@ -92,7 +92,7 @@ export function buildThinkSystemPrompt(opts: ThinkSystemPromptOpts = {}): string
|
||||
lines.push(`- Name both the user's PRIOR (default reasoning) AND the COUNTER-PRIOR from their hedged-domain self.`);
|
||||
lines.push(`- Reference active bias tags by name when relevant ("this fits the over-confident-geography pattern").`);
|
||||
lines.push(`- Do NOT silently substitute the debiased answer. ALWAYS surface both priors transparently.`);
|
||||
lines.push(`- Track-record sentences belong in a "Calibration" section in the answer body, between Conflicts and Gaps.`);
|
||||
lines.push(`- Track-record sentences belong in a "Calibration" section in the answer body, after the Conflicts section (if present).`);
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ export interface TrajectoryRegression {
|
||||
from_date: string; // YYYY-MM-DD
|
||||
to_value: number;
|
||||
to_date: string;
|
||||
delta_pct: number; // negative for a drop; range typically [-1, 0)
|
||||
delta_pct: number; // negative for a numeric drop; may be < -1 across zero
|
||||
}
|
||||
|
||||
export interface TrajectoryStats {
|
||||
@@ -82,8 +82,10 @@ function cosineSim(a: Float32Array, b: Float32Array): number {
|
||||
*
|
||||
* Iterates per-metric (so trajectories that interleave mrr + arr + team_size
|
||||
* don't trip false regressions across metric boundaries). Within each metric,
|
||||
* walks consecutive value pairs; a pair fires when
|
||||
* `(newer - older) / older <= -threshold`.
|
||||
* walks consecutive value pairs; a pair fires when the newer value is lower
|
||||
* than the older value by at least the threshold. The relative delta uses
|
||||
* `abs(older)` as the denominator so negative-valued metrics (net income,
|
||||
* cash flow, etc.) do not invert improvement and regression.
|
||||
*
|
||||
* Pre-condition: caller passed points sorted by (valid_from ASC, fact_id ASC).
|
||||
* The engine's `findTrajectory` enforces this. No re-sort here.
|
||||
@@ -111,7 +113,7 @@ export function detectRegressions(
|
||||
// Guard against division-by-zero: a metric starting at exactly 0
|
||||
// can't compute a relative delta. Skip.
|
||||
if (oldVal === 0) continue;
|
||||
const delta = (newVal - oldVal) / oldVal;
|
||||
const delta = (newVal - oldVal) / Math.abs(oldVal);
|
||||
if (delta <= -threshold) {
|
||||
out.push({
|
||||
metric,
|
||||
|
||||
@@ -63,25 +63,26 @@ interface PluginCtx {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export function register(api: PluginApi) {
|
||||
api.registerContextEngine(ENGINE_ID, (ctx: PluginCtx) => {
|
||||
const hostResolver =
|
||||
typeof ctx.resolveEntities === 'function'
|
||||
? ctx.resolveEntities
|
||||
: typeof ctx.brainQuery === 'function'
|
||||
? ctx.brainQuery
|
||||
: undefined;
|
||||
return createGBrainContextEngine({
|
||||
workspaceDir: ctx.workspaceDir,
|
||||
resolveEntities: hostResolver,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const entry: PluginEntry = {
|
||||
id: 'gbrain-context-engine',
|
||||
name: 'GBrain Context Engine',
|
||||
description: 'Deterministic temporal/spatial context injection on every turn',
|
||||
|
||||
register(api: PluginApi) {
|
||||
api.registerContextEngine(ENGINE_ID, (ctx: PluginCtx) => {
|
||||
const hostResolver =
|
||||
typeof ctx.resolveEntities === 'function'
|
||||
? ctx.resolveEntities
|
||||
: typeof ctx.brainQuery === 'function'
|
||||
? ctx.brainQuery
|
||||
: undefined;
|
||||
return createGBrainContextEngine({
|
||||
workspaceDir: ctx.workspaceDir,
|
||||
resolveEntities: hostResolver,
|
||||
});
|
||||
});
|
||||
},
|
||||
register,
|
||||
};
|
||||
|
||||
export default entry;
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { resetPgliteState } from './helpers/reset-pglite.ts';
|
||||
import { queryAdminSources } from '../src/commands/serve-http.ts';
|
||||
import { buildSyncStatusReport } from '../src/commands/sync.ts';
|
||||
|
||||
/**
|
||||
* v0.41.29 Sources tab — `/admin/api/sources` endpoint SQL.
|
||||
*
|
||||
* The endpoint is a thin Express handler over `queryAdminSources` +
|
||||
* `buildSyncStatusReport`; the source-selection SQL is the load-bearing
|
||||
* surface (same pattern as test/admin-agents-spend.test.ts).
|
||||
*
|
||||
* Pinned behaviors:
|
||||
* - Excludes archived sources
|
||||
* - INCLUDES sources with null local_path (push-only brains: filtering
|
||||
* on local_path emptied the Sources tab + federation source-picker)
|
||||
* - JSONB config surfaces as an object, defaulting to {}
|
||||
* - Deterministic ORDER BY id
|
||||
* - buildSyncStatusReport accepts the rows (no disk I/O on null paths)
|
||||
*/
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
|
||||
beforeAll(async () => {
|
||||
engine = new PGLiteEngine();
|
||||
await engine.connect({});
|
||||
await engine.initSchema();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await engine.disconnect();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetPgliteState(engine);
|
||||
});
|
||||
|
||||
describe('queryAdminSources (/admin/api/sources SQL)', () => {
|
||||
it('includes push-only sources with null local_path', async () => {
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO sources (id, name, local_path, config)
|
||||
VALUES ('push-only', 'push-only', NULL, '{}'::jsonb)`,
|
||||
);
|
||||
const sources = await queryAdminSources(engine);
|
||||
const ids = sources.map((s) => s.id);
|
||||
expect(ids).toContain('push-only');
|
||||
expect(sources.find((s) => s.id === 'push-only')!.local_path).toBe(null);
|
||||
});
|
||||
|
||||
it('excludes archived sources', async () => {
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO sources (id, name, archived) VALUES ('gone', 'gone', true)`,
|
||||
);
|
||||
const sources = await queryAdminSources(engine);
|
||||
expect(sources.map((s) => s.id)).not.toContain('gone');
|
||||
});
|
||||
|
||||
it('surfaces JSONB config as an object and orders by id', async () => {
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO sources (id, name, config)
|
||||
VALUES ('bbb', 'bbb', '{"syncEnabled": true}'::jsonb),
|
||||
('aaa', 'aaa', '{}'::jsonb)`,
|
||||
);
|
||||
const sources = await queryAdminSources(engine);
|
||||
const ids = sources.map((s) => s.id);
|
||||
expect(ids.indexOf('aaa')).toBeLessThan(ids.indexOf('bbb'));
|
||||
expect(sources.find((s) => s.id === 'bbb')!.config).toEqual({ syncEnabled: true });
|
||||
expect(sources.find((s) => s.id === 'aaa')!.config).toEqual({});
|
||||
});
|
||||
|
||||
it('buildSyncStatusReport accepts the rows (null local_path does not throw)', async () => {
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO sources (id, name, local_path, config)
|
||||
VALUES ('push-only', 'push-only', NULL, '{}'::jsonb)`,
|
||||
);
|
||||
const report = await buildSyncStatusReport(engine, await queryAdminSources(engine));
|
||||
expect(report.schema_version).toBe(1);
|
||||
const row = report.sources.find((s) => s.source_id === 'push-only');
|
||||
expect(row).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
resetGateway,
|
||||
embed,
|
||||
splitByTokenBudget,
|
||||
capBatchItems,
|
||||
isTokenLimitError,
|
||||
__setEmbedTransportForTests,
|
||||
__getShrinkStateForTests,
|
||||
@@ -151,6 +152,41 @@ describe('splitByTokenBudget (pure helper)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('capBatchItems (hard COUNT cap helper)', () => {
|
||||
test('batch at or under the cap is returned as a single batch (no copy of contents)', () => {
|
||||
const texts = ['a', 'b', 'c'];
|
||||
expect(capBatchItems(texts, 3)).toEqual([texts]);
|
||||
expect(capBatchItems(texts, 10)).toEqual([texts]);
|
||||
});
|
||||
|
||||
test('oversized batch splits into chunks of at most maxItems', () => {
|
||||
const texts = Array.from({ length: 100 }, (_, i) => `t${i}`);
|
||||
const result = capBatchItems(texts, 32);
|
||||
expect(result.map(b => b.length)).toEqual([32, 32, 32, 4]);
|
||||
expect(result.every(b => b.length <= 32)).toBe(true);
|
||||
});
|
||||
|
||||
test('exact multiple splits evenly with no trailing empty batch', () => {
|
||||
const texts = Array.from({ length: 64 }, (_, i) => `t${i}`);
|
||||
expect(capBatchItems(texts, 32).map(b => b.length)).toEqual([32, 32]);
|
||||
});
|
||||
|
||||
test('order is preserved across the split (concatenation round-trips)', () => {
|
||||
const texts = Array.from({ length: 70 }, (_, i) => `t${i}`);
|
||||
expect(capBatchItems(texts, 32).flat()).toEqual(texts);
|
||||
});
|
||||
|
||||
test('maxItems <= 0 is a no-op (single batch) — never produces empty/infinite batches', () => {
|
||||
const texts = ['a', 'b', 'c'];
|
||||
expect(capBatchItems(texts, 0)).toEqual([texts]);
|
||||
expect(capBatchItems(texts, -5)).toEqual([texts]);
|
||||
});
|
||||
|
||||
test('empty input returns a single empty batch', () => {
|
||||
expect(capBatchItems([], 32)).toEqual([[]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isTokenLimitError (pure helper)', () => {
|
||||
test('matches Voyage error format', () => {
|
||||
expect(isTokenLimitError(VOYAGE_TOKEN_LIMIT_ERROR)).toBe(true);
|
||||
|
||||
@@ -28,8 +28,8 @@ describe('v0.32 #779: no_batch_cap suppresses the missing-max_batch_tokens warni
|
||||
resetGateway();
|
||||
});
|
||||
|
||||
test('Ollama, LiteLLM, llama-server all declare no_batch_cap: true', () => {
|
||||
for (const id of ['ollama', 'litellm', 'llama-server']) {
|
||||
test('Ollama, LiteLLM declare no_batch_cap: true', () => {
|
||||
for (const id of ['ollama', 'litellm']) {
|
||||
const r = getRecipe(id);
|
||||
expect(r, `${id} not registered`).toBeDefined();
|
||||
expect(
|
||||
@@ -39,6 +39,16 @@ describe('v0.32 #779: no_batch_cap suppresses the missing-max_batch_tokens warni
|
||||
}
|
||||
});
|
||||
|
||||
test('llama-server declares a hard item-count cap (max_batch_items: 32)', () => {
|
||||
// llama.cpp enforces a request-COUNT cap equal to its launch --batch-size
|
||||
// (default 32); declaring max_batch_items both bounds batches AND suppresses
|
||||
// the missing-max_batch_tokens warning. Replaces the prior no_batch_cap flag.
|
||||
const r = getRecipe('llama-server');
|
||||
expect(r, 'llama-server not registered').toBeDefined();
|
||||
expect(r!.touchpoints.embedding?.max_batch_items).toBe(32);
|
||||
expect(r!.touchpoints.embedding?.no_batch_cap).toBeUndefined();
|
||||
});
|
||||
|
||||
test('configureGateway does NOT warn for ollama/litellm/llama-server', () => {
|
||||
warnSpy.mockClear();
|
||||
resetGateway();
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* dashscope-rerank recipe smoke.
|
||||
*
|
||||
* Sibling of recipe-llama-server-reranker.test.ts. Pins the recipe shape so:
|
||||
* - id + tier + implementation + base_url stay byte-stable
|
||||
* - reranker touchpoint declares the PLURAL `/reranks` leaf (the whole
|
||||
* reason this recipe exists — DashScope's compatible-api surface 404s
|
||||
* on singular `/rerank`) + `default_timeout_ms`
|
||||
* - only live-verified models are listed (gte-rerank-v2 is native-API only
|
||||
* and rejected by the OpenAI-compat surface)
|
||||
*/
|
||||
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { getRecipe } from '../../src/core/ai/recipes/index.ts';
|
||||
import { defaultResolveAuth } from '../../src/core/ai/gateway.ts';
|
||||
import { AIConfigError } from '../../src/core/ai/errors.ts';
|
||||
|
||||
describe('recipe: dashscope-rerank', () => {
|
||||
test('registered with expected shape', () => {
|
||||
const r = getRecipe('dashscope-rerank');
|
||||
expect(r).toBeDefined();
|
||||
expect(r!.id).toBe('dashscope-rerank');
|
||||
expect(r!.tier).toBe('openai-compat');
|
||||
expect(r!.implementation).toBe('openai-compatible');
|
||||
expect(r!.base_url_default).toBe(
|
||||
'https://dashscope-intl.aliyuncs.com/compatible-api/v1',
|
||||
);
|
||||
expect(r!.auth_env?.required).toEqual(['DASHSCOPE_API_KEY']);
|
||||
});
|
||||
|
||||
test('declares reranker touchpoint with PLURAL /reranks path + timeout', () => {
|
||||
const r = getRecipe('dashscope-rerank')!;
|
||||
const tp = r.touchpoints.reranker;
|
||||
expect(tp).toBeDefined();
|
||||
expect(tp!.path).toBe('/reranks');
|
||||
expect(tp!.default_timeout_ms).toBe(30_000);
|
||||
expect(tp!.max_payload_bytes).toBe(5_000_000);
|
||||
});
|
||||
|
||||
test('base_url + path concatenation produces /v1/reranks, NOT /v1/v1/…', () => {
|
||||
const r = getRecipe('dashscope-rerank')!;
|
||||
const combined =
|
||||
r.base_url_default!.replace(/\/$/, '') + (r.touchpoints.reranker!.path ?? '/models/rerank');
|
||||
expect(combined).toBe('https://dashscope-intl.aliyuncs.com/compatible-api/v1/reranks');
|
||||
expect(combined).not.toContain('/v1/v1/');
|
||||
expect(combined.endsWith('/reranks')).toBe(true);
|
||||
});
|
||||
|
||||
test('lists only the live-verified compat-surface model', () => {
|
||||
const r = getRecipe('dashscope-rerank')!;
|
||||
const tp = r.touchpoints.reranker!;
|
||||
expect(tp.models).toEqual(['qwen3-rerank']);
|
||||
expect(tp.default_model).toBe('qwen3-rerank');
|
||||
// gte-rerank-v2 is native-API only; the compat surface rejects it.
|
||||
expect(tp.models).not.toContain('gte-rerank-v2');
|
||||
});
|
||||
|
||||
test('default auth: DASHSCOPE_API_KEY set → Bearer token', () => {
|
||||
const r = getRecipe('dashscope-rerank')!;
|
||||
const auth = defaultResolveAuth(
|
||||
r,
|
||||
{ DASHSCOPE_API_KEY: 'sk-dashscope-fake' },
|
||||
'reranker',
|
||||
);
|
||||
expect(auth.headerName).toBe('Authorization');
|
||||
expect(auth.token).toBe('Bearer sk-dashscope-fake');
|
||||
});
|
||||
|
||||
test('default auth: missing DASHSCOPE_API_KEY → AIConfigError', () => {
|
||||
const r = getRecipe('dashscope-rerank')!;
|
||||
expect(() => defaultResolveAuth(r, {}, 'reranker')).toThrow(AIConfigError);
|
||||
});
|
||||
|
||||
test('does not perturb the sibling dashscope embedding recipe', () => {
|
||||
const emb = getRecipe('dashscope')!;
|
||||
expect(emb.base_url_default).toBe('https://dashscope-intl.aliyuncs.com/compatible-mode/v1');
|
||||
expect(emb.touchpoints.reranker).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Ollama Matryoshka dims passthrough.
|
||||
*
|
||||
* Several embedding models served via Ollama (Qwen3-Embedding family) support
|
||||
* Matryoshka truncation through the `dimensions` field on /v1/embeddings.
|
||||
* Without this passthrough, gbrain ignores user-selected reduced dims and the
|
||||
* provider returns its native size, causing dim-mismatch failures against
|
||||
* brains configured for smaller widths.
|
||||
*/
|
||||
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { dimsProviderOptions } from '../../src/core/ai/dims.ts';
|
||||
|
||||
describe('dims: ollama Matryoshka models', () => {
|
||||
test('qwen3-embedding:4b threads dimensions=1536', () => {
|
||||
expect(dimsProviderOptions('openai-compatible', 'qwen3-embedding:4b', 1536))
|
||||
.toEqual({ openaiCompatible: { dimensions: 1536 } });
|
||||
});
|
||||
|
||||
test('qwen3-embedding:0.6b threads dimensions=512', () => {
|
||||
expect(dimsProviderOptions('openai-compatible', 'qwen3-embedding:0.6b', 512))
|
||||
.toEqual({ openaiCompatible: { dimensions: 512 } });
|
||||
});
|
||||
|
||||
test('qwen3-embedding:8b threads dimensions=2048', () => {
|
||||
expect(dimsProviderOptions('openai-compatible', 'qwen3-embedding:8b', 2048))
|
||||
.toEqual({ openaiCompatible: { dimensions: 2048 } });
|
||||
});
|
||||
|
||||
test('bare qwen3-embedding (no quant tag) also recognized', () => {
|
||||
expect(dimsProviderOptions('openai-compatible', 'qwen3-embedding', 1024))
|
||||
.toEqual({ openaiCompatible: { dimensions: 1024 } });
|
||||
});
|
||||
|
||||
test('unrelated openai-compat model returns undefined (regression guard)', () => {
|
||||
expect(dimsProviderOptions('openai-compatible', 'nomic-embed-text', 768))
|
||||
.toBeUndefined();
|
||||
expect(dimsProviderOptions('openai-compatible', 'mxbai-embed-large', 1024))
|
||||
.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,568 +0,0 @@
|
||||
/**
|
||||
* Tests for `gbrain auth grant-read|revoke-read|set-federated-read`.
|
||||
*
|
||||
* Pure helper: parseSourceCsv (no DB).
|
||||
* DB-coupled: resolveClient, assertSourceExists, *Core fns — exercised
|
||||
* against a real PGLite via the canonical block.
|
||||
*/
|
||||
import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:test';
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { resetPgliteState } from './helpers/reset-pglite.ts';
|
||||
import { sqlQueryForEngine } from '../src/core/sql-query.ts';
|
||||
import { pgArray } from '../src/core/oauth-provider.ts';
|
||||
import {
|
||||
parseSourceCsv,
|
||||
resolveClient,
|
||||
assertSourceExists,
|
||||
grantReadCore,
|
||||
revokeReadCore,
|
||||
setFederatedReadCore,
|
||||
extractDryRun,
|
||||
sanitizeForTerminal,
|
||||
} from '../src/commands/auth.ts';
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
|
||||
beforeAll(async () => {
|
||||
engine = new PGLiteEngine();
|
||||
await engine.connect({});
|
||||
await engine.initSchema();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await engine.disconnect();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetPgliteState(engine);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// pure helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('parseSourceCsv', () => {
|
||||
test('splits and trims', () => {
|
||||
expect(parseSourceCsv('a,b,c')).toEqual(['a', 'b', 'c']);
|
||||
expect(parseSourceCsv(' a , b ')).toEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
test('drops empty segments', () => {
|
||||
expect(parseSourceCsv('a,,b,')).toEqual(['a', 'b']);
|
||||
expect(parseSourceCsv(',,')).toEqual([]);
|
||||
expect(parseSourceCsv('')).toEqual([]);
|
||||
});
|
||||
|
||||
test('dedupes while preserving first-seen order', () => {
|
||||
expect(parseSourceCsv('a,b,a,c,b')).toEqual(['a', 'b', 'c']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractDryRun', () => {
|
||||
test('absent flag → false', () => {
|
||||
expect(extractDryRun(['alice', 'proj-x'])).toEqual({
|
||||
dryRun: false,
|
||||
rest: ['alice', 'proj-x'],
|
||||
});
|
||||
});
|
||||
|
||||
test('flag at end', () => {
|
||||
expect(extractDryRun(['alice', 'proj-x', '--dry-run'])).toEqual({
|
||||
dryRun: true,
|
||||
rest: ['alice', 'proj-x'],
|
||||
});
|
||||
});
|
||||
|
||||
test('flag at start', () => {
|
||||
expect(extractDryRun(['--dry-run', 'alice', 'proj-x'])).toEqual({
|
||||
dryRun: true,
|
||||
rest: ['alice', 'proj-x'],
|
||||
});
|
||||
});
|
||||
|
||||
test('flag in middle', () => {
|
||||
expect(extractDryRun(['alice', '--dry-run', 'proj-x'])).toEqual({
|
||||
dryRun: true,
|
||||
rest: ['alice', 'proj-x'],
|
||||
});
|
||||
});
|
||||
|
||||
test('no args', () => {
|
||||
expect(extractDryRun([])).toEqual({ dryRun: false, rest: [] });
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DB-coupled
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function seedSource(id: string): Promise<void> {
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await sql`INSERT INTO sources (id, name) VALUES (${id}, ${id}) ON CONFLICT (id) DO NOTHING`;
|
||||
}
|
||||
|
||||
async function seedClient(name: string, federated: string[] = []): Promise<string> {
|
||||
// Ensure write source FK is satisfied — every seeded client points at 'default'.
|
||||
await seedSource('default');
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const clientId = `gbrain_cl_test_${name}_${Date.now()}_${Math.random().toString(16).slice(2, 8)}`;
|
||||
const fedLit = pgArray(federated);
|
||||
await sql`
|
||||
INSERT INTO oauth_clients (client_id, client_name, client_secret_hash,
|
||||
redirect_uris, grant_types, scope,
|
||||
client_id_issued_at, source_id, federated_read)
|
||||
VALUES (${clientId}, ${name}, ${'dummy-hash'},
|
||||
${pgArray([])}, ${pgArray(['client_credentials'])}, ${'read'},
|
||||
${Date.now()}, ${'default'}, ${fedLit})
|
||||
`;
|
||||
return clientId;
|
||||
}
|
||||
|
||||
async function readFederated(clientId: string): Promise<string[]> {
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const rows = await sql`SELECT federated_read FROM oauth_clients WHERE client_id = ${clientId}`;
|
||||
const fed = rows[0]?.federated_read;
|
||||
return Array.isArray(fed) ? (fed as string[]).map(String) : [];
|
||||
}
|
||||
|
||||
describe('resolveClient', () => {
|
||||
test('matches by client_id', async () => {
|
||||
await seedSource('default');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const c = await resolveClient(sql, id);
|
||||
expect(c.client_name).toBe('alice');
|
||||
expect(c.federated_read).toEqual(['default']);
|
||||
});
|
||||
|
||||
test('matches by client_name', async () => {
|
||||
await seedSource('default');
|
||||
await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const c = await resolveClient(sql, 'alice');
|
||||
expect(c.client_name).toBe('alice');
|
||||
});
|
||||
|
||||
test('errors loudly on no-match', async () => {
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await expect(resolveClient(sql, 'nobody')).rejects.toThrow(/No active OAuth client found/);
|
||||
});
|
||||
|
||||
test('errors loudly on ambiguous client_name', async () => {
|
||||
await seedSource('default');
|
||||
await seedClient('bob', ['default']);
|
||||
await seedClient('bob', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await expect(resolveClient(sql, 'bob')).rejects.toThrow(/Multiple active OAuth clients named/);
|
||||
});
|
||||
|
||||
test('null source_id is preserved as null (legacy row tolerance)', async () => {
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const clientId = `gbrain_cl_test_null_${Date.now()}`;
|
||||
await sql`
|
||||
INSERT INTO oauth_clients (client_id, client_name, client_secret_hash,
|
||||
redirect_uris, grant_types, scope,
|
||||
client_id_issued_at, source_id, federated_read)
|
||||
VALUES (${clientId}, ${'legacy'}, ${'dummy'},
|
||||
${pgArray([])}, ${pgArray(['client_credentials'])}, ${'read'},
|
||||
${Date.now()}, ${null}, ${pgArray([])})
|
||||
`;
|
||||
const c = await resolveClient(sql, clientId);
|
||||
expect(c.source_id).toBeNull();
|
||||
expect(c.federated_read).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('assertSourceExists', () => {
|
||||
test('passes when present', async () => {
|
||||
await seedSource('proj-x');
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await expect(assertSourceExists(sql, 'proj-x')).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test('throws with paste-ready hint when missing', async () => {
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await expect(assertSourceExists(sql, 'ghost')).rejects.toThrow(
|
||||
/Source "ghost" does not exist.*gbrain sources add ghost/s,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('grantReadCore', () => {
|
||||
test('appends when not present and persists', async () => {
|
||||
await seedSource('default');
|
||||
await seedSource('proj-x');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const outcome = await grantReadCore(sql, 'alice', 'proj-x');
|
||||
expect(outcome.kind).toBe('updated');
|
||||
if (outcome.kind === 'updated') {
|
||||
expect(outcome.before).toEqual(['default']);
|
||||
expect(outcome.after).toEqual(['default', 'proj-x']);
|
||||
}
|
||||
expect(await readFederated(id)).toEqual(['default', 'proj-x']);
|
||||
});
|
||||
|
||||
test('is idempotent — second call is a noop, list unchanged', async () => {
|
||||
await seedSource('default');
|
||||
await seedSource('proj-x');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await grantReadCore(sql, 'alice', 'proj-x');
|
||||
const outcome = await grantReadCore(sql, 'alice', 'proj-x');
|
||||
expect(outcome.kind).toBe('noop');
|
||||
if (outcome.kind === 'noop') {
|
||||
expect(outcome.reason).toBe('already-granted');
|
||||
}
|
||||
expect(await readFederated(id)).toEqual(['default', 'proj-x']);
|
||||
});
|
||||
|
||||
test('refuses unknown source (fails BEFORE mutating)', async () => {
|
||||
await seedSource('default');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await expect(grantReadCore(sql, 'alice', 'ghost')).rejects.toThrow(/does not exist/);
|
||||
expect(await readFederated(id)).toEqual(['default']);
|
||||
});
|
||||
|
||||
test('refuses unknown client', async () => {
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await expect(grantReadCore(sql, 'nobody', 'whatever')).rejects.toThrow(/No active OAuth client found/);
|
||||
});
|
||||
|
||||
test('accepts client_id resolution too', async () => {
|
||||
await seedSource('default');
|
||||
await seedSource('proj-x');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await grantReadCore(sql, id, 'proj-x');
|
||||
expect(await readFederated(id)).toEqual(['default', 'proj-x']);
|
||||
});
|
||||
|
||||
test('rejects malformed source_id BEFORE existence check (Codex finding #3)', async () => {
|
||||
await seedSource('default');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
// Even with a row in `sources` having a weird id, the validator at the
|
||||
// boundary refuses. Closes the "manual SQL plants a row, CLI lets it
|
||||
// become unmanageable in federated_read" vector.
|
||||
await sql`INSERT INTO sources (id, name) VALUES (${'has,"weird"-bits'}, ${'weird'})`;
|
||||
await expect(grantReadCore(sql, 'alice', 'has,"weird"-bits')).rejects.toThrow(/Invalid source_id/);
|
||||
// DB unchanged.
|
||||
expect(await readFederated(id)).toEqual(['default']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('revokeReadCore', () => {
|
||||
test('removes when present', async () => {
|
||||
await seedSource('default');
|
||||
await seedSource('proj-x');
|
||||
const id = await seedClient('alice', ['default', 'proj-x']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const outcome = await revokeReadCore(sql, 'alice', 'proj-x');
|
||||
expect(outcome.kind).toBe('updated');
|
||||
expect(await readFederated(id)).toEqual(['default']);
|
||||
});
|
||||
|
||||
test('is idempotent — second call is a noop, list unchanged', async () => {
|
||||
await seedSource('default');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const outcome = await revokeReadCore(sql, 'alice', 'ghost-source');
|
||||
expect(outcome.kind).toBe('noop');
|
||||
if (outcome.kind === 'noop') {
|
||||
expect(outcome.reason).toBe('not-present');
|
||||
}
|
||||
expect(await readFederated(id)).toEqual(['default']);
|
||||
});
|
||||
|
||||
test('allows clearing the list down to empty (no implicit guard)', async () => {
|
||||
await seedSource('default');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await revokeReadCore(sql, 'alice', 'default');
|
||||
expect(await readFederated(id)).toEqual([]);
|
||||
});
|
||||
|
||||
test('does NOT validate the source exists — operator may revoke stale references', async () => {
|
||||
await seedSource('default');
|
||||
// federated_read carries 'proj-x' but the source row was deleted.
|
||||
const id = await seedClient('alice', ['default', 'proj-x']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const outcome = await revokeReadCore(sql, 'alice', 'proj-x');
|
||||
expect(outcome.kind).toBe('updated');
|
||||
expect(await readFederated(id)).toEqual(['default']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setFederatedReadCore', () => {
|
||||
test('replaces list wholesale', async () => {
|
||||
await seedSource('a');
|
||||
await seedSource('b');
|
||||
await seedSource('c');
|
||||
const id = await seedClient('alice', ['a']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const outcome = await setFederatedReadCore(sql, 'alice', 'b,c');
|
||||
expect(outcome.kind).toBe('updated');
|
||||
expect(await readFederated(id)).toEqual(['b', 'c']);
|
||||
});
|
||||
|
||||
test('dedupes CSV input', async () => {
|
||||
await seedSource('a');
|
||||
await seedSource('b');
|
||||
const id = await seedClient('alice', []);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await setFederatedReadCore(sql, 'alice', 'a,b,a,b,a');
|
||||
expect(await readFederated(id)).toEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
test('empty string clears the list', async () => {
|
||||
await seedSource('a');
|
||||
const id = await seedClient('alice', ['a']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await setFederatedReadCore(sql, 'alice', '');
|
||||
expect(await readFederated(id)).toEqual([]);
|
||||
});
|
||||
|
||||
test('noop when result equals current list', async () => {
|
||||
await seedSource('a');
|
||||
await seedSource('b');
|
||||
const id = await seedClient('alice', ['a', 'b']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const outcome = await setFederatedReadCore(sql, 'alice', 'a,b');
|
||||
expect(outcome.kind).toBe('noop');
|
||||
if (outcome.kind === 'noop') {
|
||||
expect(outcome.reason).toBe('same-list');
|
||||
}
|
||||
expect(await readFederated(id)).toEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
test('refuses unknown source (fails BEFORE mutating)', async () => {
|
||||
await seedSource('a');
|
||||
const id = await seedClient('alice', ['a']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await expect(setFederatedReadCore(sql, 'alice', 'a,ghost')).rejects.toThrow(/does not exist/);
|
||||
// Original list preserved.
|
||||
expect(await readFederated(id)).toEqual(['a']);
|
||||
});
|
||||
|
||||
test('order in CSV is the order persisted', async () => {
|
||||
await seedSource('a');
|
||||
await seedSource('b');
|
||||
await seedSource('c');
|
||||
const id = await seedClient('alice', ['a']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await setFederatedReadCore(sql, 'alice', 'c,a,b');
|
||||
expect(await readFederated(id)).toEqual(['c', 'a', 'b']);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// --dry-run semantics
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Codex fixes: soft-delete filter, atomic-SQL race-safety, sanitizer
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('sanitizeForTerminal', () => {
|
||||
test('preserves printable ASCII unchanged', () => {
|
||||
expect(sanitizeForTerminal('alice')).toBe('alice');
|
||||
expect(sanitizeForTerminal('a b-c_d.e/f@g')).toBe('a b-c_d.e/f@g');
|
||||
});
|
||||
|
||||
test('escapes ANSI escape sequences', () => {
|
||||
expect(sanitizeForTerminal('\x1b[2J')).toBe('\\x1b[2J');
|
||||
expect(sanitizeForTerminal('\x1b]0;TITLE\x07')).toBe('\\x1b]0;TITLE\\x07');
|
||||
});
|
||||
|
||||
test('escapes ALL C0 controls including tab and newline', () => {
|
||||
// Codex re-review: preserving \n lets a DCR-registered name spoof
|
||||
// additional rows in list-clients output. Tab spoofs field separators.
|
||||
// Both are now escaped.
|
||||
expect(sanitizeForTerminal('\x00\x07\x08')).toBe('\\x00\\x07\\x08');
|
||||
expect(sanitizeForTerminal('line1\nline2')).toBe('line1\\x0aline2');
|
||||
expect(sanitizeForTerminal('col1\tcol2')).toBe('col1\\x09col2');
|
||||
});
|
||||
|
||||
test('escapes DEL and C1 controls', () => {
|
||||
expect(sanitizeForTerminal('\x7f')).toBe('\\x7f');
|
||||
expect(sanitizeForTerminal('\x9b[31m')).toBe('\\x9b[31m');
|
||||
});
|
||||
|
||||
test('passes through unicode', () => {
|
||||
expect(sanitizeForTerminal('café')).toBe('café');
|
||||
expect(sanitizeForTerminal('日本語')).toBe('日本語');
|
||||
});
|
||||
});
|
||||
|
||||
describe('soft-delete filter (Codex finding #2)', () => {
|
||||
async function softDeleteClient(clientId: string): Promise<void> {
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await sql`UPDATE oauth_clients SET deleted_at = now() WHERE client_id = ${clientId}`;
|
||||
}
|
||||
|
||||
test('resolveClient hides soft-deleted clients by default', async () => {
|
||||
await seedSource('default');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
await softDeleteClient(id);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await expect(resolveClient(sql, 'alice')).rejects.toThrow(/No active OAuth client found/);
|
||||
await expect(resolveClient(sql, id)).rejects.toThrow(/No active OAuth client found/);
|
||||
});
|
||||
|
||||
test('resolveClient with includeDeleted finds soft-deleted clients', async () => {
|
||||
await seedSource('default');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
await softDeleteClient(id);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const c = await resolveClient(sql, id, { includeDeleted: true });
|
||||
expect(c.client_name).toBe('alice');
|
||||
expect(c.deleted_at).not.toBeNull();
|
||||
});
|
||||
|
||||
test('grantReadCore refuses to mutate soft-deleted clients', async () => {
|
||||
await seedSource('default');
|
||||
await seedSource('proj-x');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
await softDeleteClient(id);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await expect(grantReadCore(sql, 'alice', 'proj-x')).rejects.toThrow(/No active OAuth client found/);
|
||||
expect(await readFederated(id)).toEqual(['default']);
|
||||
});
|
||||
|
||||
test('revokeReadCore refuses to mutate soft-deleted clients', async () => {
|
||||
await seedSource('default');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
await softDeleteClient(id);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await expect(revokeReadCore(sql, 'alice', 'default')).rejects.toThrow(/No active OAuth client found/);
|
||||
expect(await readFederated(id)).toEqual(['default']);
|
||||
});
|
||||
|
||||
test('two clients with same name but only one active resolves to the active one', async () => {
|
||||
await seedSource('default');
|
||||
// Seed two clients with the same name; soft-delete the older one.
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const oldId = await seedClient('alice', ['default']);
|
||||
await softDeleteClient(oldId);
|
||||
const newId = await seedClient('alice', ['default']); // same name, new row
|
||||
const c = await resolveClient(sql, 'alice');
|
||||
expect(c.client_id).toBe(newId); // active row wins; ambiguity error suppressed
|
||||
});
|
||||
});
|
||||
|
||||
describe('atomic SQL race-safety (Codex finding #1, HIGH)', () => {
|
||||
test('grant+revoke serialize at row-lock — sensitive stays revoked', async () => {
|
||||
await seedSource('default');
|
||||
await seedSource('sensitive');
|
||||
await seedSource('harmless');
|
||||
const id = await seedClient('alice', ['default', 'sensitive']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
|
||||
// Simulate concurrent revoke(sensitive) + grant(harmless). Real concurrency
|
||||
// would race at the JS event loop boundary; here we await sequentially but
|
||||
// each call goes through the ATOMIC SQL path. The contract: regardless of
|
||||
// ordering, the final state has sensitive REMOVED and harmless ADDED.
|
||||
await revokeReadCore(sql, 'alice', 'sensitive');
|
||||
await grantReadCore(sql, 'alice', 'harmless');
|
||||
const final1 = await readFederated(id);
|
||||
expect(final1.sort()).toEqual(['default', 'harmless']);
|
||||
|
||||
// Reverse order, same final state. The pre-fix read-modify-write shape
|
||||
// would have produced ['default', 'sensitive', 'harmless'] here (the
|
||||
// resurrection bug Codex caught).
|
||||
const id2 = await seedClient('bob', ['default', 'sensitive']);
|
||||
await grantReadCore(sql, 'bob', 'harmless');
|
||||
await revokeReadCore(sql, 'bob', 'sensitive');
|
||||
const final2 = await readFederated(id2);
|
||||
expect(final2.sort()).toEqual(['default', 'harmless']);
|
||||
});
|
||||
|
||||
test('grant uses RETURNING to surface the post-write state', async () => {
|
||||
await seedSource('default');
|
||||
await seedSource('proj-x');
|
||||
await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const outcome = await grantReadCore(sql, 'alice', 'proj-x');
|
||||
expect(outcome.kind).toBe('updated');
|
||||
if (outcome.kind === 'updated') {
|
||||
// The `after` came from RETURNING, not from computing prev+sourceId
|
||||
// in JS — proves the atomic path returned authoritative state.
|
||||
expect(outcome.after).toEqual(['default', 'proj-x']);
|
||||
}
|
||||
});
|
||||
|
||||
test('grant noop path still survives without writing', async () => {
|
||||
await seedSource('default');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const outcome = await grantReadCore(sql, 'alice', 'default');
|
||||
expect(outcome.kind).toBe('noop');
|
||||
if (outcome.kind === 'noop') expect(outcome.reason).toBe('already-granted');
|
||||
expect(await readFederated(id)).toEqual(['default']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dryRun mode', () => {
|
||||
test('grantReadCore returns "updated" outcome but skips the write', async () => {
|
||||
await seedSource('default');
|
||||
await seedSource('proj-x');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const outcome = await grantReadCore(sql, 'alice', 'proj-x', { dryRun: true });
|
||||
expect(outcome.kind).toBe('updated');
|
||||
if (outcome.kind === 'updated') {
|
||||
expect(outcome.before).toEqual(['default']);
|
||||
expect(outcome.after).toEqual(['default', 'proj-x']);
|
||||
}
|
||||
// Crucially: the DB row is UNCHANGED.
|
||||
expect(await readFederated(id)).toEqual(['default']);
|
||||
});
|
||||
|
||||
test('revokeReadCore returns "updated" outcome but skips the write', async () => {
|
||||
await seedSource('default');
|
||||
await seedSource('proj-x');
|
||||
const id = await seedClient('alice', ['default', 'proj-x']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const outcome = await revokeReadCore(sql, 'alice', 'proj-x', { dryRun: true });
|
||||
expect(outcome.kind).toBe('updated');
|
||||
expect(await readFederated(id)).toEqual(['default', 'proj-x']);
|
||||
});
|
||||
|
||||
test('setFederatedReadCore returns "updated" outcome but skips the write', async () => {
|
||||
await seedSource('a');
|
||||
await seedSource('b');
|
||||
await seedSource('c');
|
||||
const id = await seedClient('alice', ['a']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const outcome = await setFederatedReadCore(sql, 'alice', 'b,c', { dryRun: true });
|
||||
expect(outcome.kind).toBe('updated');
|
||||
expect(await readFederated(id)).toEqual(['a']);
|
||||
});
|
||||
|
||||
test('noop outcomes are surfaced identically with or without dryRun', async () => {
|
||||
await seedSource('default');
|
||||
await seedSource('proj-x');
|
||||
await seedClient('alice', ['default', 'proj-x']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
const live = await grantReadCore(sql, 'alice', 'proj-x', { dryRun: false });
|
||||
const dry = await grantReadCore(sql, 'alice', 'proj-x', { dryRun: true });
|
||||
expect(live.kind).toBe('noop');
|
||||
expect(dry.kind).toBe('noop');
|
||||
});
|
||||
|
||||
test('errors still fire in dryRun (operator sees the problem before commit)', async () => {
|
||||
await seedSource('default');
|
||||
const id = await seedClient('alice', ['default']);
|
||||
const sql = sqlQueryForEngine(engine);
|
||||
await expect(
|
||||
grantReadCore(sql, 'alice', 'ghost', { dryRun: true }),
|
||||
).rejects.toThrow(/does not exist/);
|
||||
await expect(
|
||||
grantReadCore(sql, 'nobody', 'default', { dryRun: true }),
|
||||
).rejects.toThrow(/No active OAuth client found/);
|
||||
// DB unchanged.
|
||||
expect(await readFederated(id)).toEqual(['default']);
|
||||
});
|
||||
});
|
||||
@@ -174,29 +174,6 @@ describe('parseRegisterClientArgs', () => {
|
||||
});
|
||||
|
||||
describe('error cases', () => {
|
||||
test('--source with malformed id throws (validates source_id shape — codex re-review)', () => {
|
||||
// Defense for the "register-client seeds an unmanageable
|
||||
// federated_read entry" vector. assertValidSourceId fires before the
|
||||
// function returns so DB never sees a row with bad source scope.
|
||||
expect(() => parseRegisterClientArgs(['--source', 'has,weird,bits'])).toThrow(/Invalid source_id/);
|
||||
expect(() => parseRegisterClientArgs(['--source', 'UPPER'])).toThrow(/Invalid source_id/);
|
||||
expect(() => parseRegisterClientArgs(['--source', ''])).toThrow(/Invalid source_id|requires a value/);
|
||||
});
|
||||
|
||||
test('--federated-read with any malformed id throws', () => {
|
||||
// Single-item bad.
|
||||
expect(() => parseRegisterClientArgs(['--federated-read', 'bad,source!'])).toThrow(/Invalid source_id/);
|
||||
// Mixed valid + invalid — fails on the first bad one.
|
||||
expect(() => parseRegisterClientArgs(['--federated-read', 'good,bad source'])).toThrow(/Invalid source_id/);
|
||||
});
|
||||
|
||||
test('--source default + --federated-read default,team passes (regression — common case)', () => {
|
||||
// Sanity: the canonical real-world invocation still parses cleanly.
|
||||
const out = parseRegisterClientArgs(['--source', 'default', '--federated-read', 'default,team']);
|
||||
expect(out.sourceId).toBe('default');
|
||||
expect(out.federatedRead).toEqual(['default', 'team']);
|
||||
});
|
||||
|
||||
test('--redirect-uri without value → throws', () => {
|
||||
expect(() => parseRegisterClientArgs(['--redirect-uri'])).toThrow(/requires a value/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Structural regression for the backlinks Minion handler default.
|
||||
*
|
||||
* Backlinks jobs submitted with an EMPTY payload (the sync→embed→backlinks
|
||||
* chains enqueued after every ingestion) must run as 'check', never 'fix'.
|
||||
* The pre-fix handler inverted the default (`=== 'check' ? 'check' : 'fix'`),
|
||||
* so every routine post-ingestion job rewrote tracked brain pages with
|
||||
* generated "Referenced in" timeline bullets — contradicting the documented
|
||||
* intent in src/core/cycle.ts (runPhaseBacklinks): "Maintenance cycles must
|
||||
* not rewrite tracked brain pages with generated 'Referenced in' timeline
|
||||
* bullets."
|
||||
*
|
||||
* Source-grep is the right tool here (see fix-wave-structural.test.ts): the
|
||||
* handler dynamically imports runBacklinksCore and walks a real repo dir, so
|
||||
* a behavioral test would require heavy mocking that hides the regression
|
||||
* behind a test seam. The rule is "this specific default must stay 'check'".
|
||||
*/
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
describe('backlinks Minion handler — empty payload defaults to check, not fix', () => {
|
||||
const src = readFileSync('src/commands/jobs.ts', 'utf8');
|
||||
|
||||
// Isolate the backlinks register block so assertions can't accidentally
|
||||
// match another handler's action parsing.
|
||||
const blockMatch = src.match(
|
||||
/worker\.register\('backlinks',[\s\S]*?runBacklinksCore\(\{[\s\S]*?\}\);/
|
||||
);
|
||||
|
||||
test('the backlinks handler block exists', () => {
|
||||
expect(blockMatch).not.toBeNull();
|
||||
});
|
||||
|
||||
test("default action is 'check' (explicit opt-in required for 'fix')", () => {
|
||||
const block = blockMatch![0];
|
||||
expect(block).toMatch(
|
||||
/job\.data\.action\s*===\s*'fix'\s*\?\s*'fix'\s*:\s*'check'/
|
||||
);
|
||||
});
|
||||
|
||||
test('the inverted (fix-by-default) shape stays absent', () => {
|
||||
const block = blockMatch![0];
|
||||
expect(block).not.toMatch(
|
||||
/job\.data\.action\s*===\s*'check'\s*\?\s*'check'\s*:\s*'fix'/
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
checkResolvable,
|
||||
parseResolverEntries,
|
||||
extractDelegationTargets,
|
||||
extractTriggers,
|
||||
} from "../src/core/check-resolvable.ts";
|
||||
|
||||
const SKILLS_DIR = join(import.meta.dir, "..", "skills");
|
||||
@@ -195,6 +196,39 @@ describe("parseResolverEntries", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractTriggers", () => {
|
||||
const LF_FRONTMATTER =
|
||||
"---\nname: query\ndescription: Test\ntriggers:\n - \"what do we know\"\n - \"tell me about\"\ntools:\n - search\n---\n\n# Body\n";
|
||||
|
||||
test("parses triggers from LF-terminated frontmatter", () => {
|
||||
const triggers = extractTriggers(LF_FRONTMATTER);
|
||||
expect(triggers).toEqual(["what do we know", "tell me about"]);
|
||||
});
|
||||
|
||||
test("parses triggers from CRLF-terminated frontmatter (Windows checkouts)", () => {
|
||||
// Regression: `core.autocrlf=true` is the Windows default. Without
|
||||
// CRLF→LF normalization, every Windows skill is reported as a false
|
||||
// mece_gap warning because the `^---\n` regex never matches `---\r\n`.
|
||||
const crlf = LF_FRONTMATTER.replace(/\n/g, "\r\n");
|
||||
const triggers = extractTriggers(crlf);
|
||||
expect(triggers).toEqual(["what do we know", "tell me about"]);
|
||||
});
|
||||
|
||||
test("returns [] when frontmatter is missing", () => {
|
||||
expect(extractTriggers("# Just a body, no frontmatter\n")).toEqual([]);
|
||||
});
|
||||
|
||||
test("returns [] when triggers field is absent from frontmatter", () => {
|
||||
const fm = "---\nname: query\ndescription: Test\ntools:\n - search\n---\n";
|
||||
expect(extractTriggers(fm)).toEqual([]);
|
||||
});
|
||||
|
||||
test("strips surrounding quotes from trigger values", () => {
|
||||
const fm = "---\nname: x\ntriggers:\n - \"double quoted\"\n - 'single quoted'\n - unquoted\n---\n";
|
||||
expect(extractTriggers(fm)).toEqual(["double quoted", "single quoted", "unquoted"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkResolvable — real skills directory", () => {
|
||||
const report = checkResolvable(SKILLS_DIR);
|
||||
|
||||
|
||||
@@ -8,13 +8,15 @@
|
||||
//
|
||||
// PGLite-only: in-memory engine, no DATABASE_URL needed.
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { loadConfigWithEngine, type GBrainConfig } from '../src/core/config.ts';
|
||||
import {
|
||||
__setRerankTransportForTests,
|
||||
configureGateway,
|
||||
getEmbeddingModel,
|
||||
getMultimodalModel,
|
||||
rerank,
|
||||
resetGateway,
|
||||
} from '../src/core/ai/gateway.ts';
|
||||
import type { AIGatewayConfig } from '../src/core/ai/types.ts';
|
||||
@@ -52,10 +54,16 @@ afterAll(async () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
resetGateway();
|
||||
__setRerankTransportForTests(null);
|
||||
// Clear any prior config rows so tests are independent. setConfig with
|
||||
// empty string is treated as undefined by loadConfigWithEngine (per
|
||||
// dbStr semantics), so this is safe to call between tests.
|
||||
await engine.setConfig('embedding_multimodal_model', '');
|
||||
await engine.setConfig('provider_base_urls.llama-server-reranker', '');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
__setRerankTransportForTests(null);
|
||||
});
|
||||
|
||||
describe('cli connectEngine — embedding_multimodal_model DB→gateway plumbing', () => {
|
||||
@@ -122,4 +130,34 @@ describe('cli connectEngine — embedding_multimodal_model DB→gateway plumbing
|
||||
expect(getEmbeddingModel()).toBe('openai:text-embedding-3-large');
|
||||
expect(getMultimodalModel()).toBeUndefined();
|
||||
});
|
||||
|
||||
test('DB-set provider_base_urls.llama-server-reranker flows to gateway.rerank URL', async () => {
|
||||
await engine.setConfig('provider_base_urls.llama-server-reranker', 'http://127.0.0.1:8091/v1');
|
||||
|
||||
const baseConfig: GBrainConfig = {
|
||||
engine: 'pglite',
|
||||
embedding_model: 'openai:text-embedding-3-large',
|
||||
embedding_dimensions: 1536,
|
||||
};
|
||||
|
||||
const merged = await loadConfigWithEngine(engine, baseConfig);
|
||||
configureGateway(buildGatewayConfig(merged!));
|
||||
|
||||
let capturedUrl = '';
|
||||
__setRerankTransportForTests(async (url) => {
|
||||
capturedUrl = url;
|
||||
return new Response(JSON.stringify({ results: [{ index: 0, relevance_score: 0.9 }] }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
});
|
||||
|
||||
await rerank({
|
||||
query: 'q',
|
||||
documents: ['d'],
|
||||
model: 'llama-server-reranker:qwen3-reranker-4b',
|
||||
});
|
||||
|
||||
expect(capturedUrl).toBe('http://127.0.0.1:8091/v1/rerank');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,20 +1,38 @@
|
||||
/**
|
||||
* Pure-function tests for src/core/contextual-retrieval-service.ts.
|
||||
*
|
||||
* The full service test (PHASE 1 + PHASE 2 happy path, refusal restart,
|
||||
* transient error propagation) needs a real PGLite + gateway stub seam.
|
||||
* That lands in test/e2e/contextual-retrieval.test.ts. This file pins
|
||||
* the service's pure helpers: corpus_generation hash composition + the
|
||||
* expectedMode helper used by the T9 reindex sweep predicate.
|
||||
* This file pins the service's pure helpers plus hermetic service behavior
|
||||
* driven through fake engine + gateway seams. Full PGLite coverage lives in
|
||||
* test/e2e/contextual-retrieval-pglite.test.ts.
|
||||
*/
|
||||
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { afterEach, describe, test, expect } from 'bun:test';
|
||||
import {
|
||||
computeCorpusGeneration,
|
||||
computeSourceTextHash,
|
||||
expectedModeForPageSourceOnly,
|
||||
reembedPageWithContextualRetrieval,
|
||||
resolveContextualChunkConcurrency,
|
||||
TITLE_WRAPPER_VERSION,
|
||||
} from '../src/core/contextual-retrieval-service.ts';
|
||||
import {
|
||||
__setChatTransportForTests,
|
||||
__setEmbedTransportForTests,
|
||||
configureGateway,
|
||||
resetGateway,
|
||||
type ChatOpts,
|
||||
type ChatResult,
|
||||
} from '../src/core/ai/gateway.ts';
|
||||
import type { ChunkInput } from '../src/core/types.ts';
|
||||
import { withEnv } from './helpers/with-env.ts';
|
||||
|
||||
const TEST_DIMS = 1536;
|
||||
|
||||
afterEach(() => {
|
||||
__setChatTransportForTests(null);
|
||||
__setEmbedTransportForTests(null);
|
||||
resetGateway();
|
||||
});
|
||||
|
||||
describe('computeCorpusGeneration', () => {
|
||||
test('returns 16-char hex hash', () => {
|
||||
@@ -138,3 +156,317 @@ describe('expectedModeForPageSourceOnly (T9 reindex sweep helper)', () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveContextualChunkConcurrency', () => {
|
||||
test('defaults to 4 and reads the process env', async () => {
|
||||
await withEnv({ GBRAIN_CONTEXTUAL_CHUNK_CONCURRENCY: undefined }, async () => {
|
||||
expect(resolveContextualChunkConcurrency()).toBe(4);
|
||||
});
|
||||
await withEnv({ GBRAIN_CONTEXTUAL_CHUNK_CONCURRENCY: '7' }, async () => {
|
||||
expect(resolveContextualChunkConcurrency()).toBe(7);
|
||||
});
|
||||
});
|
||||
|
||||
test('clamps to [1, 16] and ignores invalid values', () => {
|
||||
expect(resolveContextualChunkConcurrency({
|
||||
GBRAIN_CONTEXTUAL_CHUNK_CONCURRENCY: '0',
|
||||
})).toBe(1);
|
||||
expect(resolveContextualChunkConcurrency({
|
||||
GBRAIN_CONTEXTUAL_CHUNK_CONCURRENCY: '-3',
|
||||
})).toBe(1);
|
||||
expect(resolveContextualChunkConcurrency({
|
||||
GBRAIN_CONTEXTUAL_CHUNK_CONCURRENCY: '99',
|
||||
})).toBe(16);
|
||||
expect(resolveContextualChunkConcurrency({
|
||||
GBRAIN_CONTEXTUAL_CHUNK_CONCURRENCY: '1.9',
|
||||
})).toBe(1);
|
||||
expect(resolveContextualChunkConcurrency({
|
||||
GBRAIN_CONTEXTUAL_CHUNK_CONCURRENCY: 'not-a-number',
|
||||
})).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe('per-chunk synopsis concurrency', () => {
|
||||
test('concurrency > 1 preserves chunk-order embed input', async () => {
|
||||
const chunks = makeChunks(['alpha', 'beta', 'gamma', 'delta']);
|
||||
const delays: Record<string, number> = { alpha: 30, beta: 5, gamma: 20, delta: 1 };
|
||||
const sequential = await runWithChatStub({
|
||||
chunks,
|
||||
concurrency: 1,
|
||||
delayForChunk: (chunk) => delays[chunk] ?? 1,
|
||||
});
|
||||
const parallel = await runWithChatStub({
|
||||
chunks,
|
||||
concurrency: 4,
|
||||
delayForChunk: (chunk) => delays[chunk] ?? 1,
|
||||
});
|
||||
|
||||
expect(parallel.result.kind).toBe('success');
|
||||
expect(parallel.embedInputs).toEqual(sequential.embedInputs);
|
||||
expect(parallel.embeddedChunks.map((c) => c.chunk_text)).toEqual(
|
||||
chunks.map((c) => c.chunk_text),
|
||||
);
|
||||
});
|
||||
|
||||
test('concurrency is bounded', async () => {
|
||||
let active = 0;
|
||||
let maxActive = 0;
|
||||
let leaseActive = 0;
|
||||
let maxLeaseActive = 0;
|
||||
let acquired = 0;
|
||||
let released = 0;
|
||||
const chunks = makeChunks(Array.from({ length: 8 }, (_, i) => `chunk-${i}`));
|
||||
const out = await runWithChatStub({
|
||||
chunks,
|
||||
concurrency: 3,
|
||||
acquireSynopsisLease: async () => {
|
||||
acquired++;
|
||||
leaseActive++;
|
||||
maxLeaseActive = Math.max(maxLeaseActive, leaseActive);
|
||||
return acquired;
|
||||
},
|
||||
releaseSynopsisLease: async () => {
|
||||
released++;
|
||||
leaseActive--;
|
||||
},
|
||||
chat: async (opts) => {
|
||||
active++;
|
||||
maxActive = Math.max(maxActive, active);
|
||||
try {
|
||||
await delay(20, opts.abortSignal);
|
||||
return chatSuccess(`Synopsis for ${extractChunk(opts)}`);
|
||||
} finally {
|
||||
active--;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
expect(out.result.kind).toBe('success');
|
||||
expect(maxActive).toBeGreaterThan(1);
|
||||
expect(maxActive).toBeLessThanOrEqual(3);
|
||||
expect(maxLeaseActive).toBeLessThanOrEqual(3);
|
||||
expect(acquired).toBe(8);
|
||||
expect(released).toBe(8);
|
||||
expect(leaseActive).toBe(0);
|
||||
});
|
||||
|
||||
test('one chunk failure aborts queued work and falls back at page level', async () => {
|
||||
let started = 0;
|
||||
const chunks = makeChunks(Array.from({ length: 9 }, (_, i) => `chunk-${i}`));
|
||||
const out = await runWithChatStub({
|
||||
chunks,
|
||||
concurrency: 3,
|
||||
chat: async (opts) => {
|
||||
started++;
|
||||
const chunk = extractChunk(opts);
|
||||
if (chunk === 'chunk-0') return chatSuccess('');
|
||||
await delay(30, opts.abortSignal);
|
||||
return chatSuccess(`Synopsis for ${chunk}`);
|
||||
},
|
||||
});
|
||||
|
||||
expect(out.result.kind).toBe('page_fallback');
|
||||
expect(started).toBeLessThanOrEqual(3);
|
||||
});
|
||||
|
||||
test('fenced code chunks bypass synopsis calls and leases', async () => {
|
||||
let chatCalls = 0;
|
||||
let leaseCalls = 0;
|
||||
const chunks: ChunkInput[] = [
|
||||
{ chunk_index: 0, chunk_text: 'intro', chunk_source: 'compiled_truth' },
|
||||
{ chunk_index: 1, chunk_text: 'const x = 1;', chunk_source: 'fenced_code' },
|
||||
{ chunk_index: 2, chunk_text: 'outro', chunk_source: 'compiled_truth' },
|
||||
];
|
||||
|
||||
const out = await runWithChatStub({
|
||||
chunks,
|
||||
concurrency: 3,
|
||||
acquireSynopsisLease: async () => {
|
||||
leaseCalls++;
|
||||
},
|
||||
releaseSynopsisLease: async () => {},
|
||||
chat: async (opts) => {
|
||||
chatCalls++;
|
||||
return chatSuccess(`Synopsis for ${extractChunk(opts)}`);
|
||||
},
|
||||
});
|
||||
|
||||
expect(out.result.kind).toBe('success');
|
||||
expect(chatCalls).toBe(2);
|
||||
expect(leaseCalls).toBe(2);
|
||||
expect(out.embedInputs[1]).toBe('const x = 1;');
|
||||
});
|
||||
|
||||
test('abortSignal cancels in-flight and queued synopsis work promptly', async () => {
|
||||
const controller = new AbortController();
|
||||
let started = 0;
|
||||
const chunks = makeChunks(Array.from({ length: 20 }, (_, i) => `chunk-${i}`));
|
||||
const startedAt = Date.now();
|
||||
const promise = runWithChatStub({
|
||||
chunks,
|
||||
concurrency: 4,
|
||||
abortSignal: controller.signal,
|
||||
chat: async (opts) => {
|
||||
started++;
|
||||
await delay(1000, opts.abortSignal);
|
||||
return chatSuccess(`Synopsis for ${extractChunk(opts)}`);
|
||||
},
|
||||
});
|
||||
setTimeout(() => controller.abort(), 20);
|
||||
|
||||
const out = await promise;
|
||||
expect(out.result.kind).toBe('transient_error');
|
||||
if (out.result.kind === 'transient_error') {
|
||||
expect(out.result.cause).toBe('timeout');
|
||||
}
|
||||
expect(started).toBeLessThanOrEqual(4);
|
||||
expect(Date.now() - startedAt).toBeLessThan(300);
|
||||
});
|
||||
});
|
||||
|
||||
function makeChunks(texts: string[]): ChunkInput[] {
|
||||
return texts.map((text, i) => ({
|
||||
chunk_index: i,
|
||||
chunk_text: text,
|
||||
chunk_source: 'compiled_truth',
|
||||
}));
|
||||
}
|
||||
|
||||
async function runWithChatStub(opts: {
|
||||
chunks: ChunkInput[];
|
||||
concurrency: number;
|
||||
abortSignal?: AbortSignal;
|
||||
delayForChunk?: (chunk: string) => number;
|
||||
chat?: (opts: ChatOpts) => Promise<ChatResult>;
|
||||
acquireSynopsisLease?: () => Promise<unknown>;
|
||||
releaseSynopsisLease?: (lease?: unknown) => Promise<void>;
|
||||
}) {
|
||||
configureGateway({
|
||||
embedding_model: 'openai:text-embedding-3-large',
|
||||
embedding_dimensions: TEST_DIMS,
|
||||
env: { OPENAI_API_KEY: 'sk-test' },
|
||||
});
|
||||
|
||||
const embedInputs: string[][] = [];
|
||||
__setEmbedTransportForTests(async ({ values }: any) => {
|
||||
embedInputs.push([...values]);
|
||||
return {
|
||||
embeddings: values.map((_: string, i: number) =>
|
||||
Array.from({ length: TEST_DIMS }, () => 0.001 + i * 0.001),
|
||||
),
|
||||
usage: { tokens: 0 },
|
||||
} as any;
|
||||
});
|
||||
|
||||
__setChatTransportForTests(opts.chat ?? (async (chatOpts) => {
|
||||
const chunk = extractChunk(chatOpts);
|
||||
await delay(opts.delayForChunk?.(chunk) ?? 1, chatOpts.abortSignal);
|
||||
return chatSuccess(`Synopsis for ${chunk}`);
|
||||
}));
|
||||
|
||||
const engine = makeServiceEngine(opts.chunks);
|
||||
const result = await reembedPageWithContextualRetrieval({
|
||||
engine,
|
||||
pageSlug: 'wiki/concepts/concurrency-test',
|
||||
sourceId: 'default',
|
||||
globalMode: 'per_chunk_synopsis',
|
||||
chunkConcurrency: opts.concurrency,
|
||||
abortSignal: opts.abortSignal,
|
||||
...(opts.acquireSynopsisLease && { acquireSynopsisLease: opts.acquireSynopsisLease }),
|
||||
...(opts.releaseSynopsisLease && { releaseSynopsisLease: opts.releaseSynopsisLease }),
|
||||
});
|
||||
|
||||
return {
|
||||
result,
|
||||
embedInputs: embedInputs.flat(),
|
||||
embeddedChunks: engine.embeddedChunks as ChunkInput[],
|
||||
};
|
||||
}
|
||||
|
||||
function makeServiceEngine(chunks: ChunkInput[]) {
|
||||
const engine: any = {
|
||||
embeddedChunks: [] as ChunkInput[],
|
||||
async getPage() {
|
||||
return {
|
||||
id: 1,
|
||||
slug: 'wiki/concepts/concurrency-test',
|
||||
source_id: 'default',
|
||||
type: 'concept',
|
||||
title: 'Concurrency Test',
|
||||
compiled_truth: chunks.map((c) => c.chunk_text).join('\n\n'),
|
||||
timeline: '',
|
||||
frontmatter: {},
|
||||
created_at: new Date('2026-01-01T00:00:00Z'),
|
||||
updated_at: new Date('2026-01-01T00:00:00Z'),
|
||||
deleted_at: null,
|
||||
};
|
||||
},
|
||||
async executeRaw() {
|
||||
return [{
|
||||
id: 'default',
|
||||
name: 'Default',
|
||||
local_path: null,
|
||||
last_commit: null,
|
||||
last_sync_at: null,
|
||||
config: {},
|
||||
created_at: new Date('2026-01-01T00:00:00Z'),
|
||||
contextual_retrieval_mode: null,
|
||||
trust_frontmatter_overrides: false,
|
||||
}];
|
||||
},
|
||||
async getChunks() {
|
||||
return chunks;
|
||||
},
|
||||
async transaction(fn: (tx: any) => Promise<void>) {
|
||||
await fn({
|
||||
upsertChunks: async (_slug: string, embedded: ChunkInput[]) => {
|
||||
engine.embeddedChunks = embedded;
|
||||
},
|
||||
updatePageContextualRetrievalState: async () => {},
|
||||
});
|
||||
},
|
||||
async updatePageContextualRetrievalState() {},
|
||||
};
|
||||
return engine;
|
||||
}
|
||||
|
||||
function extractChunk(opts: ChatOpts): string {
|
||||
const content = String(opts.messages[0]?.content ?? '');
|
||||
return content.match(/<chunk>\n([\s\S]*?)\n<\/chunk>/)?.[1] ?? '';
|
||||
}
|
||||
|
||||
function chatSuccess(text: string): ChatResult {
|
||||
return {
|
||||
text,
|
||||
blocks: [],
|
||||
stopReason: 'end',
|
||||
usage: {
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
cache_read_tokens: 0,
|
||||
cache_creation_tokens: 0,
|
||||
},
|
||||
model: 'stub:chat',
|
||||
providerId: 'stub',
|
||||
};
|
||||
}
|
||||
|
||||
function delay(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal?.aborted) {
|
||||
reject(abortError());
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(resolve, ms);
|
||||
signal?.addEventListener('abort', () => {
|
||||
clearTimeout(timer);
|
||||
reject(abortError());
|
||||
}, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
function abortError(): Error {
|
||||
const err = new Error('aborted');
|
||||
err.name = 'AbortError';
|
||||
return err;
|
||||
}
|
||||
|
||||
@@ -97,6 +97,34 @@ describe('issue #1801 fix #3 — computeWedgedQueueCheck', () => {
|
||||
expect(check.message).not.toContain("'q-healthy'");
|
||||
});
|
||||
|
||||
it('#3063: wedged queue with NO live supervisor → "no worker running", not the DB-pool message', async () => {
|
||||
await seed('default', 'cycle', 'waiting');
|
||||
await seed('default', 'cycle', 'completed', { updatedAtSql: "now() - interval '20 min'" });
|
||||
// No gbrain_cycle_locks row for gbrain-supervisor:default.
|
||||
const check = await computeWedgedQueueCheck(pgLike);
|
||||
expect(check.status).toBe('fail');
|
||||
expect(check.message).toContain('no worker running');
|
||||
expect(check.message).toContain('gbrain jobs supervisor start');
|
||||
expect(check.message).not.toContain('rebuilds a fresh DB pool');
|
||||
});
|
||||
|
||||
it('#3063: wedged queue WITH a live supervisor lock → keeps the wedged-pool message', async () => {
|
||||
await seed('default', 'cycle', 'waiting');
|
||||
await seed('default', 'cycle', 'completed', { updatedAtSql: "now() - interval '20 min'" });
|
||||
await base.executeRaw(
|
||||
`INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at)
|
||||
VALUES ('gbrain-supervisor:default', 12345, 'test-host', now(), now() + interval '5 min', now())`,
|
||||
);
|
||||
try {
|
||||
const check = await computeWedgedQueueCheck(pgLike);
|
||||
expect(check.status).toBe('fail');
|
||||
expect(check.message).toContain('worker alive but not claiming work');
|
||||
expect(check.message).toContain('rebuilds a fresh DB pool');
|
||||
} finally {
|
||||
await base.executeRaw(`DELETE FROM gbrain_cycle_locks WHERE id = 'gbrain-supervisor:default'`);
|
||||
}
|
||||
});
|
||||
|
||||
it('returns ok on PGLite (no multi-process worker surface)', async () => {
|
||||
const check = await computeWedgedQueueCheck(base as unknown as BrainEngine);
|
||||
expect(check.status).toBe('ok');
|
||||
|
||||
@@ -20,6 +20,10 @@ import {
|
||||
const skip = !hasDatabase();
|
||||
const describeE2E = skip ? describe.skip : describe;
|
||||
|
||||
if (skip) {
|
||||
console.log('Skipping E2E doctor --progress-json tests (DATABASE_URL not set)');
|
||||
}
|
||||
|
||||
const CLI = join(import.meta.dir, '..', '..', 'src', 'cli.ts');
|
||||
|
||||
describeE2E('gbrain doctor --progress-json (E2E)', () => {
|
||||
|
||||
@@ -172,6 +172,59 @@ describe('issue #972 — DB-source (gbrain extract links --source db)', () => {
|
||||
expect(strk!.link_type).toBe('wikilink_basename');
|
||||
});
|
||||
|
||||
test('flag ON → path-qualified wikilink outside DIR_PATTERN resolves via DB path', async () => {
|
||||
// `[[notes/struktura]]` — `notes` is not in DIR_PATTERN, so the ref
|
||||
// reaches the generic pass with its dirname intact. Regression: the DB
|
||||
// path queried the basename index with the raw literal (which is keyed
|
||||
// by final segments only), so path-qualified wikilinks outside
|
||||
// DIR_PATTERN silently produced zero edges while the FS path resolved
|
||||
// the identical content.
|
||||
await engine.putPage('notes/struktura', {
|
||||
type: 'concept' as any, title: 'Struktura Notes',
|
||||
compiled_truth: '', timeline: '',
|
||||
});
|
||||
await engine.putPage('concepts/knowledge-graph', {
|
||||
type: 'concept', title: 'Knowledge Graph',
|
||||
compiled_truth: 'Background in [[notes/struktura]].', timeline: '',
|
||||
});
|
||||
await engine.setConfig('link_resolution.global_basename', 'true');
|
||||
|
||||
await runExtract(engine, ['links', '--source', 'db']);
|
||||
|
||||
const outLinks = await engine.getLinks('concepts/knowledge-graph');
|
||||
const strk = outLinks.find(l => l.to_slug === 'notes/struktura');
|
||||
expect(strk).toBeDefined();
|
||||
expect(strk!.link_type).toBe('wikilink_basename');
|
||||
expect(strk!.link_source).toBe('wikilink-resolved');
|
||||
});
|
||||
|
||||
test('path-qualified wikilink never attaches to a basename-only sibling', async () => {
|
||||
// Both notes/struktura and wiki/struktura exist. The author wrote
|
||||
// `[[notes/struktura]]` — the written path must exclude wiki/struktura
|
||||
// (a bare `[[struktura]]` would legitimately match both).
|
||||
await engine.putPage('notes/struktura', {
|
||||
type: 'concept' as any, title: 'Struktura Notes',
|
||||
compiled_truth: '', timeline: '',
|
||||
});
|
||||
await engine.putPage('wiki/struktura', {
|
||||
type: 'concept' as any, title: 'Struktura Wiki',
|
||||
compiled_truth: '', timeline: '',
|
||||
});
|
||||
await engine.putPage('concepts/x', {
|
||||
type: 'concept', title: 'X',
|
||||
compiled_truth: 'See [[notes/struktura]].', timeline: '',
|
||||
});
|
||||
await engine.setConfig('link_resolution.global_basename', 'true');
|
||||
|
||||
await runExtract(engine, ['links', '--source', 'db']);
|
||||
|
||||
const outLinks = await engine.getLinks('concepts/x');
|
||||
const basenameLinks = outLinks
|
||||
.filter(l => l.link_type === 'wikilink_basename')
|
||||
.map(l => l.to_slug);
|
||||
expect(basenameLinks).toEqual(['notes/struktura']);
|
||||
});
|
||||
|
||||
test('flag OFF → no basename edges via DB path (back-compat)', async () => {
|
||||
await engine.putPage('projects/struktura', {
|
||||
type: 'project', title: 'Struktura',
|
||||
|
||||
@@ -29,9 +29,15 @@ afterAll(async () => {
|
||||
});
|
||||
|
||||
async function truncateAll() {
|
||||
for (const t of ['content_chunks', 'links', 'tags', 'raw_data', 'timeline_entries', 'page_versions', 'ingest_log', 'pages']) {
|
||||
for (const t of ['content_chunks', 'links', 'tags', 'raw_data', 'timeline_entries', 'page_versions', 'ingest_log', 'config', 'pages']) {
|
||||
await (engine as any).db.exec(`DELETE FROM ${t}`);
|
||||
}
|
||||
// Re-seed the two config keys this file touches back to their documented
|
||||
// defaults (both default to ON). This makes every test deterministic even if
|
||||
// an earlier test threw before its finally restored auto_link/auto_timeline,
|
||||
// and even though absent-key already resolves truthy via isAuto*Enabled.
|
||||
await engine.setConfig('auto_link', 'true');
|
||||
await engine.setConfig('auto_timeline', 'true');
|
||||
}
|
||||
|
||||
function makeContext(): OperationContext {
|
||||
@@ -77,10 +83,12 @@ describe('E2E graph quality (v0.10.1 pipeline)', () => {
|
||||
await runExtract(engine, ['links', '--source', 'db']);
|
||||
await runExtract(engine, ['timeline', '--source', 'db']);
|
||||
|
||||
// Verify graph populated.
|
||||
// Verify graph populated. Concrete floors derived from the seeded fixtures:
|
||||
// resolvable entity refs: alice->acme, bob->acme, standup->alice, standup->bob = 4
|
||||
// timeline lines: alice(2) + bob(1) + acme(1) + standup(1) = 5
|
||||
const stats = await engine.getStats();
|
||||
expect(stats.link_count).toBeGreaterThan(0);
|
||||
expect(stats.timeline_entry_count).toBeGreaterThan(0);
|
||||
expect(stats.link_count).toBeGreaterThanOrEqual(4);
|
||||
expect(stats.timeline_entry_count).toBeGreaterThanOrEqual(5);
|
||||
|
||||
// Verify typed link inference.
|
||||
const aliceLinks = await engine.getLinks('people/alice');
|
||||
@@ -91,7 +99,16 @@ describe('E2E graph quality (v0.10.1 pipeline)', () => {
|
||||
const bobAcme = bobLinks.find(l => l.to_slug === 'companies/acme');
|
||||
expect(bobAcme?.link_type).toBe('invested_in');
|
||||
|
||||
// The standup meeting references both Alice and Bob as attendees. Assert the
|
||||
// exact attendee edges are present and typed 'attended' (a plain .every()
|
||||
// would silently pass if a meeting->company edge were misclassified or if the
|
||||
// attendee edges were missing entirely).
|
||||
const meetingLinks = await engine.getLinks('meetings/standup');
|
||||
const attended = new Set(
|
||||
meetingLinks.filter(l => l.link_type === 'attended').map(l => l.to_slug),
|
||||
);
|
||||
expect(attended.has('people/alice')).toBe(true);
|
||||
expect(attended.has('people/bob')).toBe(true);
|
||||
expect(meetingLinks.every(l => l.link_type === 'attended')).toBe(true);
|
||||
});
|
||||
|
||||
@@ -118,7 +135,9 @@ Attendees: [Alice](people/alice). Discussed [Acme](companies/acme).
|
||||
// The response should include auto_links results.
|
||||
expect((result as any).auto_links).toBeDefined();
|
||||
const autoLinks = (result as any).auto_links;
|
||||
expect(autoLinks.created).toBeGreaterThan(0);
|
||||
// The page references exactly two seeded, resolvable targets (Alice + Acme),
|
||||
// so exactly two links are created.
|
||||
expect(autoLinks.created).toBe(2);
|
||||
expect(autoLinks.errors).toBe(0);
|
||||
|
||||
// Verify links actually exist in DB.
|
||||
@@ -283,6 +302,53 @@ Mention of [Alice](people/alice).
|
||||
expect(paths[0].link_type).toBe('works_at');
|
||||
});
|
||||
|
||||
test('graph-query traversal: direction out and both, plus depth:2 multi-hop', async () => {
|
||||
// Seed a 2-hop chain: alice -works_at-> acme -partnered_with-> beta.
|
||||
await engine.putPage('people/alice', { type: 'person', title: 'Alice', compiled_truth: '', timeline: '' });
|
||||
await engine.putPage('companies/acme', { type: 'company', title: 'Acme', compiled_truth: '', timeline: '' });
|
||||
await engine.putPage('companies/beta', { type: 'company', title: 'Beta', compiled_truth: '', timeline: '' });
|
||||
await engine.addLink('people/alice', 'companies/acme', '', 'works_at');
|
||||
await engine.addLink('companies/acme', 'companies/beta', '', 'partnered_with');
|
||||
|
||||
// direction:'out' from alice, depth 1 -> only the first hop.
|
||||
const out1 = await engine.traversePaths('people/alice', { direction: 'out', depth: 1 });
|
||||
expect(out1.length).toBe(1);
|
||||
expect(out1[0].from_slug).toBe('people/alice');
|
||||
expect(out1[0].to_slug).toBe('companies/acme');
|
||||
expect(out1[0].depth).toBe(1);
|
||||
|
||||
// depth:2 -> both hops, depths 1 and 2.
|
||||
const out2 = await engine.traversePaths('people/alice', { direction: 'out', depth: 2 });
|
||||
const out2Edges = new Set(out2.map(p => `${p.from_slug}->${p.to_slug}@${p.depth}`));
|
||||
expect(out2Edges.has('people/alice->companies/acme@1')).toBe(true);
|
||||
expect(out2Edges.has('companies/acme->companies/beta@2')).toBe(true);
|
||||
expect(out2.length).toBe(2);
|
||||
|
||||
// direction:'both' from acme depth 1 -> sees the inbound edge from alice AND
|
||||
// the outbound edge to beta. Edges keep their natural from->to orientation.
|
||||
const both = await engine.traversePaths('companies/acme', { direction: 'both', depth: 1 });
|
||||
const bothEdges = new Set(both.map(p => `${p.from_slug}->${p.to_slug}`));
|
||||
expect(bothEdges.has('people/alice->companies/acme')).toBe(true);
|
||||
expect(bothEdges.has('companies/acme->companies/beta')).toBe(true);
|
||||
});
|
||||
|
||||
test('graph-query cycle safety: A->B->A terminates and returns bounded results', async () => {
|
||||
await engine.putPage('people/alice', { type: 'person', title: 'Alice', compiled_truth: '', timeline: '' });
|
||||
await engine.putPage('people/bob', { type: 'person', title: 'Bob', compiled_truth: '', timeline: '' });
|
||||
// Create a 2-cycle: alice -> bob -> alice.
|
||||
await engine.addLink('people/alice', 'people/bob', '', 'knows');
|
||||
await engine.addLink('people/bob', 'people/alice', '', 'knows');
|
||||
|
||||
// High depth must NOT loop forever; the visited-set guard bounds the walk.
|
||||
const paths = await engine.traversePaths('people/alice', { direction: 'out', depth: 100 });
|
||||
const edges = new Set(paths.map(p => `${p.from_slug}->${p.to_slug}`));
|
||||
// Both edges of the cycle are reachable exactly once.
|
||||
expect(edges.has('people/alice->people/bob')).toBe(true);
|
||||
expect(edges.has('people/bob->people/alice')).toBe(true);
|
||||
// Bounded: there are only two edges in the graph, so no path explosion.
|
||||
expect(paths.length).toBe(2);
|
||||
});
|
||||
|
||||
test('search backlink boost: well-connected pages rank higher', async () => {
|
||||
// Create 3 pages all matching a search term, but with different inbound link counts.
|
||||
await engine.putPage('topic/popular', {
|
||||
|
||||
@@ -21,6 +21,10 @@ import { hasDatabase, setupDB, teardownDB, getEngine, getConn } from './helpers.
|
||||
const skip = !hasDatabase();
|
||||
const describeE2E = skip ? describe.skip : describe;
|
||||
|
||||
if (skip) {
|
||||
console.log('Skipping E2E JSONB roundtrip tests (DATABASE_URL not set)');
|
||||
}
|
||||
|
||||
describeE2E('E2E: JSONB roundtrip — v0.12.1 reliability wave', () => {
|
||||
beforeAll(async () => { await setupDB(); });
|
||||
afterAll(async () => { await teardownDB(); });
|
||||
|
||||
@@ -56,6 +56,7 @@ describe('E2E: MCP Tool Generation', () => {
|
||||
expect(names).toContain('get_health');
|
||||
expect(names).toContain('sync_brain');
|
||||
expect(names).toContain('file_upload');
|
||||
expect(names).toContain('find_orphans');
|
||||
});
|
||||
|
||||
test('MCP server module can be imported', async () => {
|
||||
|
||||
@@ -175,6 +175,15 @@ describeE2E('E2E: Search', () => {
|
||||
for (const [query, score] of Object.entries(scores)) {
|
||||
console.log(` "${query}": ${(score * 100).toFixed(0)}%`);
|
||||
}
|
||||
|
||||
// Guard value: every known-item query must surface at least one ground-truth
|
||||
// doc in the top 5. This is a deliberately loose floor (not a tuned P@5
|
||||
// threshold) — it catches a total keyword-retrieval regression without
|
||||
// breaking on every scoring/fixture tweak. Without it this test asserted
|
||||
// nothing and a 0%-precision result passed silently.
|
||||
for (const [query, score] of Object.entries(scores)) {
|
||||
expect(score).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -205,10 +214,22 @@ describeE2E('E2E: Links', () => {
|
||||
}, 30_000);
|
||||
|
||||
test('traverse_graph finds connected pages', async () => {
|
||||
// Links should already be added from prior test in this describe block
|
||||
const graph = await callOp('traverse_graph', { slug: 'people/sarah-chen', depth: 2 }) as any;
|
||||
// Self-contained: do not depend on a prior test's add_link. add_link is
|
||||
// idempotent (ON CONFLICT DO NOTHING), so re-adding here is safe whether or
|
||||
// not the round-trip test ran first, and the test no longer false-passes or
|
||||
// false-fails based on describe-block ordering.
|
||||
await callOp('add_link', {
|
||||
from: 'people/sarah-chen',
|
||||
to: 'companies/novamind',
|
||||
link_type: 'founded',
|
||||
});
|
||||
|
||||
const graph = await callOp('traverse_graph', { slug: 'people/sarah-chen', depth: 2 }) as any[];
|
||||
expect(Array.isArray(graph)).toBe(true);
|
||||
expect(graph.length).toBeGreaterThanOrEqual(1);
|
||||
// Content assertion, not just shape: the linked company must be reachable.
|
||||
const reachable = graph.map((n: any) => n.slug ?? n.to_slug ?? n.to_page_slug);
|
||||
expect(reachable).toContain('companies/novamind');
|
||||
});
|
||||
|
||||
test('remove_link removes the link', async () => {
|
||||
@@ -469,8 +490,14 @@ describeE2E('E2E: Admin', () => {
|
||||
test('get_health returns valid structure', async () => {
|
||||
const health = await callOp('get_health') as any;
|
||||
expect(health).toBeDefined();
|
||||
expect(typeof health.page_count).toBe('number');
|
||||
expect(typeof health.embed_coverage).toBe('number');
|
||||
// Value bounds, not just types: page_count must match the fixture inventory
|
||||
// and embed_coverage is a 0..1 fraction (src/commands/doctor.ts multiplies
|
||||
// by 100 and compares to 0.9). Type-only checks let embed_coverage: -9999
|
||||
// through; these catch a genuinely broken health payload.
|
||||
expect(health.page_count).toBe(16);
|
||||
expect(Number.isFinite(health.embed_coverage)).toBe(true);
|
||||
expect(health.embed_coverage).toBeGreaterThanOrEqual(0);
|
||||
expect(health.embed_coverage).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -488,7 +515,17 @@ describeE2E('E2E: Chunks & Resolution', () => {
|
||||
test('get_chunks returns chunks for imported page', async () => {
|
||||
const chunks = await callOp('get_chunks', { slug: 'people/sarah-chen' }) as any[];
|
||||
expect(chunks.length).toBeGreaterThan(0);
|
||||
expect(chunks[0].chunk_text).toBeTruthy();
|
||||
// Content + ordering, not just truthiness (a whitespace-only chunk is truthy):
|
||||
// every chunk has real text and a numeric index, the indexes are
|
||||
// non-decreasing in return order, and the page's own name appears somewhere.
|
||||
for (const c of chunks) {
|
||||
expect(typeof c.chunk_text).toBe('string');
|
||||
expect(c.chunk_text.trim().length).toBeGreaterThan(0);
|
||||
expect(typeof c.chunk_index).toBe('number');
|
||||
}
|
||||
const indexes = chunks.map((c: any) => c.chunk_index);
|
||||
expect(indexes).toEqual([...indexes].sort((x, y) => x - y));
|
||||
expect(chunks.some((c: any) => c.chunk_text.includes('Sarah'))).toBe(true);
|
||||
}, 30_000);
|
||||
|
||||
test('resolve_slugs finds partial match', async () => {
|
||||
@@ -662,9 +699,29 @@ describeE2E('E2E: file_list LIMIT enforcement', () => {
|
||||
}, 30_000);
|
||||
|
||||
test('file_list without slug also respects LIMIT 100', async () => {
|
||||
// The 150 rows from the previous test are still in the DB
|
||||
// Self-sufficient: seed our own >100 rows rather than relying on the
|
||||
// previous test's 150 rows surviving in the DB. A bun reorder, a focused
|
||||
// `-t` run, or a failure mid-insert in the prior test would otherwise leave
|
||||
// this asserting against an indeterminate row count.
|
||||
const sql = getConn();
|
||||
const seedSlug = 'test-limit-noslug';
|
||||
await sql`
|
||||
INSERT INTO pages (slug, title, type, compiled_truth, frontmatter)
|
||||
VALUES (${seedSlug}, ${'Test Limit NoSlug'}, ${'note'}, ${'body'}, ${'{}'}::jsonb)
|
||||
ON CONFLICT (source_id, slug) DO NOTHING
|
||||
`;
|
||||
for (let i = 0; i < 120; i++) {
|
||||
await sql`
|
||||
INSERT INTO files (page_slug, filename, storage_path, mime_type, size_bytes, content_hash, metadata)
|
||||
VALUES (${seedSlug}, ${'nf-' + String(i).padStart(3, '0') + '.txt'}, ${seedSlug + '/nf-' + i + '.txt'}, ${'text/plain'}, ${100}, ${'nhash-' + i}, ${'{}'}::jsonb)
|
||||
ON CONFLICT (storage_path) DO NOTHING
|
||||
`;
|
||||
}
|
||||
const total = await sql`SELECT count(*)::int AS n FROM files`;
|
||||
expect(Number(total[0].n)).toBeGreaterThan(100); // cap is actually exercised
|
||||
|
||||
const files = await callOp('file_list', {}) as any[];
|
||||
expect(files.length).toBeLessThanOrEqual(100);
|
||||
expect(files.length).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+149
-111
@@ -78,6 +78,19 @@ function freshTempHome(label: string) {
|
||||
return dir;
|
||||
}
|
||||
|
||||
// Restore HOME/PATH to the captured originals. Called from each test's
|
||||
// `finally` so a throw mid-test can never leave HOME/PATH pointed at a temp
|
||||
// dir for the rest of the bun process (which would silently break unrelated
|
||||
// suites that read HOME). PATH keeps the shim prepended because the
|
||||
// module-level shim install is what subsequent tests in this suite rely on;
|
||||
// afterAll does the final teardown to the pristine origPath.
|
||||
function restoreHomePath() {
|
||||
if (origHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = origHome;
|
||||
if (origPath === undefined) delete process.env.PATH;
|
||||
else process.env.PATH = `${fakeBinDir}:${origPath ?? ''}`;
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
if (SKIP) {
|
||||
console.log('[migration-flow.e2e] DATABASE_URL not set — skipping.');
|
||||
@@ -100,6 +113,15 @@ afterAll(() => {
|
||||
|
||||
beforeEach(() => {
|
||||
if (SKIP) return;
|
||||
// Robust restore: if a prior test threw before its own finally ran (or
|
||||
// before afterAll), HOME/PATH could still point at a dead temp dir. Reset
|
||||
// them to the captured originals at the start of every test so a throw in
|
||||
// one test can never leak a temp HOME/PATH into sibling suites that read
|
||||
// them. freshTempHome() re-points HOME per test immediately after this.
|
||||
if (origHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = origHome;
|
||||
if (origPath === undefined) delete process.env.PATH;
|
||||
else process.env.PATH = `${fakeBinDir}:${origPath ?? ''}`;
|
||||
try { if (tmp) rmSync(tmp, { recursive: true, force: true }); } catch { /* best-effort */ }
|
||||
});
|
||||
|
||||
@@ -114,144 +136,160 @@ const COMMON_OPTS = {
|
||||
describeE2E('E2E: v0.11.0 orchestrator against live Postgres', () => {
|
||||
test('fresh install flow: schema → smoke → prefs → host-rewrite → completed', async () => {
|
||||
tmp = freshTempHome('fresh');
|
||||
const result = await v0_11_0.orchestrator(COMMON_OPTS);
|
||||
try {
|
||||
const result = await v0_11_0.orchestrator(COMMON_OPTS);
|
||||
|
||||
// Orchestrator returns a structured result (status is `complete` when
|
||||
// no pending-host-work TODOs fired, `partial` otherwise).
|
||||
expect(result.version).toBe('0.11.0');
|
||||
expect(['complete', 'partial']).toContain(result.status);
|
||||
// Orchestrator returns a structured result (status is `complete` when
|
||||
// no pending-host-work TODOs fired, `partial` otherwise).
|
||||
expect(result.version).toBe('0.11.0');
|
||||
expect(['complete', 'partial']).toContain(result.status);
|
||||
|
||||
// Phase D: preferences.json exists with 0o600 + mode=pain_triggered.
|
||||
const prefsPath = join(tmp, '.gbrain', 'preferences.json');
|
||||
expect(existsSync(prefsPath)).toBe(true);
|
||||
expect(statSync(prefsPath).mode & 0o777).toBe(0o600);
|
||||
const prefs = loadPreferences();
|
||||
expect(prefs.minion_mode).toBe('pain_triggered');
|
||||
expect(prefs.set_at).toBeTruthy();
|
||||
expect(prefs.set_in_version).toBeTruthy();
|
||||
// Phase D: preferences.json exists with 0o600 + mode=pain_triggered.
|
||||
const prefsPath = join(tmp, '.gbrain', 'preferences.json');
|
||||
expect(existsSync(prefsPath)).toBe(true);
|
||||
expect(statSync(prefsPath).mode & 0o777).toBe(0o600);
|
||||
const prefs = loadPreferences();
|
||||
expect(prefs.minion_mode).toBe('pain_triggered');
|
||||
expect(prefs.set_at).toBeTruthy();
|
||||
expect(prefs.set_in_version).toBeTruthy();
|
||||
|
||||
// Bug 3 (v0.14.2) — orchestrator no longer writes completed.jsonl.
|
||||
// The runner (apply-migrations.ts) persists the result after the
|
||||
// orchestrator returns. A direct orchestrator call in E2E leaves the
|
||||
// ledger empty; the runner path is tested separately in
|
||||
// test/apply-migrations.test.ts + test/migration-resume.test.ts.
|
||||
const completed = loadCompletedMigrations();
|
||||
const v0110Entries = completed.filter(e => e.version === '0.11.0');
|
||||
expect(v0110Entries.length).toBe(0);
|
||||
// Bug 3 (v0.14.2) — orchestrator no longer writes completed.jsonl.
|
||||
// The runner (apply-migrations.ts) persists the result after the
|
||||
// orchestrator returns. A direct orchestrator call in E2E leaves the
|
||||
// ledger empty; the runner path is tested separately in
|
||||
// test/apply-migrations.test.ts + test/migration-resume.test.ts.
|
||||
const completed = loadCompletedMigrations();
|
||||
const v0110Entries = completed.filter(e => e.version === '0.11.0');
|
||||
expect(v0110Entries.length).toBe(0);
|
||||
|
||||
// Phase F is skipped per COMMON_OPTS — autopilot should NOT have been
|
||||
// installed on this host.
|
||||
expect(result.autopilot_installed).toBe(false);
|
||||
// Phase F is skipped per COMMON_OPTS — autopilot should NOT have been
|
||||
// installed on this host.
|
||||
expect(result.autopilot_installed).toBe(false);
|
||||
} finally {
|
||||
restoreHomePath();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test('idempotent rerun: second invocation is a safe no-op', async () => {
|
||||
tmp = freshTempHome('rerun');
|
||||
const first = await v0_11_0.orchestrator(COMMON_OPTS);
|
||||
expect(['complete', 'partial']).toContain(first.status);
|
||||
try {
|
||||
const first = await v0_11_0.orchestrator(COMMON_OPTS);
|
||||
expect(['complete', 'partial']).toContain(first.status);
|
||||
|
||||
const second = await v0_11_0.orchestrator(COMMON_OPTS);
|
||||
expect(['complete', 'partial']).toContain(second.status);
|
||||
const second = await v0_11_0.orchestrator(COMMON_OPTS);
|
||||
expect(['complete', 'partial']).toContain(second.status);
|
||||
|
||||
// Bug 3 (v0.14.2) — orchestrator does not write completed.jsonl, so
|
||||
// repeated direct invocations don't accumulate ledger entries. Assert
|
||||
// the preferences state stays stable (the real idempotency signal for
|
||||
// this orchestrator is "running again doesn't corrupt preferences").
|
||||
expect(loadPreferences().minion_mode).toBe('pain_triggered');
|
||||
const completed = loadCompletedMigrations();
|
||||
expect(completed.filter(e => e.version === '0.11.0').length).toBe(0);
|
||||
// Bug 3 (v0.14.2) — orchestrator does not write completed.jsonl, so
|
||||
// repeated direct invocations don't accumulate ledger entries. Assert
|
||||
// the preferences state stays stable (the real idempotency signal for
|
||||
// this orchestrator is "running again doesn't corrupt preferences").
|
||||
expect(loadPreferences().minion_mode).toBe('pain_triggered');
|
||||
const completed = loadCompletedMigrations();
|
||||
expect(completed.filter(e => e.version === '0.11.0').length).toBe(0);
|
||||
} finally {
|
||||
restoreHomePath();
|
||||
}
|
||||
}, 90_000);
|
||||
|
||||
test('host rewrite: builtin handlers auto-rewritten, non-builtins queued as JSONL TODOs', async () => {
|
||||
tmp = freshTempHome('host-rewrite');
|
||||
// Fixture: AGENTS.md + cron/jobs.json with a mix of gbrain-builtin and
|
||||
// non-builtin handlers.
|
||||
const claudeDir = join(tmp, '.claude');
|
||||
mkdirSync(claudeDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(claudeDir, 'AGENTS.md'),
|
||||
'# Test AGENTS.md\n\nSome existing content referencing sessions_spawn routing.\n',
|
||||
);
|
||||
mkdirSync(join(claudeDir, 'cron'), { recursive: true });
|
||||
writeFileSync(
|
||||
join(claudeDir, 'cron', 'jobs.json'),
|
||||
JSON.stringify({
|
||||
jobs: [
|
||||
{ schedule: '*/5 * * * *', kind: 'agentTurn', skill: 'sync' }, // builtin
|
||||
{ schedule: '0 */30 * * *', kind: 'agentTurn', skill: 'ea-inbox-sweep' }, // non-builtin
|
||||
{ schedule: '*/10 * * * *', kind: 'agentTurn', skill: 'embed' }, // builtin
|
||||
{ schedule: '0 8 * * *', kind: 'agentTurn', skill: 'morning-briefing' }, // non-builtin
|
||||
],
|
||||
}, null, 2) + '\n',
|
||||
);
|
||||
try {
|
||||
// Fixture: AGENTS.md + cron/jobs.json with a mix of gbrain-builtin and
|
||||
// non-builtin handlers.
|
||||
const claudeDir = join(tmp, '.claude');
|
||||
mkdirSync(claudeDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(claudeDir, 'AGENTS.md'),
|
||||
'# Test AGENTS.md\n\nSome existing content referencing sessions_spawn routing.\n',
|
||||
);
|
||||
mkdirSync(join(claudeDir, 'cron'), { recursive: true });
|
||||
writeFileSync(
|
||||
join(claudeDir, 'cron', 'jobs.json'),
|
||||
JSON.stringify({
|
||||
jobs: [
|
||||
{ schedule: '*/5 * * * *', kind: 'agentTurn', skill: 'sync' }, // builtin
|
||||
{ schedule: '0 */30 * * *', kind: 'agentTurn', skill: 'ea-inbox-sweep' }, // non-builtin
|
||||
{ schedule: '*/10 * * * *', kind: 'agentTurn', skill: 'embed' }, // builtin
|
||||
{ schedule: '0 8 * * *', kind: 'agentTurn', skill: 'morning-briefing' }, // non-builtin
|
||||
],
|
||||
}, null, 2) + '\n',
|
||||
);
|
||||
|
||||
const result = await v0_11_0.orchestrator(COMMON_OPTS);
|
||||
const result = await v0_11_0.orchestrator(COMMON_OPTS);
|
||||
|
||||
// Builtins rewritten in place; non-builtins left alone.
|
||||
const cronAfter = JSON.parse(readFileSync(join(claudeDir, 'cron', 'jobs.json'), 'utf-8'));
|
||||
expect(cronAfter.jobs[0].kind).toBe('shell'); // sync (builtin)
|
||||
expect(cronAfter.jobs[0].cmd).toContain('gbrain jobs submit sync');
|
||||
expect(cronAfter.jobs[1].kind).toBe('agentTurn'); // ea-inbox-sweep (non-builtin)
|
||||
expect(cronAfter.jobs[2].kind).toBe('shell'); // embed (builtin)
|
||||
expect(cronAfter.jobs[3].kind).toBe('agentTurn'); // morning-briefing (non-builtin)
|
||||
// Builtins rewritten in place; non-builtins left alone.
|
||||
const cronAfter = JSON.parse(readFileSync(join(claudeDir, 'cron', 'jobs.json'), 'utf-8'));
|
||||
expect(cronAfter.jobs[0].kind).toBe('shell'); // sync (builtin)
|
||||
expect(cronAfter.jobs[0].cmd).toContain('gbrain jobs submit sync');
|
||||
expect(cronAfter.jobs[1].kind).toBe('agentTurn'); // ea-inbox-sweep (non-builtin)
|
||||
expect(cronAfter.jobs[2].kind).toBe('shell'); // embed (builtin)
|
||||
expect(cronAfter.jobs[3].kind).toBe('agentTurn'); // morning-briefing (non-builtin)
|
||||
|
||||
// files_rewritten counts the 2 builtin rewrites.
|
||||
expect(result.files_rewritten).toBeGreaterThanOrEqual(2);
|
||||
// files_rewritten counts the 2 builtin rewrites.
|
||||
expect(result.files_rewritten).toBeGreaterThanOrEqual(2);
|
||||
|
||||
// pending_host_work counts the 2 non-builtin TODOs.
|
||||
expect(result.pending_host_work).toBe(2);
|
||||
// pending_host_work counts the 2 non-builtin TODOs.
|
||||
expect(result.pending_host_work).toBe(2);
|
||||
|
||||
// Status is "partial" because non-builtin TODOs remain.
|
||||
expect(result.status).toBe('partial');
|
||||
// Status is "partial" because non-builtin TODOs remain.
|
||||
expect(result.status).toBe('partial');
|
||||
|
||||
// AGENTS.md got the marker injected.
|
||||
const agentsMdAfter = readFileSync(join(claudeDir, 'AGENTS.md'), 'utf-8');
|
||||
expect(agentsMdAfter).toContain('gbrain:subagent-routing v0.11.0');
|
||||
expect(agentsMdAfter).toContain('skills/conventions/subagent-routing.md');
|
||||
// AGENTS.md got the marker injected.
|
||||
const agentsMdAfter = readFileSync(join(claudeDir, 'AGENTS.md'), 'utf-8');
|
||||
expect(agentsMdAfter).toContain('gbrain:subagent-routing v0.11.0');
|
||||
expect(agentsMdAfter).toContain('skills/conventions/subagent-routing.md');
|
||||
|
||||
// JSONL TODO file written under ~/.gbrain/migrations/.
|
||||
const jsonlPath = join(tmp, '.gbrain', 'migrations', 'pending-host-work.jsonl');
|
||||
expect(existsSync(jsonlPath)).toBe(true);
|
||||
const lines = readFileSync(jsonlPath, 'utf-8').split('\n').filter(l => l.trim());
|
||||
expect(lines.length).toBe(2);
|
||||
const todos = lines.map(l => JSON.parse(l));
|
||||
const handlers = todos.map(t => t.handler).sort();
|
||||
expect(handlers).toEqual(['ea-inbox-sweep', 'morning-briefing']);
|
||||
for (const todo of todos) {
|
||||
expect(todo.type).toBe('cron-handler-needs-host-registration');
|
||||
expect(todo.status).toBe('pending');
|
||||
expect(todo.manifest_path).toContain('cron/jobs.json');
|
||||
// JSONL TODO file written under ~/.gbrain/migrations/.
|
||||
const jsonlPath = join(tmp, '.gbrain', 'migrations', 'pending-host-work.jsonl');
|
||||
expect(existsSync(jsonlPath)).toBe(true);
|
||||
const lines = readFileSync(jsonlPath, 'utf-8').split('\n').filter(l => l.trim());
|
||||
expect(lines.length).toBe(2);
|
||||
const todos = lines.map(l => JSON.parse(l));
|
||||
const handlers = todos.map(t => t.handler).sort();
|
||||
expect(handlers).toEqual(['ea-inbox-sweep', 'morning-briefing']);
|
||||
for (const todo of todos) {
|
||||
expect(todo.type).toBe('cron-handler-needs-host-registration');
|
||||
expect(todo.status).toBe('pending');
|
||||
expect(todo.manifest_path).toContain('cron/jobs.json');
|
||||
}
|
||||
} finally {
|
||||
restoreHomePath();
|
||||
}
|
||||
}, 90_000);
|
||||
|
||||
test('resumable: partial run → orchestrator re-run → complete', async () => {
|
||||
tmp = freshTempHome('resumable');
|
||||
// Simulate a stopgap-written partial entry BEFORE running the orchestrator.
|
||||
mkdirSync(join(tmp, '.gbrain', 'migrations'), { recursive: true });
|
||||
writeFileSync(
|
||||
join(tmp, '.gbrain', 'migrations', 'completed.jsonl'),
|
||||
JSON.stringify({
|
||||
version: '0.11.0',
|
||||
status: 'partial',
|
||||
apply_migrations_pending: true,
|
||||
mode: 'pain_triggered',
|
||||
source: 'fix-v0.11.0.sh',
|
||||
ts: new Date().toISOString(),
|
||||
}) + '\n',
|
||||
);
|
||||
try {
|
||||
// Simulate a stopgap-written partial entry BEFORE running the orchestrator.
|
||||
mkdirSync(join(tmp, '.gbrain', 'migrations'), { recursive: true });
|
||||
writeFileSync(
|
||||
join(tmp, '.gbrain', 'migrations', 'completed.jsonl'),
|
||||
JSON.stringify({
|
||||
version: '0.11.0',
|
||||
status: 'partial',
|
||||
apply_migrations_pending: true,
|
||||
mode: 'pain_triggered',
|
||||
source: 'fix-v0.11.0.sh',
|
||||
ts: new Date().toISOString(),
|
||||
}) + '\n',
|
||||
);
|
||||
|
||||
// Orchestrator re-running on a partial → should succeed (schema apply
|
||||
// and smoke are idempotent; prefs are preserved from the partial
|
||||
// record; host-rewrite runs its safe-skip pass). Per Bug 3 (v0.14.2),
|
||||
// the orchestrator itself doesn't append to completed.jsonl — the
|
||||
// runner does. The stopgap's partial entry stays unchanged here.
|
||||
const result = await v0_11_0.orchestrator(COMMON_OPTS);
|
||||
expect(['complete', 'partial']).toContain(result.status);
|
||||
// Orchestrator re-running on a partial → should succeed (schema apply
|
||||
// and smoke are idempotent; prefs are preserved from the partial
|
||||
// record; host-rewrite runs its safe-skip pass). Per Bug 3 (v0.14.2),
|
||||
// the orchestrator itself doesn't append to completed.jsonl — the
|
||||
// runner does. The stopgap's partial entry stays unchanged here.
|
||||
const result = await v0_11_0.orchestrator(COMMON_OPTS);
|
||||
expect(['complete', 'partial']).toContain(result.status);
|
||||
|
||||
const completed = loadCompletedMigrations();
|
||||
const v0110 = completed.filter(e => e.version === '0.11.0');
|
||||
// Just the stopgap partial — orchestrator doesn't add its own entry.
|
||||
expect(v0110.length).toBe(1);
|
||||
expect(v0110[0].status).toBe('partial');
|
||||
expect(v0110[0].source).toBe('fix-v0.11.0.sh');
|
||||
const completed = loadCompletedMigrations();
|
||||
const v0110 = completed.filter(e => e.version === '0.11.0');
|
||||
// Just the stopgap partial — orchestrator doesn't add its own entry.
|
||||
expect(v0110.length).toBe(1);
|
||||
expect(v0110[0].status).toBe('partial');
|
||||
expect(v0110[0].source).toBe('fix-v0.11.0.sh');
|
||||
} finally {
|
||||
restoreHomePath();
|
||||
}
|
||||
}, 90_000);
|
||||
});
|
||||
|
||||
@@ -94,7 +94,7 @@ describeE2E('E2E: Minions resilience (OpenClaw real-world patterns)', () => {
|
||||
}, 30_000);
|
||||
|
||||
// --- 2. Runaway handler: ignores AbortSignal, dead-lettered by handleTimeouts ---
|
||||
test('runaway handler: ignores AbortSignal, handleTimeouts dead-letters in <2s', async () => {
|
||||
test('runaway handler: ignores AbortSignal, handleTimeouts dead-letters it', async () => {
|
||||
const { a, b } = await makeEngines();
|
||||
try {
|
||||
const queue = new MinionQueue(a);
|
||||
@@ -133,8 +133,14 @@ describeE2E('E2E: Minions resilience (OpenClaw real-world patterns)', () => {
|
||||
worker.stop();
|
||||
await startP;
|
||||
|
||||
// Correctness gate: the job MUST be dead-lettered with the timeout reason.
|
||||
// We intentionally do NOT assert a wall-clock upper bound (deadAt - started):
|
||||
// on a loaded CI runner the stall/timeout sweep cadence varies, and the only
|
||||
// thing that matters is that the runaway job terminates as 'dead'. The 3s poll
|
||||
// deadline above is the real timeout — if the sweep is too slow, finalStatus
|
||||
// stays '' and this toBe('dead') fails loudly.
|
||||
expect(finalStatus).toBe('dead');
|
||||
expect(deadAt - started).toBeLessThan(2000);
|
||||
void deadAt; // retained for debugging; no timing assertion (flake-prone)
|
||||
|
||||
const final = await queue.getJob(job.id);
|
||||
expect(final?.error_text).toMatch(/timeout exceeded/i);
|
||||
@@ -304,7 +310,7 @@ describeE2E('E2E: Minions resilience (OpenClaw real-world patterns)', () => {
|
||||
}, 60_000);
|
||||
|
||||
// --- 5. Cascade kill under load: cancelJob aborts all live descendants ---
|
||||
test('cascade kill: cancelJob on parent aborts 10 live children within 2s', async () => {
|
||||
test('cascade kill: cancelJob on parent aborts 10 live children', async () => {
|
||||
const { a, b } = await makeEngines();
|
||||
try {
|
||||
const queue = new MinionQueue(a);
|
||||
@@ -374,8 +380,12 @@ describeE2E('E2E: Minions resilience (OpenClaw real-world patterns)', () => {
|
||||
worker.stop();
|
||||
await startP;
|
||||
|
||||
// Correctness gate: all 10 cooperative handlers observed the abort and the
|
||||
// DB shows every descendant + root cancelled. We do NOT assert a wall-clock
|
||||
// upper bound on cancelElapsed — the 3s abort poll deadline above already
|
||||
// bounds the wait, and asserting a tighter time flakes on shared runners.
|
||||
expect(abortedChildren.size).toBe(10);
|
||||
expect(cancelElapsed).toBeLessThan(3000);
|
||||
void cancelElapsed; // retained for debugging; no timing assertion (flake-prone)
|
||||
|
||||
// DB truth: every descendant + root is 'cancelled'
|
||||
const conn = getConn();
|
||||
|
||||
@@ -78,7 +78,11 @@ describeE2E('v0.18.0 multi-source — Postgres schema shape (fresh install)', ()
|
||||
);
|
||||
expect(rows.length).toBe(1);
|
||||
expect(rows[0].is_nullable).toBe('NO');
|
||||
expect(String(rows[0].column_default)).toContain('default');
|
||||
// Postgres renders a TEXT DEFAULT 'default' literal as `'default'::text`.
|
||||
// Assert the exact stored expression rather than a loose substring so a
|
||||
// drift in the schema DEFAULT (e.g. a different sentinel source id) fails
|
||||
// here instead of silently passing.
|
||||
expect(String(rows[0].column_default)).toBe("'default'::text");
|
||||
});
|
||||
|
||||
test('composite UNIQUE pages(source_id, slug) replaces global UNIQUE(slug)', async () => {
|
||||
@@ -292,6 +296,18 @@ describeE2E('v0.18.0 multi-source — cascade delete covers every dependent row'
|
||||
`INSERT INTO files (source_id, page_id, filename, storage_path, content_hash)
|
||||
VALUES ('cascadetest', ${aliceId}, 'alice.pdf', 'cascadetest/people/alice/alice.pdf', 'fh1')`,
|
||||
);
|
||||
const aliceFile = await conn.unsafe(
|
||||
`SELECT id FROM files WHERE source_id = 'cascadetest' AND storage_path = 'cascadetest/people/alice/alice.pdf'`,
|
||||
);
|
||||
const aliceFileId = aliceFile[0].id as number;
|
||||
|
||||
// file_migration_ledger row keyed on the file (FK file_id ON DELETE
|
||||
// CASCADE). Removing the source cascades sources → files → ledger.
|
||||
await conn.unsafe(
|
||||
`INSERT INTO file_migration_ledger (file_id, storage_path_old, storage_path_new, status)
|
||||
VALUES (${aliceFileId}, 'cascadetest/people/alice/alice.pdf', 'cascadetest/people/alice/alice.pdf', 'pending')
|
||||
ON CONFLICT (file_id) DO NOTHING`,
|
||||
);
|
||||
|
||||
// Sanity: everything exists
|
||||
expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM pages WHERE source_id = 'cascadetest'`))[0].n).toBe(2);
|
||||
@@ -299,6 +315,7 @@ describeE2E('v0.18.0 multi-source — cascade delete covers every dependent row'
|
||||
expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM timeline_entries WHERE page_id = ${aliceId}`))[0].n).toBe(1);
|
||||
expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM links WHERE from_page_id = ${aliceId}`))[0].n).toBe(1);
|
||||
expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM files WHERE source_id = 'cascadetest'`))[0].n).toBe(1);
|
||||
expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM file_migration_ledger WHERE file_id = ${aliceFileId}`))[0].n).toBe(1);
|
||||
|
||||
// Remove the source.
|
||||
// v0.26.5: populated sources require --confirm-destructive; --yes alone is rejected.
|
||||
@@ -310,6 +327,7 @@ describeE2E('v0.18.0 multi-source — cascade delete covers every dependent row'
|
||||
expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM timeline_entries WHERE page_id = ${aliceId}`))[0].n).toBe(0);
|
||||
expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM links WHERE from_page_id = ${aliceId}`))[0].n).toBe(0);
|
||||
expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM files WHERE source_id = 'cascadetest'`))[0].n).toBe(0);
|
||||
expect((await conn.unsafe(`SELECT COUNT(*)::int AS n FROM file_migration_ledger WHERE file_id = ${aliceFileId}`))[0].n).toBe(0);
|
||||
|
||||
// The sources row itself is gone.
|
||||
const src = await conn.unsafe(`SELECT id FROM sources WHERE id = 'cascadetest'`);
|
||||
@@ -378,8 +396,10 @@ describeE2E('v0.18.0 multi-source — sync --source routes through sources table
|
||||
|
||||
test('performSync with no sourceId falls back to global sync.repo_path', async () => {
|
||||
const engine = getEngine();
|
||||
// Global config is still '/some/other/default/path' from the
|
||||
// previous test. Without --source, performSync uses it.
|
||||
// Self-contained: set the global config this test depends on directly
|
||||
// instead of inheriting the side effect of the previous test. Without
|
||||
// --source, performSync must read this global key.
|
||||
await engine.setConfig('sync.repo_path', '/some/other/default/path');
|
||||
let err: Error | null = null;
|
||||
try {
|
||||
await performSync(engine, {});
|
||||
|
||||
@@ -112,4 +112,27 @@ describe('v0.29 E2E — getRecentSalience (Garry test)', () => {
|
||||
const rows = await engine.getRecentSalience({ days: 7, slugPrefix: 'nope/does-not-exist/' });
|
||||
expect(rows).toEqual([]);
|
||||
});
|
||||
|
||||
// TIM-37: the daily briefing writes to the vault and re-ingests as
|
||||
// `briefings/<date>`. Without this filter the briefing itself would top
|
||||
// every subsequent Brain Pulse — self-reference with no signal.
|
||||
describe('TIM-37 — briefings excluded from their own Brain Pulse', () => {
|
||||
test('default query hides briefings/* slugs', async () => {
|
||||
await engine.putPage('briefings/2026-05-19', {
|
||||
type: 'note',
|
||||
title: 'Daily Briefing — 2026-05-19',
|
||||
compiled_truth: 'Auto-generated cron briefing.',
|
||||
});
|
||||
const rows = await engine.getRecentSalience({ days: 7, limit: 50 });
|
||||
expect(rows.some(r => r.slug.startsWith('briefings/'))).toBe(false);
|
||||
});
|
||||
|
||||
test('explicit slugPrefix=briefings/ still returns them', async () => {
|
||||
const rows = await engine.getRecentSalience({ days: 7, slugPrefix: 'briefings/' });
|
||||
expect(rows.length).toBeGreaterThan(0);
|
||||
for (const r of rows) {
|
||||
expect(r.slug.startsWith('briefings/')).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -128,6 +128,17 @@ describe('SearchResult fields', () => {
|
||||
expect(r.chunk_index).toBeDefined();
|
||||
expect(typeof r.chunk_index).toBe('number');
|
||||
});
|
||||
|
||||
test('empty keyword query returns a defined array without throwing', async () => {
|
||||
const results = await engine.searchKeyword('');
|
||||
expect(Array.isArray(results)).toBe(true);
|
||||
});
|
||||
|
||||
test('zero vector search returns a defined array without throwing', async () => {
|
||||
const zeroVector = new Float32Array(1536);
|
||||
const results = await engine.searchVector(zeroVector);
|
||||
expect(Array.isArray(results)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('detail parameter', () => {
|
||||
@@ -145,9 +156,11 @@ describe('detail parameter', () => {
|
||||
});
|
||||
|
||||
test('detail=low on vector search filters to compiled_truth', async () => {
|
||||
// Use a timeline-direction embedding — with detail=low, should get no results
|
||||
// or only compiled_truth results
|
||||
// Use a timeline-direction embedding — detail=low filters to compiled_truth.
|
||||
// Vector search returns every chunk with an embedding (ordered by distance),
|
||||
// so the seeded compiled_truth chunks are non-empty and ALL compiled_truth.
|
||||
const results = await engine.searchVector(basisEmbedding(1), { detail: 'low' });
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
for (const r of results) {
|
||||
expect(r.chunk_source).toBe('compiled_truth');
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ import { runSkillOpt } from '../../src/core/skillopt/orchestrator.ts';
|
||||
import {
|
||||
bestPath,
|
||||
loadHistory,
|
||||
proposedPath,
|
||||
skillPath,
|
||||
} from '../../src/core/skillopt/version-store.ts';
|
||||
import { loadRejectedBuffer } from '../../src/core/skillopt/rejected-buffer.ts';
|
||||
@@ -741,7 +742,7 @@ describe('skillopt T3 — F11 held-out gate, ablation opts, no-DB-pollution', ()
|
||||
} finally { fixture.cleanup(); }
|
||||
});
|
||||
|
||||
test('--no-mutate writes proposed.md (best.md), leaves SKILL.md untouched', async () => {
|
||||
test('--no-mutate writes proposed.md and best.md, leaves SKILL.md untouched', async () => {
|
||||
const fixture = setupFixture(SKILL_PEOPLE_ONLY, CITATIONS_BENCHMARK);
|
||||
try {
|
||||
installStub({
|
||||
@@ -753,10 +754,9 @@ describe('skillopt T3 — F11 held-out gate, ablation opts, no-DB-pollution', ()
|
||||
const result = await runOnce(fixture, { noMutate: true });
|
||||
expect(result.outcome).toBe('accepted');
|
||||
expect(result.mutatedSkillFile).toBe(false);
|
||||
expect(result.proposedPath).toBeDefined();
|
||||
// proposed.md (best.md) exists and carries the improvement.
|
||||
expect(fs.existsSync(result.proposedPath!)).toBe(true);
|
||||
expect(result.proposedPath).toBe(proposedPath(fixture.skillsDir, SKILL));
|
||||
expect(fs.readFileSync(result.proposedPath!, 'utf8')).toContain('## Citations');
|
||||
expect(fs.readFileSync(bestPath(fixture.skillsDir, SKILL), 'utf8')).toContain('## Citations');
|
||||
// SKILL.md on disk is UNCHANGED (still People-only).
|
||||
const skill = fs.readFileSync(skillPath(fixture.skillsDir, SKILL), 'utf8');
|
||||
expect(skill).not.toContain('## Citations');
|
||||
|
||||
@@ -73,7 +73,7 @@ describeE2E('E2E: Check-Update', () => {
|
||||
expect(stdout).toContain('--json');
|
||||
});
|
||||
|
||||
test('handles no-releases gracefully (current repo state)', async () => {
|
||||
test('check-update --json contract holds regardless of real release state', async () => {
|
||||
const proc = Bun.spawn(['bun', 'run', 'src/cli.ts', 'check-update', '--json'], {
|
||||
cwd: new URL('../..', import.meta.url).pathname,
|
||||
stdout: 'pipe',
|
||||
@@ -84,8 +84,16 @@ describeE2E('E2E: Check-Update', () => {
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
const output = JSON.parse(stdout);
|
||||
// With no releases, should return false and an error
|
||||
expect(output.update_available).toBe(false);
|
||||
// Don't pin update_available to a literal value — the repo may or may not
|
||||
// have a published release. Assert the JSON shape instead.
|
||||
expect(typeof output.update_available).toBe('boolean');
|
||||
expect(output.current_version).toBe(VERSION);
|
||||
if (output.latest_version != null) {
|
||||
expect(typeof output.latest_version).toBe('string');
|
||||
}
|
||||
if (output.release_url != null) {
|
||||
expect(typeof output.release_url).toBe('string');
|
||||
}
|
||||
});
|
||||
|
||||
test('version comparison wiring works end-to-end', () => {
|
||||
|
||||
@@ -803,3 +803,107 @@ describe('embedAllStale --source threading (D7)', () => {
|
||||
expect((firstCallOpts as { sourceId?: string }).sourceId).toBe('media-corpus');
|
||||
});
|
||||
});
|
||||
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
// Code metadata preservation across re-embed (regression for #769)
|
||||
// ────────────────────────────────────────────────────────────────
|
||||
//
|
||||
// gbrain v0.30.1 and earlier silently clobbered code-chunk metadata
|
||||
// (language, symbol_name, symbol_type, start_line, end_line,
|
||||
// parent_symbol_path, doc_comment, symbol_name_qualified) on every
|
||||
// re-embed pass. The chunker populated those columns at import time,
|
||||
// but embed.ts loaded chunks via getChunks then mapped them to a
|
||||
// stripped ChunkInput carrying only 5 fields. upsertChunks then
|
||||
// OVERWROTE (not COALESCEd) the metadata columns from EXCLUDED, so
|
||||
// re-embed wiped them to NULL. End result on a real brain: 4875 code
|
||||
// pages, 47866 chunks, all with NULL language/symbol_name/symbol_type;
|
||||
// code-def returned 0 hits across every indexed repo.
|
||||
//
|
||||
// All three runEmbed paths (--stale autopilot, --all, --slugs) must
|
||||
// thread metadata through the re-upsert. Tests below assert that the
|
||||
// engine.upsertChunks call carries the same metadata it loaded.
|
||||
|
||||
describe('runEmbed preserves code-chunk metadata across re-embed (regression for #769)', () => {
|
||||
const fullCodeChunk = {
|
||||
chunk_index: 0,
|
||||
chunk_text: '[Java] foo/Bar.java:10-20 method baz',
|
||||
chunk_source: 'compiled_truth' as const,
|
||||
embedded_at: null,
|
||||
token_count: 12,
|
||||
language: 'java',
|
||||
symbol_name: 'baz',
|
||||
symbol_type: 'function',
|
||||
start_line: 10,
|
||||
end_line: 20,
|
||||
parent_symbol_path: ['Bar'],
|
||||
doc_comment: 'does the thing',
|
||||
symbol_name_qualified: 'Bar.baz',
|
||||
};
|
||||
|
||||
function metadataOf(chunk: any) {
|
||||
return {
|
||||
language: chunk.language,
|
||||
symbol_name: chunk.symbol_name,
|
||||
symbol_type: chunk.symbol_type,
|
||||
start_line: chunk.start_line,
|
||||
end_line: chunk.end_line,
|
||||
parent_symbol_path: chunk.parent_symbol_path,
|
||||
doc_comment: chunk.doc_comment,
|
||||
symbol_name_qualified: chunk.symbol_name_qualified,
|
||||
};
|
||||
}
|
||||
|
||||
test('--stale (autopilot path) carries code metadata into upsertChunks', async () => {
|
||||
const stale = [{
|
||||
slug: 'code-page',
|
||||
chunk_index: 0,
|
||||
chunk_text: fullCodeChunk.chunk_text,
|
||||
chunk_source: 'compiled_truth',
|
||||
model: null,
|
||||
token_count: 12,
|
||||
}];
|
||||
let upsertChunkArgs: any[] | null = null;
|
||||
const engine = mockEngine({
|
||||
countStaleChunks: async () => 1,
|
||||
listStaleChunks: async () => stale,
|
||||
getChunks: async () => [fullCodeChunk],
|
||||
upsertChunks: async (_slug: string, chunks: any[]) => { upsertChunkArgs = chunks; },
|
||||
});
|
||||
|
||||
await runEmbed(engine, ['--stale']);
|
||||
|
||||
expect(upsertChunkArgs).not.toBeNull();
|
||||
expect(upsertChunkArgs!).toHaveLength(1);
|
||||
expect(metadataOf(upsertChunkArgs![0])).toEqual(metadataOf(fullCodeChunk));
|
||||
});
|
||||
|
||||
test('--all (full re-embed) carries code metadata into upsertChunks', async () => {
|
||||
let upsertChunkArgs: any[] | null = null;
|
||||
const engine = mockEngine({
|
||||
listPages: async () => [{ slug: 'code-page' }],
|
||||
getChunks: async () => [fullCodeChunk],
|
||||
upsertChunks: async (_slug: string, chunks: any[]) => { upsertChunkArgs = chunks; },
|
||||
});
|
||||
|
||||
await runEmbed(engine, ['--all']);
|
||||
|
||||
expect(upsertChunkArgs).not.toBeNull();
|
||||
expect(upsertChunkArgs!).toHaveLength(1);
|
||||
expect(metadataOf(upsertChunkArgs![0])).toEqual(metadataOf(fullCodeChunk));
|
||||
});
|
||||
|
||||
test('--slugs (per-page embed) carries code metadata into upsertChunks', async () => {
|
||||
let upsertChunkArgs: any[] | null = null;
|
||||
const engine = mockEngine({
|
||||
getPage: async () => ({ slug: 'code-page', compiled_truth: 'x', timeline: '' }),
|
||||
getChunks: async () => [fullCodeChunk],
|
||||
upsertChunks: async (_slug: string, chunks: any[]) => { upsertChunkArgs = chunks; },
|
||||
});
|
||||
|
||||
await runEmbed(engine, ['--slugs', 'code-page']);
|
||||
|
||||
expect(upsertChunkArgs).not.toBeNull();
|
||||
expect(upsertChunkArgs!).toHaveLength(1);
|
||||
expect(metadataOf(upsertChunkArgs![0])).toEqual(metadataOf(fullCodeChunk));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -209,6 +209,32 @@ describe('gbrain extract --stale', () => {
|
||||
expect(usRows[0]?.eq).toBe(true);
|
||||
});
|
||||
|
||||
test('REGRESSION: page with updated_at BEFORE LINK_EXTRACTOR_VERSION_TS clears (no permanent-stale loop)', async () => {
|
||||
// The v112 watermark column ships with no backfill, so every pre-existing
|
||||
// page starts NULL-stale — and most pre-date the version bump. Pre-fix,
|
||||
// extractStaleFromDB stamped links_extracted_at = read updated_at; for a
|
||||
// page edited before LINK_EXTRACTOR_VERSION_TS the stamp landed BELOW the
|
||||
// version threshold, so the version arm (links_extracted_at < versionTs)
|
||||
// re-flagged it stale forever — an infinite re-extract loop that never
|
||||
// cleared the lag (observed: 97% of pages stuck permanently).
|
||||
await engine.putPage('people/alice', personPage('Alice'));
|
||||
await engine.putPage('companies/acme', companyPage('Acme', '[Alice](people/alice) leads [Acme](companies/acme).'));
|
||||
// Backdate every page to BEFORE the extractor version timestamp.
|
||||
await engine.executeRaw(`UPDATE pages SET updated_at = '2020-01-01T00:00:00Z'`);
|
||||
expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(2);
|
||||
|
||||
await runExtract(engine, ['--stale']);
|
||||
// Fixed: stamp = GREATEST(read updated_at, versionTs) → lifts old pages to
|
||||
// the threshold so the version arm clears, while a real future edit still
|
||||
// advances updated_at past the stamp (CDX-1 race protection preserved).
|
||||
expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(0);
|
||||
|
||||
// Second run must ALSO find 0 — the defining symptom of the bug was that it
|
||||
// never converged.
|
||||
await runExtract(engine, ['--stale']);
|
||||
expect(await engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS })).toBe(0);
|
||||
});
|
||||
|
||||
test('CDX-4 (D2): a link-flush throw aborts the sweep and leaves pages UNSTAMPED', async () => {
|
||||
await engine.putPage('people/alice', personPage('Alice'));
|
||||
await engine.putPage('companies/acme', companyPage('Acme', '[Alice](people/alice) founded [Acme](companies/acme).'));
|
||||
|
||||
@@ -273,6 +273,103 @@ describe('writeFactsToFence — stub guard (v0.34.5)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeFactsToFence — basename ≠ slug (#3069)', () => {
|
||||
test('resolves the real file via the page row instead of stub-creating a duplicate', async () => {
|
||||
// Vault file whose basename differs from its slug — the way sync imports
|
||||
// `10-people/Joey Example.md` as slug `10-people/joey-example`.
|
||||
mkdirSync(join(brainDir, '10-people'), { recursive: true });
|
||||
const realPath = join(brainDir, '10-people/Joey Example.md');
|
||||
writeFileSync(
|
||||
realPath,
|
||||
'---\ntype: person\ntitle: Joey Example\nslug: 10-people/joey-example\n---\n\n# Joey Example\n\n## Facts\n\n<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n| 1 | Existing claim | fact | 1.0 | world | medium | 2024-01-01 | | import | |\n<!--- gbrain:facts:end -->\n',
|
||||
'utf-8',
|
||||
);
|
||||
await engine.putPage('10-people/joey-example', {
|
||||
type: 'person',
|
||||
title: 'Joey Example',
|
||||
compiled_truth: '# Joey Example',
|
||||
timeline: '',
|
||||
frontmatter: {},
|
||||
content_hash: 'x',
|
||||
source_path: '10-people/Joey Example.md',
|
||||
import_filename: 'Joey Example',
|
||||
});
|
||||
|
||||
const result = await writeFactsToFence(
|
||||
engine,
|
||||
{ sourceId: 'default', localPath: brainDir, slug: '10-people/joey-example' },
|
||||
[baseInput({ fact: 'New claim after rename' })],
|
||||
);
|
||||
|
||||
expect(result.inserted).toBe(1);
|
||||
expect(result.stubGuardBlocked).toBeUndefined();
|
||||
// No duplicate stub next to the real page.
|
||||
expect(existsSync(join(brainDir, '10-people/joey-example.md'))).toBe(false);
|
||||
// The fact landed on the REAL file, continuing the fence's row_num
|
||||
// sequence (a stub would have restarted at 1 → idx_facts_fence_key
|
||||
// collision against the real page's DB rows).
|
||||
const body = readFileSync(realPath, 'utf-8');
|
||||
expect(body).toContain('New claim after rename');
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const rows = await (engine as any).db.query(
|
||||
`SELECT row_num FROM facts WHERE source_markdown_slug = '10-people/joey-example'`,
|
||||
);
|
||||
expect(rows.rows[0].row_num).toBe(2);
|
||||
});
|
||||
|
||||
test('page row exists but backing file is gone → stubGuardBlocked, no stub created', async () => {
|
||||
await engine.putPage('10-people/ghost-page', {
|
||||
type: 'person',
|
||||
title: 'Ghost',
|
||||
compiled_truth: '',
|
||||
timeline: '',
|
||||
frontmatter: {},
|
||||
content_hash: 'y',
|
||||
source_path: '10-people/Ghost Page.md', // never written to disk
|
||||
import_filename: 'Ghost Page',
|
||||
});
|
||||
|
||||
const result = await writeFactsToFence(
|
||||
engine,
|
||||
{ sourceId: 'default', localPath: brainDir, slug: '10-people/ghost-page' },
|
||||
[baseInput()],
|
||||
);
|
||||
|
||||
expect(result.inserted).toBe(0);
|
||||
expect(result.stubGuardBlocked).toBe(true);
|
||||
expect(existsSync(join(brainDir, '10-people/ghost-page.md'))).toBe(false);
|
||||
});
|
||||
|
||||
test('hostile source_path with ../ cannot steer the fence write outside the source tree', async () => {
|
||||
// A corrupt/hostile page row must not make fence-write read + rename-over
|
||||
// a file OUTSIDE localPath (same threat class write-through guards with
|
||||
// isWriteTargetContained).
|
||||
const victim = join(brainDir, '..', 'fence-victim.md');
|
||||
writeFileSync(victim, '# victim\n', 'utf-8');
|
||||
const before = readFileSync(victim, 'utf-8');
|
||||
await engine.putPage('10-people/evil-row', {
|
||||
type: 'person',
|
||||
title: 'Evil',
|
||||
compiled_truth: '',
|
||||
timeline: '',
|
||||
frontmatter: {},
|
||||
content_hash: 'z',
|
||||
source_path: '../fence-victim.md',
|
||||
import_filename: null,
|
||||
});
|
||||
|
||||
const result = await writeFactsToFence(
|
||||
engine,
|
||||
{ sourceId: 'default', localPath: brainDir, slug: '10-people/evil-row' },
|
||||
[baseInput()],
|
||||
);
|
||||
|
||||
// Escaping candidate is rejected → treated as file-not-found → blocked.
|
||||
expect(result.stubGuardBlocked).toBe(true);
|
||||
expect(readFileSync(victim, 'utf-8')).toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe('lookupSourceLocalPath', () => {
|
||||
test('returns the configured local_path for an existing source', async () => {
|
||||
const got = await lookupSourceLocalPath(engine, 'default');
|
||||
|
||||
@@ -38,6 +38,35 @@ afterAll(() => {
|
||||
});
|
||||
|
||||
describe('importFile', () => {
|
||||
test('normalizes mixed-case importFromContent slug before tag/chunk writes (#2680)', async () => {
|
||||
const engine = mockEngine();
|
||||
|
||||
const result = await importFromContent(engine, 'session/GenerateText-shape-confirmed', `---
|
||||
type: concept
|
||||
title: Mixed Case
|
||||
tags: [llm, shape]
|
||||
---
|
||||
|
||||
Content here.
|
||||
`, { noEmbed: true });
|
||||
|
||||
expect(result.status).toBe('imported');
|
||||
expect(result.slug).toBe('session/generatetext-shape-confirmed');
|
||||
|
||||
const calls = (engine as any)._calls;
|
||||
const putCall = calls.find((c: any) => c.method === 'putPage');
|
||||
expect(putCall.args[0]).toBe('session/generatetext-shape-confirmed');
|
||||
|
||||
const tagCalls = calls.filter((c: any) => c.method === 'addTag');
|
||||
expect(tagCalls.map((c: any) => c.args[0])).toEqual([
|
||||
'session/generatetext-shape-confirmed',
|
||||
'session/generatetext-shape-confirmed',
|
||||
]);
|
||||
|
||||
const chunkCall = calls.find((c: any) => c.method === 'upsertChunks');
|
||||
expect(chunkCall.args[0]).toBe('session/generatetext-shape-confirmed');
|
||||
});
|
||||
|
||||
test('imports a valid markdown file', async () => {
|
||||
const filePath = join(TMP, 'test-page.md');
|
||||
writeFileSync(filePath, `---
|
||||
|
||||
@@ -403,6 +403,77 @@ describe('extractPageLinks', () => {
|
||||
expect(candidates).toEqual([]);
|
||||
});
|
||||
|
||||
test('path-qualified wikilink outside DIR_PATTERN queries by final segment', async () => {
|
||||
// `[[notes/struktura]]` (dir not in DIR_PATTERN) falls to the generic
|
||||
// pass. The resolver's basename index is keyed by final path segments,
|
||||
// so the lookup must strip the dirname — mirroring the FS path
|
||||
// (resolveSlugAll). Regression: the raw literal was passed through,
|
||||
// which never matched, so these links silently dropped.
|
||||
const seen: string[] = [];
|
||||
const resolver: SlugResolver = {
|
||||
resolve: async () => null,
|
||||
resolveBasenameMatches: async (name) => {
|
||||
seen.push(name);
|
||||
return name === 'struktura' ? ['notes/struktura'] : [];
|
||||
},
|
||||
};
|
||||
const { candidates } = await extractPageLinks(
|
||||
'concepts/x', 'See [[notes/struktura]].',
|
||||
{}, 'concept', resolver, { globalBasename: true },
|
||||
);
|
||||
expect(seen).toContain('struktura');
|
||||
expect(seen).not.toContain('notes/struktura');
|
||||
expect(candidates.map(c => c.targetSlug)).toEqual(['notes/struktura']);
|
||||
expect(candidates[0].linkType).toBe('wikilink_basename');
|
||||
expect(candidates[0].linkSource).toBe('wikilink-resolved');
|
||||
});
|
||||
|
||||
test('path-qualified wikilink keeps only matches ending with the written path', async () => {
|
||||
// The written path disambiguates: `[[notes/struktura]]` must never
|
||||
// attach to `wiki/struktura` even though both share the basename.
|
||||
const resolver: SlugResolver = {
|
||||
resolve: async () => null,
|
||||
resolveBasenameMatches: async (name) =>
|
||||
name === 'struktura' ? ['notes/struktura', 'wiki/struktura'] : [],
|
||||
};
|
||||
const { candidates } = await extractPageLinks(
|
||||
'concepts/x', 'See [[notes/struktura]].',
|
||||
{}, 'concept', resolver, { globalBasename: true },
|
||||
);
|
||||
expect(candidates.map(c => c.targetSlug)).toEqual(['notes/struktura']);
|
||||
});
|
||||
|
||||
test('path-qualified wikilink matches a deeper real slug by path suffix', async () => {
|
||||
// The page lives at vault/notes/struktura; the author wrote the shorter
|
||||
// tail `[[notes/struktura]]`. Suffix matching connects them, while the
|
||||
// basename-only sibling `wiki/struktura` stays excluded.
|
||||
const resolver: SlugResolver = {
|
||||
resolve: async () => null,
|
||||
resolveBasenameMatches: async (name) =>
|
||||
name === 'struktura' ? ['vault/notes/struktura', 'wiki/struktura'] : [],
|
||||
};
|
||||
const { candidates } = await extractPageLinks(
|
||||
'concepts/x', 'See [[notes/struktura]].',
|
||||
{}, 'concept', resolver, { globalBasename: true },
|
||||
);
|
||||
expect(candidates.map(c => c.targetSlug)).toEqual(['vault/notes/struktura']);
|
||||
});
|
||||
|
||||
test('path-qualified self-link is dropped like the bare form', async () => {
|
||||
// `[[notes/struktura]]` written on notes/struktura itself must not
|
||||
// produce a self-loop (same guard as the bare `[[own-tail]]` case).
|
||||
const resolver: SlugResolver = {
|
||||
resolve: async () => null,
|
||||
resolveBasenameMatches: async (name) =>
|
||||
name === 'struktura' ? ['notes/struktura'] : [],
|
||||
};
|
||||
const { candidates } = await extractPageLinks(
|
||||
'notes/struktura', 'See [[notes/struktura]].',
|
||||
{}, 'concept', resolver, { globalBasename: true },
|
||||
);
|
||||
expect(candidates).toEqual([]);
|
||||
});
|
||||
|
||||
test('bare wikilink resolution does not interfere with DIR_PATTERN wikilinks', async () => {
|
||||
// 2b refs (people/alice) take the verb-inferred type;
|
||||
// 2c refs (struktura) take wikilink_basename. Same call.
|
||||
@@ -1165,6 +1236,43 @@ describe('makeResolver — fallback chain', () => {
|
||||
const out = await r.resolveBasenameMatches!('struktura');
|
||||
expect(out.sort()).toEqual(['notes/struktura', 'struktura']);
|
||||
});
|
||||
|
||||
test('opts.sourceId is forwarded to findByTitleFuzzy (twin of #1436 fix)', async () => {
|
||||
// Captures every (name, dirPrefix, minSimilarity, sourceId) call so we
|
||||
// can assert the resolver threads sourceId through. Without the wire-up,
|
||||
// findByTitleFuzzy would be called with sourceId=undefined and the SQL
|
||||
// could return cross-source slug suggestions that the FK filter
|
||||
// downstream silently drops.
|
||||
const calls: Array<{ name: string; dirPrefix?: string; minSimilarity?: number; sourceId?: string }> = [];
|
||||
const engine = {
|
||||
async getPage() { return null; },
|
||||
async findByTitleFuzzy(name: string, dirPrefix?: string, minSimilarity?: number, sourceId?: string) {
|
||||
calls.push({ name, dirPrefix, minSimilarity, sourceId });
|
||||
return null;
|
||||
},
|
||||
async searchKeyword() { return []; },
|
||||
} as unknown as BrainEngine;
|
||||
const r = makeResolver(engine, { mode: 'batch', sourceId: 'src-a' });
|
||||
await r.resolve('Alice Example', 'people');
|
||||
expect(calls.length).toBeGreaterThan(0);
|
||||
expect(calls.every(c => c.sourceId === 'src-a')).toBe(true);
|
||||
});
|
||||
|
||||
test('opts.sourceId omitted → findByTitleFuzzy receives undefined (back-compat)', async () => {
|
||||
const calls: Array<{ sourceId?: string }> = [];
|
||||
const engine = {
|
||||
async getPage() { return null; },
|
||||
async findByTitleFuzzy(_name: string, _dirPrefix?: string, _min?: number, sourceId?: string) {
|
||||
calls.push({ sourceId });
|
||||
return null;
|
||||
},
|
||||
async searchKeyword() { return []; },
|
||||
} as unknown as BrainEngine;
|
||||
const r = makeResolver(engine, { mode: 'batch' });
|
||||
await r.resolve('Alice Example', 'people');
|
||||
expect(calls.length).toBeGreaterThan(0);
|
||||
expect(calls.every(c => c.sourceId === undefined)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('FRONTMATTER_LINK_MAP integrity', () => {
|
||||
|
||||
@@ -32,6 +32,29 @@ describe('lintContent', () => {
|
||||
expect(issues.some(i => i.rule === 'code-fence-wrap')).toBe(true);
|
||||
});
|
||||
|
||||
test('no false positive: page CONTAINS an inner ```markdown code block', () => {
|
||||
// Real-world case: a docs/SKILL page that shows a markdown example inline.
|
||||
// Before this fix, the detector used the /m flag so ^/$ matched start/end
|
||||
// of any line, which fired on any file that simply contained a ```markdown
|
||||
// line. But fixContent's regex has no /m flag and can only strip whole-file
|
||||
// wrappers, so the issue was reported as "fixable: true" yet never fixed.
|
||||
const content =
|
||||
'---\ntitle: Skill\n---\n\n# Skill\n\nExample input shape:\n\n' +
|
||||
'```markdown\n# Inner page\nContent.\n```\n\nThat ends the example.\n';
|
||||
const issues = lintContent(content, 'test.md');
|
||||
expect(issues.filter(i => i.rule === 'code-fence-wrap')).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('no false positive: multiple inner ```markdown blocks', () => {
|
||||
// Documentation pages frequently include several markdown examples.
|
||||
const content =
|
||||
'---\ntitle: Examples\n---\n\n# Examples\n\nFirst:\n\n' +
|
||||
'```markdown\nfoo\n```\n\nSecond:\n\n' +
|
||||
'```markdown\nbar\n```\n\nDone.\n';
|
||||
const issues = lintContent(content, 'test.md');
|
||||
expect(issues.filter(i => i.rule === 'code-fence-wrap')).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('detects placeholder dates', () => {
|
||||
const content = '---\ntitle: Test\ntype: person\ncreated: YYYY-MM-DD\n---\n\n# Test';
|
||||
const issues = lintContent(content, 'test.md');
|
||||
|
||||
@@ -9,6 +9,7 @@ import { loadConfigWithEngine, type GBrainConfig } from '../src/core/config.ts';
|
||||
|
||||
interface FakeEngine {
|
||||
getConfig(key: string): Promise<string | null | undefined>;
|
||||
listConfigKeys?(prefix: string): Promise<string[]>;
|
||||
}
|
||||
|
||||
function makeEngine(map: Record<string, string | null | undefined>): FakeEngine {
|
||||
@@ -16,6 +17,9 @@ function makeEngine(map: Record<string, string | null | undefined>): FakeEngine
|
||||
async getConfig(key: string) {
|
||||
return map[key];
|
||||
},
|
||||
async listConfigKeys(prefix: string) {
|
||||
return Object.keys(map).filter(key => key.startsWith(prefix));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -92,6 +96,31 @@ describe('loadConfigWithEngine (Phase 4 / F3)', () => {
|
||||
expect(merged?.embedding_image_ocr).toBe(true);
|
||||
});
|
||||
|
||||
test('DB provider_base_urls.<provider> fills the gateway base URL map', async () => {
|
||||
const base: GBrainConfig = { engine: 'pglite' };
|
||||
const engine = makeEngine({
|
||||
'provider_base_urls.llama-server-reranker': 'http://127.0.0.1:8091/v1',
|
||||
});
|
||||
const merged = await loadConfigWithEngine(engine, base);
|
||||
expect(merged?.provider_base_urls?.['llama-server-reranker']).toBe('http://127.0.0.1:8091/v1');
|
||||
});
|
||||
|
||||
test('provider_base_urls merge is per-provider: file value wins and DB fills siblings', async () => {
|
||||
const base: GBrainConfig = {
|
||||
engine: 'pglite',
|
||||
provider_base_urls: {
|
||||
'llama-server-reranker': 'http://file.example/v1',
|
||||
},
|
||||
};
|
||||
const engine = makeEngine({
|
||||
'provider_base_urls.llama-server-reranker': 'http://db.example/v1',
|
||||
'provider_base_urls.openrouter': 'http://openrouter.example/v1',
|
||||
});
|
||||
const merged = await loadConfigWithEngine(engine, base);
|
||||
expect(merged?.provider_base_urls?.['llama-server-reranker']).toBe('http://file.example/v1');
|
||||
expect(merged?.provider_base_urls?.openrouter).toBe('http://openrouter.example/v1');
|
||||
});
|
||||
|
||||
test('engine.getConfig throwing is non-fatal — file/env config still returned', async () => {
|
||||
const base: GBrainConfig = {
|
||||
engine: 'pglite',
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
extractCycleFreshnessSourceIds,
|
||||
parseMaintainArgs,
|
||||
} from '../src/commands/maintain.ts';
|
||||
import type { Check } from '../src/commands/doctor.ts';
|
||||
|
||||
describe('maintain args', () => {
|
||||
test('defaults to dry-run unless --safe is explicit', () => {
|
||||
expect(parseMaintainArgs([])).toMatchObject({
|
||||
safe: false,
|
||||
dryRun: true,
|
||||
json: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('--safe enables mutating safe mode', () => {
|
||||
expect(parseMaintainArgs(['--safe', '--json'])).toMatchObject({
|
||||
safe: true,
|
||||
dryRun: false,
|
||||
json: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('--dry-run wins over --safe', () => {
|
||||
expect(parseMaintainArgs(['--safe', '--dry-run'])).toMatchObject({
|
||||
safe: true,
|
||||
dryRun: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('cycle freshness source extraction', () => {
|
||||
test('extracts stale source ids from doctor messages', () => {
|
||||
const checks: Check[] = [
|
||||
{
|
||||
name: 'cycle_freshness',
|
||||
status: 'fail',
|
||||
message: "Source 'brain-sync-remote-teffur' last cycled 40h ago. Run `gbrain dream --source <id>`.",
|
||||
},
|
||||
{
|
||||
name: 'cycle_freshness',
|
||||
status: 'fail',
|
||||
message: "Source 'wiki' last cycled 25h ago. Source 'wiki' last cycled 25h ago.",
|
||||
},
|
||||
];
|
||||
|
||||
expect(extractCycleFreshnessSourceIds(checks)).toEqual([
|
||||
'brain-sync-remote-teffur',
|
||||
'wiki',
|
||||
]);
|
||||
});
|
||||
|
||||
test('ignores ok and unrelated checks', () => {
|
||||
const checks: Check[] = [
|
||||
{ name: 'cycle_freshness', status: 'ok', message: "Source 'fresh' last cycled recently." },
|
||||
{ name: 'frontmatter_integrity', status: 'warn', message: "Source 'wiki' has frontmatter issues." },
|
||||
];
|
||||
|
||||
expect(extractCycleFreshnessSourceIds(checks)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -132,7 +132,7 @@ describe('runNightlyQualityProbe (DI stub harness)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('enabled + recent run within 24h → outcome: rate_limited', async () => {
|
||||
test('enabled + recent run within 24h → outcome: rate_limited (no audit row for the skip)', async () => {
|
||||
// Pre-seed a recent audit event by running the probe once first.
|
||||
await withEnv({ GBRAIN_AUDIT_DIR: auditTmp }, async () => {
|
||||
// First run succeeds.
|
||||
@@ -140,9 +140,28 @@ describe('runNightlyQualityProbe (DI stub harness)', () => {
|
||||
// Second run, same hour → rate_limited.
|
||||
const r2 = await runNightlyQualityProbe(makeDeps());
|
||||
expect(r2.outcome).toBe('rate_limited');
|
||||
// #3064: the skip does NOT log an audit row — autopilot ticks every
|
||||
// ~5 min, so skip rows would spam the JSONL and (pre-fix) re-arm the
|
||||
// 24h window on every tick, muting the probe forever after one run.
|
||||
const events = await readEvents();
|
||||
expect(events.length).toBe(2);
|
||||
expect(events[1].outcome).toBe('rate_limited');
|
||||
expect(events.length).toBe(1);
|
||||
expect(events[0].outcome).toBe('pass');
|
||||
});
|
||||
});
|
||||
|
||||
test('#3064 regression: historical rate_limited skip rows do NOT re-arm the 24h window', async () => {
|
||||
await withEnv({ GBRAIN_AUDIT_DIR: auditTmp }, async () => {
|
||||
const { logQualityProbeEvent } = await import('../src/core/audit-quality-probe.ts');
|
||||
const now = new Date();
|
||||
const zero = { exit_code: 0, pass_count: 0, fail_count: 0, inconclusive_count: 0, error_count: 0, est_cost_usd: 0 };
|
||||
// Real run 25h ago (outside the window)...
|
||||
logQualityProbeEvent({ outcome: 'pass', ts: new Date(now.getTime() - 25 * 3600_000).toISOString(), ...zero });
|
||||
// ...plus skip rows a pre-fix brain logged on every autopilot tick.
|
||||
logQualityProbeEvent({ outcome: 'rate_limited', ts: new Date(now.getTime() - 10 * 60_000).toISOString(), ...zero });
|
||||
logQualityProbeEvent({ outcome: 'rate_limited', ts: new Date(now.getTime() - 5 * 60_000).toISOString(), ...zero });
|
||||
|
||||
const r = await runNightlyQualityProbe(makeDeps({ now: () => now }));
|
||||
expect(r.outcome).toBe('pass'); // pre-fix: 'rate_limited' forever
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
describe('root OpenClaw plugin manifest', () => {
|
||||
it('declares the id required by OpenClaw plugin installs', () => {
|
||||
const manifest = JSON.parse(readFileSync(join(import.meta.dir, '..', 'openclaw.plugin.json'), 'utf8'));
|
||||
const entrySource = readFileSync(join(import.meta.dir, '..', 'src', 'openclaw-context-engine.ts'), 'utf8');
|
||||
const entryId = entrySource.match(/id:\s*'([^']+)'/)?.[1];
|
||||
|
||||
expect(manifest.id).toBe(entryId);
|
||||
expect(manifest.configSchema).toBeDefined();
|
||||
expect(typeof manifest.configSchema).toBe('object');
|
||||
expect(manifest.contracts?.contextEngines).toContain('gbrain-context');
|
||||
expect(entrySource).toContain('export function register');
|
||||
});
|
||||
});
|
||||
@@ -186,11 +186,67 @@ describe('shouldExclude — orphan filter regression (preserve curation)', () =>
|
||||
expect(shouldExclude('entities/anonymous')).toBe(true);
|
||||
expect(shouldExclude('atoms/fact-123')).toBe(true);
|
||||
expect(shouldExclude('skills/gbrain-operations')).toBe(true);
|
||||
expect(shouldExclude('dreaming/light/2026-07-20')).toBe(true);
|
||||
expect(shouldExclude('daily/2026-07-20')).toBe(true);
|
||||
expect(shouldExclude('agent-openclaw/daily/2026-07-20')).toBe(true);
|
||||
});
|
||||
|
||||
test('workspace convention slugs are excluded', () => {
|
||||
expect(shouldExclude('_brain-conventions')).toBe(true);
|
||||
expect(shouldExclude('_templates/decision')).toBe(true);
|
||||
expect(shouldExclude('extracts/2026-06-30/takes.proposed/round-single')).toBe(true);
|
||||
expect(shouldExclude('2026-07-20')).toBe(true);
|
||||
expect(shouldExclude('2026-07-20-qa-sweep')).toBe(true);
|
||||
expect(shouldExclude('agents/arya/identity')).toBe(true);
|
||||
expect(shouldExclude('agents/arya/memory/dreaming/deep/2026-07-20')).toBe(true);
|
||||
});
|
||||
|
||||
test('regular slugs are NOT excluded', () => {
|
||||
expect(shouldExclude('people/alice')).toBe(false);
|
||||
expect(shouldExclude('companies/acme')).toBe(false);
|
||||
expect(shouldExclude('writing/post-1')).toBe(false);
|
||||
expect(shouldExclude('agents/arya/qa-reports/launch-review')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getHealth orphan_pages uses shared exclusion policy', () => {
|
||||
test('excluded convention islands do not count against health', async () => {
|
||||
await engine.putPage('_templates/decision', {
|
||||
type: 'template', title: 'Decision', compiled_truth: 'template', timeline: '', frontmatter: {},
|
||||
});
|
||||
await engine.putPage('skills/arya/source-check', {
|
||||
type: 'concept', title: 'Skill', compiled_truth: 'skill', timeline: '', frontmatter: {},
|
||||
});
|
||||
await engine.putPage('agents/arya/identity', {
|
||||
type: 'note', title: 'Identity', compiled_truth: 'identity', timeline: '', frontmatter: {},
|
||||
});
|
||||
await engine.putPage('people/alice', {
|
||||
type: 'person', title: 'Alice', compiled_truth: 'real island', timeline: '', frontmatter: {},
|
||||
});
|
||||
|
||||
const health = await engine.getHealth();
|
||||
|
||||
expect(health.orphan_pages).toBe(1);
|
||||
});
|
||||
|
||||
test('per-brain config overrides (orphans.exclude_*) also apply to health', async () => {
|
||||
await engine.putPage('my-private-folder/secret-ref', {
|
||||
type: 'note', title: 'Ref', compiled_truth: 'ref', timeline: '', frontmatter: {},
|
||||
});
|
||||
await engine.putPage('one-off-fixture-page', {
|
||||
type: 'note', title: 'Fixture', compiled_truth: 'fixture', timeline: '', frontmatter: {},
|
||||
});
|
||||
await engine.putPage('people/alice', {
|
||||
type: 'person', title: 'Alice', compiled_truth: 'real island', timeline: '', frontmatter: {},
|
||||
});
|
||||
|
||||
expect((await engine.getHealth()).orphan_pages).toBe(3);
|
||||
|
||||
await engine.setConfig('orphans.exclude_prefixes', 'my-private-folder/');
|
||||
await engine.setConfig('orphans.exclude_slugs', 'one-off-fixture-page');
|
||||
expect((await engine.getHealth()).orphan_pages).toBe(1);
|
||||
|
||||
await engine.unsetConfig('orphans.exclude_prefixes');
|
||||
await engine.unsetConfig('orphans.exclude_slugs');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -66,6 +66,10 @@ describe('shouldExclude', () => {
|
||||
expect(shouldExclude('templates/meeting-note')).toBe(true);
|
||||
});
|
||||
|
||||
test('excludes deny-prefix: _templates/', () => {
|
||||
expect(shouldExclude('_templates/meeting-note')).toBe(true);
|
||||
});
|
||||
|
||||
test('excludes deny-prefix: openclaw/config/', () => {
|
||||
expect(shouldExclude('openclaw/config/agent')).toBe(true);
|
||||
});
|
||||
@@ -86,10 +90,44 @@ describe('shouldExclude', () => {
|
||||
expect(shouldExclude('entities/product-hunt')).toBe(true);
|
||||
});
|
||||
|
||||
test('excludes first-segment: skills, dreaming, and daily', () => {
|
||||
expect(shouldExclude('skills/arya/source-check')).toBe(true);
|
||||
expect(shouldExclude('dreaming/light/2026-07-20')).toBe(true);
|
||||
expect(shouldExclude('daily/2026-07-20')).toBe(true);
|
||||
expect(shouldExclude('agent-openclaw/daily/2026-07-20')).toBe(true);
|
||||
});
|
||||
|
||||
test('excludes root date logs and agent workspace conventions', () => {
|
||||
expect(shouldExclude('_brain-conventions')).toBe(true);
|
||||
expect(shouldExclude('2026-07-20')).toBe(true);
|
||||
expect(shouldExclude('2026-07-20-qa-sweep')).toBe(true);
|
||||
expect(shouldExclude('agents/arya/identity')).toBe(true);
|
||||
expect(shouldExclude('agents/arya/memory/dreaming/deep/2026-07-20')).toBe(true);
|
||||
});
|
||||
|
||||
test('excludes generated extracts', () => {
|
||||
expect(shouldExclude('extracts/2026-06-30/takes.proposed/round-single')).toBe(true);
|
||||
});
|
||||
|
||||
test('brain-specific exclusions come from config overrides, not global defaults', () => {
|
||||
// No baked-in defaults for these:
|
||||
expect(shouldExclude('my-private-folder/some-secret-ref.md')).toBe(false);
|
||||
expect(shouldExclude('one-off-fixture-page')).toBe(false);
|
||||
// The per-brain config plane (orphans.exclude_prefixes / exclude_slugs):
|
||||
const overrides = {
|
||||
excludePrefixes: ['my-private-folder/'],
|
||||
excludeSlugs: ['one-off-fixture-page'],
|
||||
};
|
||||
expect(shouldExclude('my-private-folder/some-secret-ref.md', overrides)).toBe(true);
|
||||
expect(shouldExclude('one-off-fixture-page', overrides)).toBe(true);
|
||||
expect(shouldExclude('people/jane-doe', overrides)).toBe(false);
|
||||
});
|
||||
|
||||
test('does NOT exclude a normal content page', () => {
|
||||
expect(shouldExclude('companies/acme')).toBe(false);
|
||||
expect(shouldExclude('people/jane-doe')).toBe(false);
|
||||
expect(shouldExclude('projects/gbrain')).toBe(false);
|
||||
expect(shouldExclude('agents/arya/qa-reports/launch-review')).toBe(false);
|
||||
});
|
||||
|
||||
test('does NOT exclude a page ending with log-like text that is not /log', () => {
|
||||
|
||||
@@ -1264,6 +1264,7 @@ describe('PGLiteEngine: getHealth graph metrics', () => {
|
||||
await engine.putPage('people/alice', { ...testPage, type: 'person', title: 'Alice' });
|
||||
await engine.putPage('people/bob', { ...testPage, type: 'person', title: 'Bob' });
|
||||
await engine.putPage('companies/acme', { ...testPage, type: 'company', title: 'Acme' });
|
||||
await engine.putPage('entities/project-x', { ...testPage, type: 'entity', title: 'Project X' });
|
||||
});
|
||||
|
||||
test('link_coverage = 0 when no links exist', async () => {
|
||||
@@ -1272,17 +1273,17 @@ describe('PGLiteEngine: getHealth graph metrics', () => {
|
||||
});
|
||||
|
||||
test('link_coverage = % of entity pages with >= 1 inbound link', async () => {
|
||||
// Acme gets 1 inbound link (from Alice), Alice/Bob get 0 inbound.
|
||||
// 1 of 3 entity pages has inbound links -> 33%.
|
||||
// Acme gets 1 inbound link (from Alice), Alice/Bob/Reddit get 0 inbound.
|
||||
// 1 of 4 entity pages has inbound links -> 25%.
|
||||
await engine.addLink('people/alice', 'companies/acme', '', 'works_at');
|
||||
const h = await engine.getHealth();
|
||||
expect(h.link_coverage).toBeCloseTo(1 / 3, 2);
|
||||
expect(h.link_coverage).toBeCloseTo(1 / 4, 2);
|
||||
});
|
||||
|
||||
test('timeline_coverage = % with >= 1 timeline entry', async () => {
|
||||
await engine.addTimelineEntry('people/alice', { date: '2026-01-15', summary: 'Joined' });
|
||||
const h = await engine.getHealth();
|
||||
expect(h.timeline_coverage).toBeCloseTo(1 / 3, 2);
|
||||
expect(h.timeline_coverage).toBeCloseTo(1 / 4, 2);
|
||||
});
|
||||
|
||||
test('most_connected lists top entities by link count', async () => {
|
||||
@@ -1295,14 +1296,14 @@ describe('PGLiteEngine: getHealth graph metrics', () => {
|
||||
});
|
||||
|
||||
test('orphan_pages: pages with neither inbound nor outbound links', async () => {
|
||||
// All 3 pages start with no links. Expect 3 orphans.
|
||||
// All 4 pages start with no links. Expect 4 orphans.
|
||||
const h = await engine.getHealth();
|
||||
expect(h.orphan_pages).toBe(3);
|
||||
expect(h.orphan_pages).toBe(4);
|
||||
|
||||
// Add alice -> acme. Alice has outbound, acme has inbound, only Bob is orphan.
|
||||
// Add alice -> acme. Alice has outbound, acme has inbound, Bob and Reddit are orphan.
|
||||
await engine.addLink('people/alice', 'companies/acme', '', 'works_at');
|
||||
const h2 = await engine.getHealth();
|
||||
expect(h2.orphan_pages).toBe(1);
|
||||
expect(h2.orphan_pages).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -109,7 +109,7 @@ describe('pglite-lock #2058 heartbeat + steal-grace', () => {
|
||||
if (existsSync(TEST_DIR)) rmSync(TEST_DIR, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function writeHolder(fields: { pid: number; acquiredAgoMs: number; refreshedAgoMs: number }) {
|
||||
function writeHolder(fields: { pid: number; acquiredAgoMs: number; refreshedAgoMs: number; command?: string }) {
|
||||
const lockDir = join(TEST_DIR, '.gbrain-lock');
|
||||
mkdirSync(lockDir, { recursive: true });
|
||||
const now = Date.now();
|
||||
@@ -117,7 +117,7 @@ describe('pglite-lock #2058 heartbeat + steal-grace', () => {
|
||||
pid: fields.pid,
|
||||
acquired_at: now - fields.acquiredAgoMs,
|
||||
refreshed_at: now - fields.refreshedAgoMs,
|
||||
command: 'test holder',
|
||||
command: fields.command ?? 'test holder',
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -146,6 +146,26 @@ describe('pglite-lock #2058 heartbeat + steal-grace', () => {
|
||||
expect(existsSync(join(TEST_DIR, '.gbrain-lock'))).toBe(true);
|
||||
});
|
||||
|
||||
test('explains live gbrain serve contention is not a sync advisory lock', async () => {
|
||||
writeHolder({
|
||||
pid: process.pid,
|
||||
acquiredAgoMs: 60_000,
|
||||
refreshedAgoMs: 0,
|
||||
command: 'bun /Users/master/.bun/bin/gbrain serve',
|
||||
});
|
||||
|
||||
let message = '';
|
||||
try {
|
||||
await acquireLock(TEST_DIR, { timeoutMs: 100 });
|
||||
} catch (error) {
|
||||
message = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
expect(message).toContain('serve↔sync contention');
|
||||
expect(message).toContain('not the `gbrain-sync:*` advisory lock');
|
||||
expect(message).toContain('`gbrain sync --break-lock` will not clear a live PGLite holder');
|
||||
expect(existsSync(join(TEST_DIR, '.gbrain-lock'))).toBe(true);
|
||||
});
|
||||
|
||||
test('[REGRESSION] releaseLock does NOT remove a lock that was stolen + re-acquired by another process', async () => {
|
||||
// We acquire, then simulate a steal: another process reaped us past grace
|
||||
// and now owns the lock (different pid + acquired_at). Our releaseLock must
|
||||
|
||||
@@ -218,15 +218,21 @@ describe('progress reporter', () => {
|
||||
test('only one process-level signal handler installed across many reporters', () => {
|
||||
// Baseline: one handler already installed by prior tests in this file.
|
||||
const installedBefore = __signalHandlerInstalledForTest();
|
||||
// liveReporters is module-global, so a reporter left running by ANOTHER
|
||||
// test file in the same shard shows up here. Assert the DELTA (these 50
|
||||
// lifecycles leak nothing) instead of an absolute zero — the absolute
|
||||
// form flaked whenever shard composition changed and an unrelated file
|
||||
// held a live reporter across this test.
|
||||
const liveBefore = __liveReporterCountForTest();
|
||||
const { stream } = sink(false);
|
||||
for (let i = 0; i < 50; i++) {
|
||||
const p = createProgress({ mode: 'json', stream, minIntervalMs: 0, minItems: 1 });
|
||||
p.start(`phase_${i}`, 1);
|
||||
p.finish();
|
||||
}
|
||||
// After 50 reporter lifecycles, still exactly one handler and zero leaked live entries.
|
||||
// After 50 reporter lifecycles, still exactly one handler and no new live entries.
|
||||
expect(__signalHandlerInstalledForTest()).toBe(installedBefore || true);
|
||||
expect(__liveReporterCountForTest()).toBe(0);
|
||||
expect(__liveReporterCountForTest()).toBe(liveBefore);
|
||||
});
|
||||
|
||||
test('startHeartbeat() fires heartbeats and stop() clears', async () => {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user