mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-15 09:22:18 +00:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c275fa3fab | ||
|
|
ee095f1ca2 | ||
|
|
5f123c1404 | ||
|
|
d9eb027bdd | ||
|
|
62e009d192 | ||
|
|
314fefa560 | ||
|
|
7f841fae7f | ||
|
|
1fabbb9849 | ||
|
|
64920f83c9 | ||
|
|
e861b92da7 | ||
|
|
948ccc7b4f |
@@ -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" },
|
||||
};
|
||||
|
||||
+50
-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', 'bench', '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
|
||||
@@ -104,6 +106,9 @@ const CLI_ONLY_SELF_HELP = new Set([
|
||||
// `gbrain connect --help` prints its own usage (flags + examples) from
|
||||
// runConnect; route around the generic one-line short-circuit.
|
||||
'connect',
|
||||
// #1474: bench-publish ships its own detailed HELP (flags, exit codes,
|
||||
// the export → publish → gate loop). Route around the generic stub.
|
||||
'bench',
|
||||
]);
|
||||
|
||||
// v114 (#1941): alias -> operation lookup, kept separate from `cliOps` so
|
||||
@@ -1427,6 +1432,29 @@ async function handleCliOnly(command: string, args: string[]) {
|
||||
return;
|
||||
}
|
||||
|
||||
// #1474: `gbrain bench publish` is pure file I/O (reads a captured
|
||||
// eval-candidates NDJSON from `gbrain eval export`, writes a baseline
|
||||
// NDJSON). No DB access; bypass connectEngine entirely so the documented
|
||||
// export → publish → gate loop works on machines without a brain.
|
||||
// The v0.41.1 wave shipped bench-publish.ts + docs/eval-bench.md but this
|
||||
// dispatcher case was never added, so the command hit 'Unknown command'.
|
||||
if (command === 'bench') {
|
||||
if (args[0] === 'publish') {
|
||||
const { runBenchPublish } = await import('./commands/bench-publish.ts');
|
||||
await runBenchPublish(args.slice(1));
|
||||
return;
|
||||
}
|
||||
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
||||
const { runBenchPublish } = await import('./commands/bench-publish.ts');
|
||||
await runBenchPublish(['--help']);
|
||||
return;
|
||||
}
|
||||
console.error(`Unknown bench subcommand: ${args[0]}`);
|
||||
console.error('Usage: gbrain bench publish --from <captured.ndjson> --to <baseline.ndjson> [flags]');
|
||||
console.error(' See docs/eval-bench.md for the full loop: eval export → bench publish → eval gate');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
// v0.42.x (#2390): `gbrain eval chronicle` is deterministic — brings its own
|
||||
// in-memory PGLite, no DB/gateway. CI fixture gate runs anywhere.
|
||||
if (command === 'eval' && args[0] === 'chronicle') {
|
||||
@@ -1757,6 +1785,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.
|
||||
@@ -2217,6 +2250,22 @@ async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEngin
|
||||
if (merged.embedding_image_ocr_model !== undefined) {
|
||||
process.env.GBRAIN_EMBEDDING_IMAGE_OCR_MODEL = merged.embedding_image_ocr_model;
|
||||
}
|
||||
// #1475: stash the merged eval.* flags the same way. The capture gate
|
||||
// (isEvalCaptureEnabled / isEvalScrubEnabled) runs against ctx.config,
|
||||
// which is built from the sync file-plane loadConfig() in both the CLI
|
||||
// op path and MCP dispatch — it never sees the DB plane directly. The
|
||||
// gates consult this stash when the file plane is silent, so
|
||||
// `gbrain config set eval.capture true` actually turns capture on.
|
||||
// A pre-set env value wins over the DB plane (env-above-config, the
|
||||
// incident escape hatch) — unlike GBRAIN_EMBEDDING_MULTIMODAL these
|
||||
// keys have no loadConfig() env mapping, so without this guard the
|
||||
// DB stash would silently clobber an operator's export.
|
||||
if (process.env.GBRAIN_EVAL_CAPTURE === undefined && merged.eval?.capture !== undefined) {
|
||||
process.env.GBRAIN_EVAL_CAPTURE = String(merged.eval.capture);
|
||||
}
|
||||
if (process.env.GBRAIN_EVAL_SCRUB_PII === undefined && merged.eval?.scrub_pii !== undefined) {
|
||||
process.env.GBRAIN_EVAL_SCRUB_PII = String(merged.eval.scrub_pii);
|
||||
}
|
||||
// Always re-configure with merged values when DB merge succeeded. The
|
||||
// trigger used to be field-name-gated (only when embedding_multimodal_model
|
||||
// was set); that coupled the gate to the field set and would silently
|
||||
|
||||
+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
|
||||
`);
|
||||
}
|
||||
|
||||
+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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.');
|
||||
}
|
||||
}
|
||||
+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,
|
||||
|
||||
@@ -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`
|
||||
@@ -1547,111 +1511,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
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -816,6 +816,25 @@ export async function loadConfigWithEngine(
|
||||
merged.dream = mergedDream;
|
||||
}
|
||||
|
||||
// #1475: eval.* DB-plane merge. `gbrain config set eval.capture true`
|
||||
// writes the DB plane (both keys are in KNOWN_CONFIG_KEYS, so `set`
|
||||
// accepts them silently), but the capture gate (isEvalCaptureEnabled)
|
||||
// reads the merged config. Without this merge the DB value was written
|
||||
// and never read — capture only fired via GBRAIN_CONTRIBUTOR_MODE=1.
|
||||
// Sparse per-key merge: file/env wins per key, DB fills the gaps.
|
||||
const dbEvalCapture = await dbBool('eval.capture');
|
||||
const dbEvalScrub = await dbBool('eval.scrub_pii');
|
||||
const mergedEval: NonNullable<GBrainConfig['eval']> = { ...(merged.eval ?? {}) };
|
||||
if (mergedEval.capture === undefined && dbEvalCapture !== undefined) {
|
||||
mergedEval.capture = dbEvalCapture;
|
||||
}
|
||||
if (mergedEval.scrub_pii === undefined && dbEvalScrub !== undefined) {
|
||||
mergedEval.scrub_pii = dbEvalScrub;
|
||||
}
|
||||
if (Object.keys(mergedEval).length > 0) {
|
||||
merged.eval = mergedEval;
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ import {
|
||||
import {
|
||||
generatePerChunkSynopsis,
|
||||
SYNOPSIS_PROMPT_VERSION,
|
||||
SYNOPSIS_DOC_MAX_CHARS,
|
||||
type GeneratePerChunkSynopsisResult,
|
||||
} from './page-summary.ts';
|
||||
import {
|
||||
@@ -103,8 +104,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 +123,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -253,7 +265,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 +298,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 ───────────────────────────
|
||||
|
||||
@@ -251,6 +251,14 @@ registerBackgroundWorkDrainer({
|
||||
export function isEvalCaptureEnabled(config: GBrainConfig | null | undefined): boolean {
|
||||
if (config?.eval?.capture === true) return true;
|
||||
if (config?.eval?.capture === false) return false;
|
||||
// #1475: DB-plane stash. `gbrain config set eval.capture true` lands in the
|
||||
// config table; connectEngine stamps the merged value here because
|
||||
// ctx.config is the sync file-plane load and never sees the DB plane.
|
||||
// Explicit per-key setting (file above, DB here) beats the broad
|
||||
// CONTRIBUTOR_MODE flag, matching how file-plane `false` already wins.
|
||||
// Doubles as a direct operator env knob.
|
||||
if (process.env.GBRAIN_EVAL_CAPTURE === 'true') return true;
|
||||
if (process.env.GBRAIN_EVAL_CAPTURE === 'false') return false;
|
||||
return process.env.GBRAIN_CONTRIBUTOR_MODE === '1';
|
||||
}
|
||||
|
||||
@@ -263,5 +271,8 @@ export function isEvalCaptureEnabled(config: GBrainConfig | null | undefined): b
|
||||
* have explicit `capture: true`.
|
||||
*/
|
||||
export function isEvalScrubEnabled(config: GBrainConfig | null | undefined): boolean {
|
||||
return config?.eval?.scrub_pii !== false;
|
||||
if (config?.eval?.scrub_pii === false) return false;
|
||||
if (config?.eval?.scrub_pii === true) return true;
|
||||
// #1475: DB-plane stash — see isEvalCaptureEnabled. Default stays true.
|
||||
return process.env.GBRAIN_EVAL_SCRUB_PII !== 'false';
|
||||
}
|
||||
|
||||
@@ -733,6 +733,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;
|
||||
|
||||
@@ -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(',')}}`;
|
||||
|
||||
@@ -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>',
|
||||
|
||||
+30
-19
@@ -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,
|
||||
@@ -2322,6 +2324,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 +2351,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
|
||||
@@ -5207,15 +5213,10 @@ export class PGLiteEngine implements BrainEngine {
|
||||
(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,
|
||||
@@ -5240,10 +5241,20 @@ export class PGLiteEngine implements BrainEngine {
|
||||
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 +5282,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,
|
||||
|
||||
+33
-22
@@ -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],
|
||||
@@ -5313,11 +5322,9 @@ 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')
|
||||
@@ -5326,13 +5333,8 @@ export class PostgresEngine implements BrainEngine {
|
||||
(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,
|
||||
@@ -5356,9 +5358,18 @@ export class PostgresEngine implements BrainEngine {
|
||||
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 +5397,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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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,67 @@
|
||||
// #1474: the v0.41.1 wave shipped bench-publish.ts + docs/eval-bench.md
|
||||
// advertising `gbrain bench publish`, but the cli.ts dispatcher case was never
|
||||
// added — the documented command hit 'Unknown command'. These tests spawn the
|
||||
// real CLI (no DB needed; bench publish is pure file I/O) and fail on any
|
||||
// regression of the dispatcher wiring.
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { mkdtempSync, writeFileSync, existsSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
function runCli(args: string[]): { stdout: string; stderr: string; code: number } {
|
||||
const result = spawnSync(process.execPath, ['run', 'src/cli.ts', 'bench', ...args], {
|
||||
encoding: 'utf8',
|
||||
cwd: process.cwd(),
|
||||
env: { ...process.env },
|
||||
});
|
||||
return { stdout: result.stdout ?? '', stderr: result.stderr ?? '', code: result.status ?? -1 };
|
||||
}
|
||||
|
||||
describe('gbrain bench dispatcher (#1474)', () => {
|
||||
test('bench --help reaches bench-publish help without a DB (was: Unknown command)', () => {
|
||||
const { stdout, stderr, code } = runCli(['--help']);
|
||||
expect(stderr).not.toContain('Unknown command');
|
||||
expect(code).toBe(0);
|
||||
expect(stdout).toContain('gbrain bench publish');
|
||||
expect(stdout).toContain('--from');
|
||||
});
|
||||
|
||||
test('unknown bench subcommand exits 2 with usage', () => {
|
||||
const { stderr, code } = runCli(['bogus']);
|
||||
expect(code).toBe(2);
|
||||
expect(stderr).toContain('Unknown bench subcommand');
|
||||
expect(stderr).toContain('bench publish');
|
||||
});
|
||||
|
||||
test('bench publish roundtrip: captured NDJSON in, baseline file out', () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), 'bench-cli-'));
|
||||
try {
|
||||
const row = {
|
||||
tool_name: 'query',
|
||||
query: 'hello world',
|
||||
retrieved_slugs: ['slug-a'],
|
||||
retrieved_chunk_ids: [1],
|
||||
source_ids: ['default'],
|
||||
expand_enabled: false,
|
||||
detail: 'medium',
|
||||
detail_resolved: 'medium',
|
||||
vector_enabled: true,
|
||||
expansion_applied: false,
|
||||
latency_ms: 100,
|
||||
remote: false,
|
||||
job_id: null,
|
||||
subagent_id: null,
|
||||
};
|
||||
const from = join(tmp, 'captured.ndjson');
|
||||
const to = join(tmp, 'personal.baseline.ndjson');
|
||||
writeFileSync(from, `${JSON.stringify(row)}\n`);
|
||||
const { code, stderr } = runCli(['publish', '--from', from, '--to', to]);
|
||||
expect(stderr).not.toContain('Unknown command');
|
||||
expect(code).toBe(0);
|
||||
expect(existsSync(to)).toBe(true);
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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',
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -309,3 +309,62 @@ describe('isEvalCaptureEnabled / isEvalScrubEnabled (CONTRIBUTOR_MODE-gated)', (
|
||||
} finally { restore(); }
|
||||
});
|
||||
});
|
||||
|
||||
describe('DB-plane stash (#1475): GBRAIN_EVAL_CAPTURE / GBRAIN_EVAL_SCRUB_PII', () => {
|
||||
// connectEngine stamps `gbrain config set eval.capture` (DB plane) onto
|
||||
// these env vars because ctx.config is the sync file-plane load. Without
|
||||
// the stash check the DB value was written and never read.
|
||||
const origCapture = process.env.GBRAIN_EVAL_CAPTURE;
|
||||
const origScrub = process.env.GBRAIN_EVAL_SCRUB_PII;
|
||||
const origMode = process.env.GBRAIN_CONTRIBUTOR_MODE;
|
||||
const restore = () => {
|
||||
if (origCapture === undefined) delete process.env.GBRAIN_EVAL_CAPTURE;
|
||||
else process.env.GBRAIN_EVAL_CAPTURE = origCapture;
|
||||
if (origScrub === undefined) delete process.env.GBRAIN_EVAL_SCRUB_PII;
|
||||
else process.env.GBRAIN_EVAL_SCRUB_PII = origScrub;
|
||||
if (origMode === undefined) delete process.env.GBRAIN_CONTRIBUTOR_MODE;
|
||||
else process.env.GBRAIN_CONTRIBUTOR_MODE = origMode;
|
||||
};
|
||||
|
||||
test('stash=true turns capture on when file plane is silent (the #1475 repro)', () => {
|
||||
delete process.env.GBRAIN_CONTRIBUTOR_MODE;
|
||||
process.env.GBRAIN_EVAL_CAPTURE = 'true';
|
||||
try {
|
||||
expect(isEvalCaptureEnabled(null)).toBe(true);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const noEval: any = { engine: 'pglite' };
|
||||
expect(isEvalCaptureEnabled(noEval)).toBe(true);
|
||||
} finally { restore(); }
|
||||
});
|
||||
|
||||
test('stash=false wins over CONTRIBUTOR_MODE=1 (explicit per-key beats broad flag)', () => {
|
||||
process.env.GBRAIN_CONTRIBUTOR_MODE = '1';
|
||||
process.env.GBRAIN_EVAL_CAPTURE = 'false';
|
||||
try {
|
||||
expect(isEvalCaptureEnabled(null)).toBe(false);
|
||||
} finally { restore(); }
|
||||
});
|
||||
|
||||
test('file-plane explicit value still wins over the stash', () => {
|
||||
process.env.GBRAIN_EVAL_CAPTURE = 'true';
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const disabled: any = { engine: 'pglite', eval: { capture: false } };
|
||||
expect(isEvalCaptureEnabled(disabled)).toBe(false);
|
||||
} finally { restore(); }
|
||||
});
|
||||
|
||||
test('scrub stash: false disables, file plane wins, default stays true', () => {
|
||||
process.env.GBRAIN_EVAL_SCRUB_PII = 'false';
|
||||
try {
|
||||
expect(isEvalScrubEnabled(null)).toBe(false);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const fileWins: any = { engine: 'pglite', eval: { scrub_pii: true } };
|
||||
expect(isEvalScrubEnabled(fileWins)).toBe(true);
|
||||
} finally { restore(); }
|
||||
delete process.env.GBRAIN_EVAL_SCRUB_PII;
|
||||
try {
|
||||
expect(isEvalScrubEnabled(null)).toBe(true);
|
||||
} finally { restore(); }
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -302,4 +302,29 @@ describe('loadConfigWithEngine (Phase 4 / F3)', () => {
|
||||
expect(merged?.engine).toBe('pglite');
|
||||
});
|
||||
});
|
||||
|
||||
describe('eval.* DB-plane merge (#1475)', () => {
|
||||
test('gbrain config set eval.capture true reaches the merged config', async () => {
|
||||
// The #1475 repro: DB plane has eval.capture=true, file plane silent.
|
||||
// Pre-fix the merge skipped eval.* entirely and capture never fired.
|
||||
const base: GBrainConfig = { engine: 'pglite' };
|
||||
const engine = makeEngine({ 'eval.capture': 'true', 'eval.scrub_pii': 'false' });
|
||||
const merged = await loadConfigWithEngine(engine, base);
|
||||
expect(merged?.eval?.capture).toBe(true);
|
||||
expect(merged?.eval?.scrub_pii).toBe(false);
|
||||
});
|
||||
|
||||
test('file plane wins per key; DB fills only the gaps', async () => {
|
||||
const base: GBrainConfig = { engine: 'pglite', eval: { capture: false } };
|
||||
const engine = makeEngine({ 'eval.capture': 'true', 'eval.scrub_pii': 'false' });
|
||||
const merged = await loadConfigWithEngine(engine, base);
|
||||
expect(merged?.eval?.capture).toBe(false); // file wins
|
||||
expect(merged?.eval?.scrub_pii).toBe(false); // DB fills the gap
|
||||
});
|
||||
|
||||
test('no eval keys anywhere leaves cfg.eval undefined', async () => {
|
||||
const merged = await loadConfigWithEngine(makeEngine({}), { engine: 'pglite' });
|
||||
expect(merged?.eval).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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 process-global: earlier test files in the same shard
|
||||
// can leave a live entry behind (e.g. a production path that skips
|
||||
// finish() on an error branch). Assert NET-zero leak from THIS test's
|
||||
// lifecycles, not an absolute zero we don't control — same tolerance
|
||||
// the handler assertion below already applies via `installedBefore`.
|
||||
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 zero NEWLY leaked live entries.
|
||||
expect(__signalHandlerInstalledForTest()).toBe(installedBefore || true);
|
||||
expect(__liveReporterCountForTest()).toBe(0);
|
||||
expect(__liveReporterCountForTest()).toBe(liveBefore);
|
||||
});
|
||||
|
||||
test('startHeartbeat() fires heartbeats and stop() clears', async () => {
|
||||
|
||||
@@ -12,9 +12,11 @@ import {
|
||||
bestPath,
|
||||
historyPath,
|
||||
loadHistory,
|
||||
proposedPath,
|
||||
revertAllPending,
|
||||
skillPath,
|
||||
versionsDir,
|
||||
writeProposed,
|
||||
} from '../../src/core/skillopt/version-store.ts';
|
||||
|
||||
let tmpDir: string;
|
||||
@@ -79,6 +81,19 @@ describe('acceptCandidate (D8 two-phase commit)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeProposed', () => {
|
||||
test('writes distinct best and proposed artifacts without mutating SKILL.md (#2635)', () => {
|
||||
const candidate = '---\nname: test\n---\nproposed body\n';
|
||||
|
||||
const written = writeProposed(tmpDir, SKILL, candidate);
|
||||
|
||||
expect(written).toBe(proposedPath(tmpDir, SKILL));
|
||||
expect(fs.readFileSync(bestPath(tmpDir, SKILL), 'utf8')).toBe(candidate);
|
||||
expect(fs.readFileSync(proposedPath(tmpDir, SKILL), 'utf8')).toBe(candidate);
|
||||
expect(fs.readFileSync(skillPath(tmpDir, SKILL), 'utf8')).toContain('baseline body');
|
||||
});
|
||||
});
|
||||
|
||||
describe('revertAllPending (D8 crash recovery)', () => {
|
||||
test('no-op when no pending rows', () => {
|
||||
const reverted = revertAllPending(tmpDir, SKILL);
|
||||
|
||||
Reference in New Issue
Block a user