mirror of
https://github.com/garrytan/gbrain.git
synced 2026-08-16 01:42:23 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b45023dba |
Vendored
-56
File diff suppressed because one or more lines are too long
Vendored
+57
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-CoGEje3-.js"></script>
|
||||
<script type="module" crossorigin src="/admin/assets/index-CzLjRij_.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/admin/assets/index-GxkWX7v3.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -39,6 +39,7 @@ export const api = {
|
||||
stats: () => apiFetch('/admin/api/stats'),
|
||||
health: () => apiFetch('/admin/api/health-indicators'),
|
||||
agents: () => apiFetch('/admin/api/agents'),
|
||||
sources: () => apiFetch('/admin/api/sources'),
|
||||
requests: (page = 1, qs = '') => apiFetch(`/admin/api/requests?page=${page}${qs}`),
|
||||
apiKeys: () => apiFetch('/admin/api/api-keys'),
|
||||
createApiKey: (name: string) => apiFetch('/admin/api/api-keys', { method: 'POST', body: JSON.stringify({ name }) }),
|
||||
|
||||
@@ -23,9 +23,16 @@ interface Agent {
|
||||
total_requests: number;
|
||||
requests_today: number;
|
||||
token_ttl: number | null;
|
||||
source_id: string | null;
|
||||
federated_read: string[] | null;
|
||||
status: 'active' | 'revoked';
|
||||
}
|
||||
|
||||
interface SourceOption {
|
||||
id: string;
|
||||
name: string | null;
|
||||
}
|
||||
|
||||
interface ApiKey {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -88,6 +95,7 @@ export function AgentsPage() {
|
||||
<th>Name</th>
|
||||
<th>Type</th>
|
||||
<th>Scopes</th>
|
||||
<th>Source</th>
|
||||
<th>Status</th>
|
||||
<th>Requests</th>
|
||||
<th>Last Used</th>
|
||||
@@ -108,6 +116,9 @@ export function AgentsPage() {
|
||||
<span key={s} className={`badge badge-${s}`} style={{ marginRight: 4 }}>{s}</span>
|
||||
))}
|
||||
</td>
|
||||
<td className="mono" style={{ fontSize: 12, color: 'var(--text-secondary)' }}>
|
||||
{a.auth_type === 'oauth' ? (a.source_id || 'default') : 'all'}
|
||||
</td>
|
||||
<td>
|
||||
<span className={`badge ${a.status === 'active' ? 'badge-success' : 'badge-danger'}`}>{a.status}</span>
|
||||
</td>
|
||||
@@ -257,9 +268,29 @@ function RegisterModal({ onClose, onRegistered }: {
|
||||
Object.fromEntries(ALLOWED_SCOPES_LIST.map(s => [s, s === 'read'])) as Record<Scope, boolean>,
|
||||
);
|
||||
const [ttl, setTtl] = useState('86400'); // 24h default
|
||||
const [redirectUris, setRedirectUris] = useState('');
|
||||
const [sources, setSources] = useState<SourceOption[]>([{ id: 'default', name: 'default' }]);
|
||||
const [sourceId, setSourceId] = useState('default');
|
||||
const [readSources, setReadSources] = useState<Record<string, boolean>>({ default: true });
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
api.sources()
|
||||
.then((rows: SourceOption[]) => {
|
||||
const nextSources = rows.length > 0 ? rows : [{ id: 'default', name: 'default' }];
|
||||
const nextSourceId = nextSources.some(s => s.id === sourceId) ? sourceId : nextSources[0].id;
|
||||
setSources(nextSources);
|
||||
setSourceId(nextSourceId);
|
||||
setReadSources(prev => {
|
||||
const next = Object.fromEntries(nextSources.map(s => [s.id, Boolean(prev[s.id])])) as Record<string, boolean>;
|
||||
next[nextSourceId] = true;
|
||||
return next;
|
||||
});
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const ttlOptions = [
|
||||
{ label: '1 hour', value: '3600' },
|
||||
{ label: '24 hours', value: '86400' },
|
||||
@@ -277,11 +308,24 @@ function RegisterModal({ onClose, onRegistered }: {
|
||||
try {
|
||||
// Use the CLI registration endpoint (POST to admin API)
|
||||
const selectedScopes = Object.entries(scopes).filter(([, v]) => v).map(([k]) => k).join(' ');
|
||||
const federatedRead = sources.map(s => s.id).filter(id => readSources[id]);
|
||||
if (federatedRead.length === 0) { setError('Select at least one read source'); setLoading(false); return; }
|
||||
// #1036: redirect URIs, one per line. Mirrors the CLI convention
|
||||
// (src/commands/auth.ts): presence of redirect URIs implies
|
||||
// authorization_code + refresh_token grants unless the user had none.
|
||||
const uris = redirectUris.split('\n').map(u => u.trim()).filter(Boolean);
|
||||
const res = await fetch('/admin/api/register-client', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: name.trim(), scopes: selectedScopes, tokenTtl: ttl === '0' ? 315360000 : Number(ttl) }),
|
||||
body: JSON.stringify({
|
||||
name: name.trim(),
|
||||
scopes: selectedScopes,
|
||||
tokenTtl: ttl === '0' ? 315360000 : Number(ttl),
|
||||
source_id: sourceId,
|
||||
federated_read: federatedRead,
|
||||
...(uris.length > 0 ? { redirectUris: uris, grantTypes: ['authorization_code', 'refresh_token'] } : {}),
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error('Registration failed');
|
||||
const data = await res.json();
|
||||
@@ -312,6 +356,42 @@ function RegisterModal({ onClose, onRegistered }: {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label>Write Source</label>
|
||||
<select value={sourceId} onChange={e => {
|
||||
const id = e.target.value;
|
||||
setSourceId(id);
|
||||
setReadSources(p => ({ ...p, [id]: true }));
|
||||
}}
|
||||
style={{ width: '100%', background: 'var(--bg-secondary)', color: 'var(--text-primary)', border: '1px solid var(--border)', borderRadius: 6, padding: '6px 10px', fontSize: 14 }}>
|
||||
{sources.map(s => <option key={s.id} value={s.id}>{s.name && s.name !== s.id ? `${s.id} (${s.name})` : s.id}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label>Read Sources</label>
|
||||
<div className="checkbox-group">
|
||||
{sources.map(s => (
|
||||
<label key={s.id} className="checkbox-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(readSources[s.id])}
|
||||
onChange={e => setReadSources(p => ({ ...p, [s.id]: e.target.checked }))}
|
||||
/>
|
||||
{s.name && s.name !== s.id ? `${s.id} (${s.name})` : s.id}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label>Redirect URIs <span style={{ color: 'var(--text-secondary)', fontWeight: 400 }}>(optional, one per line — enables authorization_code flow)</span></label>
|
||||
<textarea
|
||||
placeholder={'https://example.com/callback'}
|
||||
value={redirectUris}
|
||||
onChange={e => setRedirectUris(e.target.value)}
|
||||
rows={2}
|
||||
style={{ width: '100%', background: 'var(--bg-secondary)', color: 'var(--text-primary)', border: '1px solid var(--border)', borderRadius: 6, padding: '6px 10px', fontSize: 13, fontFamily: 'inherit', resize: 'vertical' }}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<label>Token Lifetime</label>
|
||||
<select value={ttl} onChange={e => setTtl(e.target.value)}
|
||||
@@ -528,6 +608,8 @@ function AgentDrawer({ agent, onClose, onRevoked }: { agent: Agent; onClose: ()
|
||||
client_name: agentName,
|
||||
auth_type: agent.auth_type,
|
||||
scope: agent.scope,
|
||||
source_id: agent.source_id,
|
||||
federated_read: agent.federated_read,
|
||||
}, null, 2),
|
||||
};
|
||||
|
||||
@@ -547,6 +629,10 @@ function AgentDrawer({ agent, onClose, onRevoked }: { agent: Agent; onClose: ()
|
||||
<span>{(agent.scope || '').split(' ').filter(Boolean).map(s => (
|
||||
<span key={s} className={`badge badge-${s}`} style={{ marginRight: 4 }}>{s}</span>
|
||||
))}</span>
|
||||
<span style={{ color: 'var(--text-secondary)' }}>Write Source</span>
|
||||
<span className="mono">{agent.source_id || (isOAuth ? 'default' : 'all')}</span>
|
||||
<span style={{ color: 'var(--text-secondary)' }}>Read Sources</span>
|
||||
<span className="mono">{isOAuth ? (agent.federated_read && agent.federated_read.length > 0 ? agent.federated_read.join(', ') : (agent.source_id || 'default')) : 'all'}</span>
|
||||
<span style={{ color: 'var(--text-secondary)' }}>Registered</span>
|
||||
<span>{new Date(agent.created_at).toLocaleDateString()}</span>
|
||||
<span style={{ color: 'var(--text-secondary)' }}>Token TTL</span>
|
||||
|
||||
+1
-3
@@ -1411,8 +1411,7 @@ This is the dispatcher. Skills are the implementation. **Read the skill file bef
|
||||
| "get more out of gbrain", "is my brain set up right", "weekly brain checkup", "advise me on my brain", "gbrain advisor" | `skills/gbrain-advisor/SKILL.md` |
|
||||
| Save or load reports | `skills/reports/SKILL.md` |
|
||||
| "Create a skill", "improve this skill" | `skills/skill-creator/SKILL.md` |
|
||||
| "save this learning to the vault", "capture this skill in Obsidian", "record this workflow in my notes", "put this setup change in the vault" | `skills/skill-vault-capture-policy/SKILL.md` |
|
||||
| "Skillify this", "is this a skill?", "make this proper", "add tests and evals for this" | `skills/skillify/SKILL.md` |
|
||||
| "Skillify this", "is this a skill?", "make this proper" | `skills/skillify/SKILL.md` |
|
||||
| "Compress my resolver", "AGENTS.md too large", "RESOLVER.md too big", "functional area dispatcher", "shrink routing table" | `skills/functional-area-resolver/SKILL.md` |
|
||||
| "Is gbrain healthy?", morning health check, skillpack-check | `skills/skillpack-check/SKILL.md` |
|
||||
| "harvest this skill into gbrain", "publish this skill to gbrain", "lift this skill upstream", "share this skill with other gbrain clients", "promote my skill to gbrain" | `skills/skillpack-harvest/SKILL.md` |
|
||||
@@ -1430,7 +1429,6 @@ This is the dispatcher. Skills are the implementation. **Read the skill file bef
|
||||
| "Set up GBrain", first boot | `skills/setup/SKILL.md` |
|
||||
| "Now what?", "fill my brain", "cold start", "bootstrap", "import my data", "what should I import first" | `skills/cold-start/SKILL.md` |
|
||||
| "Migrate from Obsidian/Notion/Logseq" | `skills/migrate/SKILL.md` |
|
||||
| "Connect Obsidian to gbrain", "import my vault to gbrain", "sync vault and gbrain", "embed gbrain after vault update", "is gbrain synced with my vault" | `skills/obsidian-gbrain-safe-index/SKILL.md` |
|
||||
| Brain health check, maintenance run | `skills/maintain/SKILL.md` |
|
||||
| "Extract links", "build link graph", "populate timeline" | `skills/maintain/SKILL.md` (extraction sections) |
|
||||
| "Run dream", "process today's session", "synthesize my conversations", "consolidate yesterday's conversations", "what patterns did you see", "did the dream cycle run" | `skills/maintain/SKILL.md` (dream cycle section) |
|
||||
|
||||
@@ -39,8 +39,8 @@
|
||||
"skills/briefing",
|
||||
"skills/citation-fixer",
|
||||
"skills/concept-synthesis",
|
||||
"skills/cron-scheduler",
|
||||
"skills/cross-modal-review",
|
||||
"skills/cron-scheduler",
|
||||
"skills/daily-task-manager",
|
||||
"skills/daily-task-prep",
|
||||
"skills/data-research",
|
||||
@@ -54,11 +54,10 @@
|
||||
"skills/media-ingest",
|
||||
"skills/meeting-ingestion",
|
||||
"skills/minion-orchestrator",
|
||||
"skills/obsidian-gbrain-safe-index",
|
||||
"skills/perplexity-research",
|
||||
"skills/query",
|
||||
"skills/repo-architecture",
|
||||
"skills/reports",
|
||||
"skills/repo-architecture",
|
||||
"skills/signal-detector",
|
||||
"skills/skill-creator",
|
||||
"skills/skillify",
|
||||
|
||||
+1
-3
@@ -60,8 +60,7 @@ This is the dispatcher. Skills are the implementation. **Read the skill file bef
|
||||
| "get more out of gbrain", "is my brain set up right", "weekly brain checkup", "advise me on my brain", "gbrain advisor" | `skills/gbrain-advisor/SKILL.md` |
|
||||
| Save or load reports | `skills/reports/SKILL.md` |
|
||||
| "Create a skill", "improve this skill" | `skills/skill-creator/SKILL.md` |
|
||||
| "save this learning to the vault", "capture this skill in Obsidian", "record this workflow in my notes", "put this setup change in the vault" | `skills/skill-vault-capture-policy/SKILL.md` |
|
||||
| "Skillify this", "is this a skill?", "make this proper", "add tests and evals for this" | `skills/skillify/SKILL.md` |
|
||||
| "Skillify this", "is this a skill?", "make this proper" | `skills/skillify/SKILL.md` |
|
||||
| "Compress my resolver", "AGENTS.md too large", "RESOLVER.md too big", "functional area dispatcher", "shrink routing table" | `skills/functional-area-resolver/SKILL.md` |
|
||||
| "Is gbrain healthy?", morning health check, skillpack-check | `skills/skillpack-check/SKILL.md` |
|
||||
| "harvest this skill into gbrain", "publish this skill to gbrain", "lift this skill upstream", "share this skill with other gbrain clients", "promote my skill to gbrain" | `skills/skillpack-harvest/SKILL.md` |
|
||||
@@ -79,7 +78,6 @@ This is the dispatcher. Skills are the implementation. **Read the skill file bef
|
||||
| "Set up GBrain", first boot | `skills/setup/SKILL.md` |
|
||||
| "Now what?", "fill my brain", "cold start", "bootstrap", "import my data", "what should I import first" | `skills/cold-start/SKILL.md` |
|
||||
| "Migrate from Obsidian/Notion/Logseq" | `skills/migrate/SKILL.md` |
|
||||
| "Connect Obsidian to gbrain", "import my vault to gbrain", "sync vault and gbrain", "embed gbrain after vault update", "is gbrain synced with my vault" | `skills/obsidian-gbrain-safe-index/SKILL.md` |
|
||||
| Brain health check, maintenance run | `skills/maintain/SKILL.md` |
|
||||
| "Extract links", "build link graph", "populate timeline" | `skills/maintain/SKILL.md` (extraction sections) |
|
||||
| "Run dream", "process today's session", "synthesize my conversations", "consolidate yesterday's conversations", "what patterns did you see", "did the dream cycle run" | `skills/maintain/SKILL.md` (dream cycle section) |
|
||||
|
||||
+1
-11
@@ -2,7 +2,7 @@
|
||||
"name": "gbrain",
|
||||
"version": "0.32.3.0",
|
||||
"conformance_version": "1.0.0",
|
||||
"description": "Personal knowledge brain with hybrid RAG search — GStack mod for agent platforms",
|
||||
"description": "Personal knowledge brain with hybrid RAG search \u2014 GStack mod for agent platforms",
|
||||
"skills": [
|
||||
{
|
||||
"name": "ingest",
|
||||
@@ -34,11 +34,6 @@
|
||||
"path": "migrate/SKILL.md",
|
||||
"description": "Universal migration from Obsidian, Notion, Logseq, markdown, CSV, JSON, Roam"
|
||||
},
|
||||
{
|
||||
"name": "obsidian-gbrain-safe-index",
|
||||
"path": "obsidian-gbrain-safe-index/SKILL.md",
|
||||
"description": "Connect and sync an Obsidian-style Markdown vault with gbrain using a cost-controlled import-first workflow, explicit embedding gates, and durable skill/workflow capture."
|
||||
},
|
||||
{
|
||||
"name": "setup",
|
||||
"path": "setup/SKILL.md",
|
||||
@@ -268,11 +263,6 @@
|
||||
"name": "skill-optimizer",
|
||||
"path": "skill-optimizer/SKILL.md",
|
||||
"description": "Self-evolving skill optimization via gbrain skillopt — SkillOpt-paper-grounded text-space optimizer with validation gating (median-of-3 + epsilon=0.05), bundled-skill safety, bootstrap review sentinel, per-skill DB lock, and atomic versioned writes."
|
||||
},
|
||||
{
|
||||
"name": "skill-vault-capture-policy",
|
||||
"path": "skill-vault-capture-policy/SKILL.md",
|
||||
"description": "Capture durable operational learnings, new agent skills, and environment/setup changes into the Obsidian vault instead of transient chat memory."
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
---
|
||||
name: obsidian-gbrain-safe-index
|
||||
version: 1.0.0
|
||||
description: |
|
||||
Connect, maintain, and sync an Obsidian-style Markdown vault with gbrain while preserving a cost-controlled workflow: the vault remains the source of truth, gbrain is the searchable/embedded index, durable skills/workflows are captured into the vault, and paid embedding runs only after explicit approval.
|
||||
triggers:
|
||||
- "connect Obsidian to gbrain"
|
||||
- "import my vault to gbrain"
|
||||
- "sync vault and gbrain"
|
||||
- "capture this skill in my vault"
|
||||
- "embed gbrain after vault update"
|
||||
- "is gbrain synced with my vault"
|
||||
tools:
|
||||
- terminal
|
||||
- read_file
|
||||
- search_files
|
||||
- write_file
|
||||
- patch
|
||||
mutating: true
|
||||
---
|
||||
|
||||
# Obsidian → gbrain Safe Index and Capture
|
||||
|
||||
## Contract
|
||||
|
||||
This skill guarantees:
|
||||
|
||||
- Treats the user's Obsidian-style Markdown vault as the source of truth before gbrain indexing.
|
||||
- Keeps gbrain in conservative mode unless the user explicitly approves a more expensive mode.
|
||||
- Imports vault changes with `--no-embed` first, then embeds only after explicit approval for the specific paid action.
|
||||
- Captures durable new skills, workflows, and environment learnings into the vault instead of leaving them only in chat memory.
|
||||
- Verifies every sync with concrete `gbrain stats`, search mode, and, when embeddings run, exact embedded chunk counts.
|
||||
|
||||
## Phases
|
||||
|
||||
1. **Resolve the vault path.**
|
||||
- Prefer an existing environment variable such as `OBSIDIAN_VAULT_PATH` or `WIKI_PATH`.
|
||||
- If no path is configured, search likely note directories and ask the user before writing.
|
||||
- Verify the directory exists and contains markdown files or an `.obsidian` directory.
|
||||
|
||||
2. **Read vault operating rules before writing.**
|
||||
- If the vault has `SCHEMA.md`, `index.md`, `log.md`, `AGENTS.md`, or similar operating files, read them before ingest/query/major edit.
|
||||
- Respect immutable source folders such as `raw/` when the vault declares them.
|
||||
- Use the vault's native link convention, usually Obsidian `[[wikilinks]]`, for durable relationships.
|
||||
|
||||
3. **MECE/capture decision.**
|
||||
- If new knowledge belongs on an existing page, update that page.
|
||||
- If it is a distinct recurring workflow or operational policy, create a small meta or concept page following the vault schema.
|
||||
- Update the vault index/catalog for every new page when the vault maintains one.
|
||||
- Append a log entry for meaningful vault updates when the vault maintains a log.
|
||||
|
||||
4. **Safe gbrain import path.**
|
||||
- Pre-check source directory; do not import a nonexistent path.
|
||||
- Run `gbrain config set search.mode conservative` before/after risky reinit steps.
|
||||
- Run `gbrain import "$OBSIDIAN_VAULT_PATH" --no-embed`.
|
||||
- Run `gbrain extract links --source fs --dir "$OBSIDIAN_VAULT_PATH"` when wikilinks changed materially.
|
||||
|
||||
5. **Paid embedding gate.**
|
||||
- Do not run `gbrain embed --stale` unless the user explicitly asks or a prior instruction clearly approved this exact paid action.
|
||||
- Before embedding, verify provider readiness with `gbrain providers test --model <provider:model>`.
|
||||
- Confirm the configured embedding dimensions match the local schema.
|
||||
- After embedding, verify `gbrain stats` and record exact `Pages`, `Chunks`, `Embedded`, and `Links` counts.
|
||||
|
||||
6. **Final verification and vault echo.**
|
||||
- Run `gbrain stats` and `gbrain search modes`.
|
||||
- If vault files changed, re-import with `--no-embed`; if embedding was approved, embed stale chunks afterward.
|
||||
- Report what changed, what was free/local, what used API billing, and what remains pending.
|
||||
|
||||
## Output Format
|
||||
|
||||
Use a compact status table:
|
||||
|
||||
| Item | Status |
|
||||
|---|---|
|
||||
| Vault path | `/path` |
|
||||
| Vault updated | yes/no + files |
|
||||
| gbrain mode | conservative/balanced/tokenmax |
|
||||
| Import | `--no-embed` completed / skipped / failed |
|
||||
| Pages/chunks | exact counts from `gbrain stats` |
|
||||
| Embeddings | exact count; note whether this run used API billing |
|
||||
| Links | exact count |
|
||||
| Background jobs | none / list exact jobs |
|
||||
|
||||
Then include:
|
||||
|
||||
- **Safe next step:** free/local action.
|
||||
- **Paid next step:** embedding/LLM action, if any, with explicit approval requirement.
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- Creating a duplicate skill/page when an existing Obsidian, gbrain, or vault-ingest skill already covers the workflow.
|
||||
- Running `gbrain embed --stale`, `gbrain dream`, `gbrain autopilot --install`, `gbrain onboard --auto`, or `tokenmax` without explicit cost approval.
|
||||
- Importing a nonexistent or wrong directory and treating a zero-page import as success.
|
||||
- Forgetting to update the vault index/catalog and log after creating or materially updating vault pages.
|
||||
- Recording API keys, tokens, or raw secrets in the vault or final response.
|
||||
|
||||
## Tools Used
|
||||
|
||||
- `read_file` — read vault schema/index/log and target notes.
|
||||
- `search_files` — find existing vault pages and avoid duplicates.
|
||||
- `write_file` / `patch` — create or update vault pages.
|
||||
- `terminal` — run `gbrain`, `git`, and environment checks with secret values redacted.
|
||||
|
||||
## Safe Commands
|
||||
|
||||
```bash
|
||||
export PATH="$HOME/.bun/bin:$PATH"
|
||||
gbrain config set search.mode conservative
|
||||
gbrain import "$OBSIDIAN_VAULT_PATH" --no-embed
|
||||
gbrain extract links --source fs --dir "$OBSIDIAN_VAULT_PATH"
|
||||
gbrain stats
|
||||
gbrain search modes
|
||||
```
|
||||
|
||||
## Paid / Approval-Gated Commands
|
||||
|
||||
```bash
|
||||
gbrain providers test --model <provider:model>
|
||||
gbrain embed --stale
|
||||
gbrain dream
|
||||
gbrain autopilot --install
|
||||
gbrain onboard --auto --max-usd 5
|
||||
gbrain config set search.mode tokenmax
|
||||
```
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
- [ ] Vault path exists and is the intended source.
|
||||
- [ ] Vault operating files were read before edits when present.
|
||||
- [ ] Existing pages/skills were searched to avoid duplicates.
|
||||
- [ ] New/updated vault pages follow the vault schema and link convention.
|
||||
- [ ] Vault index/catalog updated for new pages when present.
|
||||
- [ ] Vault log appended for meaningful actions when present.
|
||||
- [ ] `gbrain import ... --no-embed` completed.
|
||||
- [ ] `gbrain stats` recorded pages/chunks/embeddings/links.
|
||||
- [ ] `gbrain search modes` confirms conservative mode unless a different mode was explicitly approved.
|
||||
- [ ] No paid/background commands ran without approval.
|
||||
@@ -1,11 +0,0 @@
|
||||
// Routing eval fixtures for skills/obsidian-gbrain-safe-index.
|
||||
// Positive cases: intents embed a trigger phrase in natural surrounding context
|
||||
// (never verbatim-identical to a trigger — the fixture linter rejects tautologies).
|
||||
{"intent": "help me connect Obsidian to gbrain for my notes", "expected_skill": "obsidian-gbrain-safe-index"}
|
||||
{"intent": "import my vault to gbrain but skip embeddings for now", "expected_skill": "obsidian-gbrain-safe-index"}
|
||||
{"intent": "please sync vault and gbrain after I edit notes", "expected_skill": "obsidian-gbrain-safe-index"}
|
||||
{"intent": "run embed gbrain after vault update tonight", "expected_skill": "obsidian-gbrain-safe-index"}
|
||||
{"intent": "hey is gbrain synced with my vault right now", "expected_skill": "obsidian-gbrain-safe-index"}
|
||||
// Negative cases: related but owned by other skills. Assert NO route to this skill.
|
||||
{"intent": "migrate my notes from Notion to gbrain", "expected_skill": null}
|
||||
{"intent": "what is on my calendar tomorrow", "expected_skill": null}
|
||||
@@ -1,100 +0,0 @@
|
||||
---
|
||||
name: skill-vault-capture-policy
|
||||
version: 1.0.0
|
||||
description: |
|
||||
Use when the user wants a durable operational learning, new agent skill, or
|
||||
important environment/setup change to be captured into the Obsidian vault
|
||||
instead of left only in transient chat memory. Covers the capture rule,
|
||||
preferred page patterns, and index/log update obligations.
|
||||
triggers:
|
||||
- "save this learning to the vault"
|
||||
- "capture this skill in Obsidian"
|
||||
- "record this workflow in my notes"
|
||||
- "put this setup change in the vault"
|
||||
- "should we add this to the knowledge base"
|
||||
tools:
|
||||
- read_file
|
||||
- search_files
|
||||
- write_file
|
||||
- patch
|
||||
mutating: true
|
||||
---
|
||||
|
||||
# Skill Vault Capture Policy
|
||||
|
||||
## Contract
|
||||
|
||||
This skill guarantees:
|
||||
|
||||
- Durable operational learnings, newly adopted skills, and important environment/setup changes are captured into the Obsidian vault rather than left only in chat memory.
|
||||
- An existing page is updated when the knowledge clearly belongs there; a new page is created only when the topic is distinct and likely to recur.
|
||||
- Every new vault page is added to `index.md`.
|
||||
- Every meaningful create/update appends a dated entry to `log.md`.
|
||||
- Small linked pages are preferred over one giant running note.
|
||||
|
||||
## Phases
|
||||
|
||||
1. **Classify the learning.**
|
||||
- New gbrain operating rule, cost control, or embedding/provider change.
|
||||
- New agent-fork / harness / coding-tool integration fact.
|
||||
- New Obsidian vault workflow or structure decision.
|
||||
- New recurring agent skill that changes how the agent should operate here.
|
||||
|
||||
2. **Avoid duplicates.**
|
||||
- Search the vault for an existing page that already owns the topic.
|
||||
- If found, update it with a new section or dated note rather than creating a near-duplicate.
|
||||
|
||||
3. **Create when distinct.**
|
||||
- Place new pages under the vault schema: `_meta/` for operating notes, `concepts/` for workflows, `entities/` for tools/people.
|
||||
- Use YAML frontmatter and at least two `[[wikilinks]]` unless it is a short seed page.
|
||||
|
||||
4. **Update navigation.**
|
||||
- Add the page to `index.md` under the correct type heading.
|
||||
- Append a `## [YYYY-MM-DD] create|update | subject` entry to `log.md`.
|
||||
|
||||
5. **Report the capture.**
|
||||
- State which files changed and whether `index.md` / `log.md` were updated.
|
||||
|
||||
## Output Format
|
||||
|
||||
Use a short status block:
|
||||
|
||||
| Item | Status |
|
||||
|---|---|
|
||||
| Learning classified | type |
|
||||
| Page created/updated | path |
|
||||
| index.md updated | yes/no |
|
||||
| log.md updated | yes/no |
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- Leaving durable learnings only in chat memory.
|
||||
- Creating a near-duplicate page instead of updating the existing one.
|
||||
- Forgetting to update `index.md` and `log.md`.
|
||||
- Writing one giant running note instead of small linked pages.
|
||||
- Recording secrets, API keys, or raw credentials in the vault.
|
||||
|
||||
## Tools Used
|
||||
|
||||
- `read_file` — read `SCHEMA.md`, `index.md`, `log.md`, and target pages.
|
||||
- `search_files` — find existing pages to avoid duplicates.
|
||||
- `write_file` / `patch` — create or update vault pages and navigation.
|
||||
|
||||
## Safe Commands
|
||||
|
||||
```bash
|
||||
# inspect vault navigation before writing
|
||||
read SCHEMA.md index.md log.md
|
||||
# create or update a page, then refresh catalog/log
|
||||
# index.md: add [[page-slug]] under the matching type heading
|
||||
# log.md: append ## [YYYY-MM-DD] create|update | subject
|
||||
```
|
||||
|
||||
## Verification Checklist
|
||||
|
||||
- [ ] Vault schema/read files were checked before writing.
|
||||
- [ ] Existing pages were searched to avoid duplicates.
|
||||
- [ ] New/updated page has frontmatter and wikilinks.
|
||||
- [ ] `index.md` updated for new pages.
|
||||
- [ ] `log.md` appended for meaningful actions.
|
||||
- [ ] No secrets or raw credentials were written.
|
||||
@@ -1,10 +0,0 @@
|
||||
// Routing eval fixtures for skills/skill-vault-capture-policy.
|
||||
// Positive cases: intents embed a trigger phrase in natural surrounding context
|
||||
// (never verbatim-identical to a trigger — the fixture linter rejects tautologies).
|
||||
{"intent": "please save this learning to the vault so we keep it", "expected_skill": "skill-vault-capture-policy", "ambiguous_with": ["idea-ingest"]}
|
||||
{"intent": "we should capture this skill in Obsidian for reuse", "expected_skill": "skill-vault-capture-policy", "ambiguous_with": ["capture"]}
|
||||
{"intent": "can you record this workflow in my notes for next time", "expected_skill": "skill-vault-capture-policy"}
|
||||
{"intent": "put this setup change in the vault before we forget", "expected_skill": "skill-vault-capture-policy"}
|
||||
// Negative cases: related but owned by other skills or out of scope.
|
||||
{"intent": "connect my Obsidian vault to gbrain", "expected_skill": null}
|
||||
{"intent": "what is on my calendar tomorrow", "expected_skill": null}
|
||||
@@ -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-05-27.
|
||||
// Source: admin/dist/ at 2026-07-21.
|
||||
//
|
||||
// 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_CoGEje3__js from '../admin/dist/assets/index-CoGEje3-.js' with { type: 'file' };
|
||||
import A_0_assets_index_CzLjRij__js from '../admin/dist/assets/index-CzLjRij_.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-CoGEje3-.js": { path: A_0_assets_index_CoGEje3__js as unknown as string, mime: "application/javascript; charset=utf-8" },
|
||||
"/admin/assets/index-CzLjRij_.js": { path: A_0_assets_index_CzLjRij__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" },
|
||||
};
|
||||
|
||||
@@ -39,6 +39,7 @@ import * as db from '../core/db.ts';
|
||||
import { sqlQueryForEngine, executeRawJsonb } from '../core/sql-query.ts';
|
||||
import { MinionQueue } from '../core/minions/queue.ts';
|
||||
import { isRetryableError } from '../core/retry-matcher.ts';
|
||||
import { normalizeAdminClientSourceScope } from '../core/admin-source-scope.ts';
|
||||
import {
|
||||
computeContentHash,
|
||||
validateIngestionEvent,
|
||||
@@ -1086,6 +1087,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
const oauthClients = await sql`
|
||||
SELECT c.client_id as id, c.client_name as name, 'oauth' as auth_type,
|
||||
c.grant_types, c.scope, c.created_at, c.token_ttl,
|
||||
c.source_id, c.federated_read,
|
||||
CASE WHEN c.deleted_at IS NOT NULL THEN 'revoked' ELSE 'active' END as status,
|
||||
(SELECT max(created_at) FROM mcp_request_log WHERE token_name = c.client_id) as last_used_at,
|
||||
(SELECT count(*)::int FROM mcp_request_log WHERE token_name = c.client_id) as total_requests,
|
||||
@@ -1095,6 +1097,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
const legacyKeys = await sql`
|
||||
SELECT a.id, a.name, 'api_key' as auth_type,
|
||||
'{"bearer"}' as grant_types, 'read write admin' as scope, a.created_at, null as token_ttl,
|
||||
null as source_id, null as federated_read,
|
||||
CASE WHEN a.revoked_at IS NOT NULL THEN 'revoked' ELSE 'active' END as status,
|
||||
a.last_used_at,
|
||||
(SELECT count(*)::int FROM mcp_request_log WHERE token_name = a.name) as total_requests,
|
||||
@@ -1107,6 +1110,17 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/admin/api/sources', requireAdmin, async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const sources = await engine.listAllSources({ includeArchived: false });
|
||||
const options = sources.map(s => ({ id: s.id, name: s.name }));
|
||||
if (!options.some(s => s.id === 'default')) options.unshift({ id: 'default', name: 'default' });
|
||||
res.json(options);
|
||||
} catch (e) {
|
||||
res.status(503).json({ error: 'service_unavailable' });
|
||||
}
|
||||
});
|
||||
|
||||
// v0.38 Slice 4 — per-OAuth-client agent spend viewer. Pre-computes today's
|
||||
// spend (committed + pending reservations) per client so the Agents tab
|
||||
// can render a "$X / $Y today" cell. Read-side endpoint only — no mutation.
|
||||
@@ -1440,6 +1454,8 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
// missing, empty) and rejects the rest with a structured 400.
|
||||
const { name, tokenTtl, grantTypes, redirectUris, tokenEndpointAuthMethod } = req.body;
|
||||
const rawScopes = (req.body as Record<string, unknown>).scopes ?? (req.body as Record<string, unknown>).scope;
|
||||
const rawSourceId = (req.body as Record<string, unknown>).source_id ?? (req.body as Record<string, unknown>).sourceId;
|
||||
const rawFederatedRead = (req.body as Record<string, unknown>).federated_read ?? (req.body as Record<string, unknown>).federatedRead;
|
||||
if (!name) { res.status(400).json({ error: 'Name required' }); return; }
|
||||
let scopeString: string;
|
||||
try {
|
||||
@@ -1470,8 +1486,23 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
});
|
||||
return;
|
||||
}
|
||||
let sourceScope: ReturnType<typeof normalizeAdminClientSourceScope>;
|
||||
try {
|
||||
const sources = await engine.listAllSources({ includeArchived: false });
|
||||
sourceScope = normalizeAdminClientSourceScope(
|
||||
rawSourceId,
|
||||
rawFederatedRead,
|
||||
sources.map(s => s.id),
|
||||
);
|
||||
} catch (e) {
|
||||
res.status(400).json({
|
||||
error: 'invalid_source_scope',
|
||||
message: e instanceof Error ? e.message : String(e),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const result = await oauthProvider.registerClientManual(
|
||||
name, grants, scopeString, uris, 'default', undefined, validatedAuthMethod,
|
||||
name, grants, scopeString, uris, sourceScope.sourceId, sourceScope.federatedRead, validatedAuthMethod,
|
||||
);
|
||||
// Set per-client TTL if specified
|
||||
if (tokenTtl && Number(tokenTtl) > 0) {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { isValidSourceId } from './source-id.ts';
|
||||
|
||||
export interface AdminClientSourceScope {
|
||||
sourceId: string;
|
||||
federatedRead: string[];
|
||||
}
|
||||
|
||||
function parseFederatedReadInput(raw: unknown, sourceId: string): string[] {
|
||||
if (raw === undefined || raw === null) return [sourceId];
|
||||
if (typeof raw === 'string') {
|
||||
const values = raw.split(',').map(s => s.trim()).filter(Boolean);
|
||||
return values.length > 0 ? values : [sourceId];
|
||||
}
|
||||
if (Array.isArray(raw)) {
|
||||
if (!raw.every(v => typeof v === 'string')) {
|
||||
throw new Error('federated_read must be an array of source ids');
|
||||
}
|
||||
const values = raw.map(v => v.trim()).filter(Boolean);
|
||||
return values.length > 0 ? values : [sourceId];
|
||||
}
|
||||
throw new Error('federated_read must be a string or array');
|
||||
}
|
||||
|
||||
export function normalizeAdminClientSourceScope(
|
||||
rawSourceId: unknown,
|
||||
rawFederatedRead: unknown,
|
||||
availableSourceIds: string[],
|
||||
): AdminClientSourceScope {
|
||||
const knownSources = new Set(availableSourceIds);
|
||||
const fallbackSourceId = knownSources.has('default') ? 'default' : (availableSourceIds[0] ?? 'default');
|
||||
const sourceId = rawSourceId === undefined || rawSourceId === null || rawSourceId === ''
|
||||
? fallbackSourceId
|
||||
: rawSourceId;
|
||||
if (!isValidSourceId(sourceId)) {
|
||||
throw new Error(`Invalid source_id: ${JSON.stringify(sourceId)}`);
|
||||
}
|
||||
if (knownSources.size > 0 && !knownSources.has(sourceId)) {
|
||||
throw new Error(`Unknown source_id: ${sourceId}`);
|
||||
}
|
||||
|
||||
const federatedRead = Array.from(new Set(parseFederatedReadInput(rawFederatedRead, sourceId)));
|
||||
for (const id of federatedRead) {
|
||||
if (!isValidSourceId(id)) {
|
||||
throw new Error(`Invalid federated_read source_id: ${JSON.stringify(id)}`);
|
||||
}
|
||||
if (knownSources.size > 0 && !knownSources.has(id)) {
|
||||
throw new Error(`Unknown federated_read source_id: ${id}`);
|
||||
}
|
||||
}
|
||||
return { sourceId, federatedRead };
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { normalizeAdminClientSourceScope } from '../src/core/admin-source-scope.ts';
|
||||
|
||||
describe('admin register-client source scope normalization', () => {
|
||||
const sources = ['default', 'team-a', 'team-b'];
|
||||
|
||||
test('defaults write and read scope to default source', () => {
|
||||
expect(normalizeAdminClientSourceScope(undefined, undefined, sources)).toEqual({
|
||||
sourceId: 'default',
|
||||
federatedRead: ['default'],
|
||||
});
|
||||
});
|
||||
|
||||
test('accepts snake-case body fields with multiple read sources', () => {
|
||||
expect(normalizeAdminClientSourceScope('team-a', ['team-a', 'team-b'], sources)).toEqual({
|
||||
sourceId: 'team-a',
|
||||
federatedRead: ['team-a', 'team-b'],
|
||||
});
|
||||
});
|
||||
|
||||
test('accepts comma-separated federated_read for API callers', () => {
|
||||
expect(normalizeAdminClientSourceScope('team-a', 'team-b, default,team-b', sources)).toEqual({
|
||||
sourceId: 'team-a',
|
||||
federatedRead: ['team-b', 'default'],
|
||||
});
|
||||
});
|
||||
|
||||
test('falls back to selected write source when federated_read is empty', () => {
|
||||
expect(normalizeAdminClientSourceScope('team-b', [], sources)).toEqual({
|
||||
sourceId: 'team-b',
|
||||
federatedRead: ['team-b'],
|
||||
});
|
||||
});
|
||||
|
||||
test('rejects malformed source ids before registration', () => {
|
||||
expect(() => normalizeAdminClientSourceScope('../secret', undefined, sources)).toThrow(/Invalid source_id/);
|
||||
expect(() => normalizeAdminClientSourceScope('team-a', ['snake_case'], sources)).toThrow(/Invalid federated_read/);
|
||||
});
|
||||
|
||||
test('rejects valid-looking but unregistered source ids', () => {
|
||||
expect(() => normalizeAdminClientSourceScope('ghost', undefined, sources)).toThrow(/Unknown source_id/);
|
||||
expect(() => normalizeAdminClientSourceScope('team-a', ['ghost'], sources)).toThrow(/Unknown federated_read/);
|
||||
});
|
||||
});
|
||||
@@ -1,61 +0,0 @@
|
||||
/**
|
||||
* E2E smoke for skills/obsidian-gbrain-safe-index.
|
||||
*
|
||||
* Verifies the from-trigger-to-side-effect path that skillify requires:
|
||||
* a real user trigger phrase routes to the skill, the resolver/check
|
||||
* pipeline treats it as reachable, and the skill file exposes the
|
||||
* gbrain commands the workflow actually runs.
|
||||
*
|
||||
* This stays local-only (no paid embedding, no external API): it asserts
|
||||
* the documented safe/import path is present and parseable, not that it
|
||||
* mutates a live brain.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
const SKILLS = join(import.meta.dir, '..', '..', 'skills');
|
||||
const SKILL_MD = join(SKILLS, 'obsidian-gbrain-safe-index', 'SKILL.md');
|
||||
const RESOLVER = join(SKILLS, 'RESOLVER.md');
|
||||
|
||||
const TRIGGER_PHRASES = [
|
||||
'connect my Obsidian vault to gbrain',
|
||||
'import my vault to gbrain',
|
||||
'sync vault and gbrain',
|
||||
'capture this skill in my vault',
|
||||
'embed gbrain after vault update',
|
||||
'is gbrain synced with my vault',
|
||||
];
|
||||
|
||||
describe('obsidian-gbrain-safe-index E2E', () => {
|
||||
it('resolver maps real trigger phrasings to the skill', () => {
|
||||
const resolver = readFileSync(RESOLVER, 'utf-8');
|
||||
expect(resolver).toContain('obsidian-gbrain-safe-index/SKILL.md');
|
||||
// Each representative phrase shares a token substring with a resolver row.
|
||||
const rows = resolver
|
||||
.split('\n')
|
||||
.filter((l) => l.includes('obsidian-gbrain-safe-index/SKILL.md'))
|
||||
.join('\n');
|
||||
for (const phrase of TRIGGER_PHRASES) {
|
||||
const hit = phrase
|
||||
.toLowerCase()
|
||||
.split(/\s+/)
|
||||
.some((tok) => tok.length > 3 && rows.toLowerCase().includes(tok));
|
||||
expect(hit, `no resolver token for: ${phrase}`).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('skill documents the gbrain import-first safe path', () => {
|
||||
const body = readFileSync(SKILL_MD, 'utf-8');
|
||||
expect(body).toContain('gbrain import');
|
||||
expect(body).toContain('--no-embed');
|
||||
expect(body).toContain('gbrain config set search.mode conservative');
|
||||
// Paid gate must be explicit, not a silent default.
|
||||
expect(body).toContain('gbrain embed --stale');
|
||||
});
|
||||
|
||||
it('skill is reachable from the skill tree', () => {
|
||||
expect(existsSync(SKILL_MD)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,52 +0,0 @@
|
||||
/**
|
||||
* E2E smoke for skills/skill-vault-capture-policy.
|
||||
*
|
||||
* Verifies the from-trigger-to-side-effect path: a real capture request
|
||||
* routes to the skill, and the skill documents the vault navigation
|
||||
* obligations (index.md / log.md) that make a capture durable.
|
||||
*
|
||||
* Local-only: it asserts documented behavior, not live vault writes.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
const SKILLS = join(import.meta.dir, '..', '..', 'skills');
|
||||
const SKILL_MD = join(SKILLS, 'skill-vault-capture-policy', 'SKILL.md');
|
||||
const RESOLVER = join(SKILLS, 'RESOLVER.md');
|
||||
|
||||
const TRIGGER_PHRASES = [
|
||||
'save this learning to the vault',
|
||||
'capture this skill in Obsidian',
|
||||
'record this workflow in my notes',
|
||||
'put this setup change in the knowledge base',
|
||||
];
|
||||
|
||||
describe('skill-vault-capture-policy E2E', () => {
|
||||
it('resolver maps real capture phrasings to the skill', () => {
|
||||
const resolver = readFileSync(RESOLVER, 'utf-8');
|
||||
expect(resolver).toContain('skill-vault-capture-policy/SKILL.md');
|
||||
const rows = resolver
|
||||
.split('\n')
|
||||
.filter((l) => l.includes('skill-vault-capture-policy/SKILL.md'))
|
||||
.join('\n');
|
||||
for (const phrase of TRIGGER_PHRASES) {
|
||||
const hit = phrase
|
||||
.toLowerCase()
|
||||
.split(/\s+/)
|
||||
.some((tok) => tok.length > 3 && rows.toLowerCase().includes(tok));
|
||||
expect(hit, `no resolver token for: ${phrase}`).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('skill documents index.md and log.md update obligations', () => {
|
||||
const body = readFileSync(SKILL_MD, 'utf-8');
|
||||
expect(body).toContain('index.md');
|
||||
expect(body).toContain('log.md');
|
||||
});
|
||||
|
||||
it('skill is reachable from the skill tree', () => {
|
||||
expect(existsSync(SKILL_MD)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -78,6 +78,8 @@ describe('v0.36.1.x #1077 — admin register-client supports PKCE public clients
|
||||
// (under either name) from req.body. Pin the fallback pattern so the
|
||||
// PKCE-fix regression contract stays load-bearing.
|
||||
expect(src).toMatch(/req\.body[^;]*scopes\s*\?\?\s*[^;]*scope\b/);
|
||||
expect(src).toMatch(/req\.body[^;]*source_id\s*\?\?\s*[^;]*sourceId\b/);
|
||||
expect(src).toMatch(/req\.body[^;]*federated_read\s*\?\?\s*[^;]*federatedRead\b/);
|
||||
// v0.41.3 (T4 atomicity fix, codex F4): admin endpoint now validates
|
||||
// tokenEndpointAuthMethod via the shared validator and passes it to
|
||||
// registerClientManual as a positional arg. Pre-v0.41.3 the route did
|
||||
@@ -87,6 +89,7 @@ describe('v0.36.1.x #1077 — admin register-client supports PKCE public clients
|
||||
// UPDATE block (the regex deliberately asserts the post-insert UPDATE
|
||||
// is GONE).
|
||||
expect(src).toMatch(/validateTokenEndpointAuthMethod\(tokenEndpointAuthMethod\)/);
|
||||
expect(src).toMatch(/normalizeAdminClientSourceScope\(/);
|
||||
expect(src).toMatch(/registerClientManual\([^)]*validatedAuthMethod[^)]*\)/);
|
||||
// Regression guard: post-insert UPDATE flipping client_secret_hash to
|
||||
// NULL based on a runtime check is exactly the non-atomic pattern T4
|
||||
@@ -267,3 +270,26 @@ describe('v0.42.43.0 #2095 — volunteer-events sink + cycle purge wiring (struc
|
||||
expect(src).toMatch(/purged_volunteer_events_count/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#1490 + #1036 — admin Register Agent form exposes source scope + redirect URIs', () => {
|
||||
test('Agents.tsx RegisterModal sends source_id + federated_read in the POST body (#1490)', () => {
|
||||
const src = readFileSync('admin/src/pages/Agents.tsx', 'utf8');
|
||||
expect(src).toMatch(/source_id:\s*sourceId/);
|
||||
expect(src).toMatch(/federated_read:\s*federatedRead/);
|
||||
// The source list comes from the requireAdmin-gated endpoint, not a hardcoded 'default'.
|
||||
expect(src).toMatch(/api\.sources\(\)/);
|
||||
});
|
||||
|
||||
test('serve-http.ts serves /admin/api/sources behind requireAdmin (#1490)', () => {
|
||||
const src = readFileSync('src/commands/serve-http.ts', 'utf8');
|
||||
expect(src).toMatch(/app\.get\('\/admin\/api\/sources',\s*requireAdmin/);
|
||||
});
|
||||
|
||||
test('Agents.tsx RegisterModal sends redirectUris + authorization_code grants when URIs are entered (#1036)', () => {
|
||||
const src = readFileSync('admin/src/pages/Agents.tsx', 'utf8');
|
||||
// One-per-line textarea split into an array...
|
||||
expect(src).toMatch(/redirectUris\.split\('\\n'\)/);
|
||||
// ...included in the body with the CLI's grant-type inference convention.
|
||||
expect(src).toMatch(/redirectUris:\s*uris,\s*grantTypes:\s*\['authorization_code',\s*'refresh_token'\]/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -125,6 +125,30 @@ describe('client registration', () => {
|
||||
expect(client!.client_name).toBe('test-agent');
|
||||
});
|
||||
|
||||
test('registerClientManual persists source_id and federated_read into AuthInfo', async () => {
|
||||
await sql`
|
||||
INSERT INTO sources (id, name) VALUES (${'team-a'}, ${'Team A'}), (${'team-b'}, ${'Team B'})
|
||||
ON CONFLICT DO NOTHING
|
||||
`;
|
||||
const { clientId, clientSecret } = await provider.registerClientManual(
|
||||
'source-scoped-test',
|
||||
['client_credentials'],
|
||||
'read write',
|
||||
[],
|
||||
'team-a',
|
||||
['team-a', 'team-b'],
|
||||
);
|
||||
|
||||
const tokens = await provider.exchangeClientCredentials(clientId, clientSecret!, 'read');
|
||||
const authInfo = await provider.verifyAccessToken(tokens.access_token) as {
|
||||
sourceId?: string;
|
||||
allowedSources?: string[];
|
||||
};
|
||||
|
||||
expect(authInfo.sourceId).toBe('team-a');
|
||||
expect(authInfo.allowedSources).toEqual(['team-a', 'team-b']);
|
||||
});
|
||||
|
||||
test('getClient returns undefined for unknown client', async () => {
|
||||
const client = await provider.clientsStore.getClient('nonexistent');
|
||||
expect(client).toBeUndefined();
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { readFileSync, existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
const SKILL_DIR = join(import.meta.dir, '..', 'skills', 'obsidian-gbrain-safe-index');
|
||||
const SKILL_MD = join(SKILL_DIR, 'SKILL.md');
|
||||
const RESOLVER = join(import.meta.dir, '..', 'skills', 'RESOLVER.md');
|
||||
|
||||
function parseFrontmatter(raw: string): Record<string, unknown> {
|
||||
const m = raw.match(/^---\n([\s\S]*?)\n---/);
|
||||
if (!m) throw new Error('no frontmatter');
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const line of m[1].split('\n')) {
|
||||
const mm = line.match(/^([a-zA-Z_]+):\s*(.*)$/);
|
||||
if (mm) out[mm[1]] = mm[2].trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('obsidian-gbrain-safe-index skill', () => {
|
||||
it('has a SKILL.md with required frontmatter', () => {
|
||||
expect(existsSync(SKILL_MD)).toBe(true);
|
||||
const fm = parseFrontmatter(readFileSync(SKILL_MD, 'utf-8'));
|
||||
expect(fm['name']).toBe('obsidian-gbrain-safe-index');
|
||||
expect(fm['description']).toBeTruthy();
|
||||
});
|
||||
|
||||
it('has the required conformance sections', () => {
|
||||
const body = readFileSync(SKILL_MD, 'utf-8');
|
||||
for (const section of ['## Contract', '## Phases', '## Output Format', '## Anti-Patterns']) {
|
||||
expect(body.includes(section), `missing ${section}`).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('is registered in RESOLVER.md', () => {
|
||||
expect(existsSync(RESOLVER)).toBe(true);
|
||||
const resolver = readFileSync(RESOLVER, 'utf-8');
|
||||
expect(resolver.includes('obsidian-gbrain-safe-index/SKILL.md')).toBe(true);
|
||||
});
|
||||
|
||||
it('has routing-eval fixtures that exercise real trigger phrasings', () => {
|
||||
const evalPath = join(SKILL_DIR, 'routing-eval.jsonl');
|
||||
expect(existsSync(evalPath)).toBe(true);
|
||||
const lines = readFileSync(evalPath, 'utf-8')
|
||||
.split('\n')
|
||||
.filter((l) => l.trim() && !l.trim().startsWith('//'))
|
||||
.map((l) => JSON.parse(l));
|
||||
const positives = lines.filter((l) => l.expected_skill === 'obsidian-gbrain-safe-index');
|
||||
expect(positives.length).toBeGreaterThanOrEqual(5);
|
||||
});
|
||||
});
|
||||
@@ -1,64 +0,0 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { readFileSync, existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { DEFAULT_PRIVATE_PATTERNS } from '../src/core/skillpack/harvest-lint.ts';
|
||||
|
||||
const SKILL_DIR = join(import.meta.dir, '..', 'skills', 'skill-vault-capture-policy');
|
||||
const SKILL_MD = join(SKILL_DIR, 'SKILL.md');
|
||||
const RESOLVER = join(import.meta.dir, '..', 'skills', 'RESOLVER.md');
|
||||
|
||||
function parseFrontmatter(raw: string): Record<string, unknown> {
|
||||
const m = raw.match(/^---\n([\s\S]*?)\n---/);
|
||||
if (!m) throw new Error('no frontmatter');
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const line of m[1].split('\n')) {
|
||||
const mm = line.match(/^([a-zA-Z_]+):\s*(.*)$/);
|
||||
if (mm) out[mm[1]] = mm[2].trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('skill-vault-capture-policy skill', () => {
|
||||
it('has a SKILL.md with required frontmatter', () => {
|
||||
expect(existsSync(SKILL_MD)).toBe(true);
|
||||
const fm = parseFrontmatter(readFileSync(SKILL_MD, 'utf-8'));
|
||||
expect(fm['name']).toBe('skill-vault-capture-policy');
|
||||
expect(fm['description']).toBeTruthy();
|
||||
});
|
||||
|
||||
it('has the required conformance sections', () => {
|
||||
const body = readFileSync(SKILL_MD, 'utf-8');
|
||||
for (const section of ['## Contract', '## Phases', '## Output Format', '## Anti-Patterns']) {
|
||||
expect(body.includes(section), `missing ${section}`).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('is registered in RESOLVER.md', () => {
|
||||
expect(existsSync(RESOLVER)).toBe(true);
|
||||
expect(readFileSync(RESOLVER, 'utf-8').includes('skill-vault-capture-policy/SKILL.md')).toBe(true);
|
||||
});
|
||||
|
||||
it('contains no private user or agent-fork names (privacy rule)', () => {
|
||||
for (const file of [SKILL_MD, join(SKILL_DIR, 'routing-eval.jsonl')]) {
|
||||
const body = readFileSync(file, 'utf-8');
|
||||
// DEFAULT_PRIVATE_PATTERNS[0] is the banned fork-name pattern; sourced
|
||||
// from harvest-lint so this file never contains the literal itself
|
||||
// (scripts/check-privacy.sh would reject it).
|
||||
const forkName = new RegExp(DEFAULT_PRIVATE_PATTERNS[0], 'i');
|
||||
for (const name of [/\bAdam\b/, /\bHermes\b/, /\bHerdr\b/, /\bArk\b/, forkName]) {
|
||||
expect(name.test(body), `private name ${name} in ${file}`).toBe(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('has routing-eval fixtures', () => {
|
||||
const evalPath = join(SKILL_DIR, 'routing-eval.jsonl');
|
||||
expect(existsSync(evalPath)).toBe(true);
|
||||
const positives = readFileSync(evalPath, 'utf-8')
|
||||
.split('\n')
|
||||
.filter((l) => l.trim() && !l.trim().startsWith('//'))
|
||||
.map((l) => JSON.parse(l))
|
||||
.filter((l) => l.expected_skill === 'skill-vault-capture-policy');
|
||||
expect(positives.length).toBeGreaterThanOrEqual(4);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user