Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(connectors): adversarial review fixes for the meetings and Slack sources

garrytanc72c610eb029
diff --git a/docs/guides/meeting-and-slack-sources.md b/docs/guides/meeting-and-slack-sources.md
index 3e13964e44..8f2cb22c8b 100644
--- a/docs/guides/meeting-and-slack-sources.md
+++ b/docs/guides/meeting-and-slack-sources.md
@@ -65,6 +65,13 @@ a daily quota) is recorded and autopilot waits until then. Without autopilot,
run `gbrain sync --source meetings` from cron through the wrapper in
[cron-schedule.md](cron-schedule.md#calling-gbrain-unattended).
+`gbrain sync --source meetings --full` re-reads the whole `--history-days`
+window, for items added upstream behind the lookback. `--dry-run` has no
+preview for these sources: it fetches and writes nothing. The first account a
+source syncs is pinned to it, and a key for another account is refused with
+`connector_account_changed` even after a config change. `gbrain connectors
+status fireflies` (or `slack`) reports whether a key is saved, without the key.
+
## Record modes
The record mode is chosen once, when the source is added, and stored. It is
diff --git a/src/commands/connectors/status.ts b/src/commands/connectors/status.ts
index d87519d17c..6fad88e271 100644
--- a/src/commands/connectors/status.ts
+++ b/src/commands/connectors/status.ts
@@ -11,7 +11,8 @@
import type { BrainEngine } from '../../core/engine.ts';
import { setCliExitVerdict } from '../../core/cli-force-exit.ts';
import { connectorProviders, getConnectorProvider } from '../../core/connectors/registry.ts';
-import { credentialMode, resolveCredential } from '../../core/connectors/credentials.ts';
+import { credentialMode, resolveApiToken, resolveCredential } from '../../core/connectors/credentials.ts';
+import { isTokenProviderName } from '../../core/connectors/types.ts';
import {
authErrorAtKey,
autoSyncKey,
@@ -24,6 +25,14 @@ import { fullSyncArgv, readFailedLedger } from '../../core/connectors/failed-led
export async function runConnectorStatus(engine: BrainEngine, args: string[]): Promise<void> {
const json = args.includes('--json');
const only = args.find((a) => !a.startsWith('-'));
+ if (only && isTokenProviderName(only)) {
+ const key = resolveApiToken(only);
+ const row = { provider: only, credential_present: !!key, credential_source: key?.source ?? null, credential_file_mode: credentialMode(only) };
+ if (json) console.log(JSON.stringify({ providers: [row] }, null, 2));
+ else console.log(key ? `${only} credential: ${key.source}` : `${only} no credential (gbrain connectors auth ${only} --token -)`);
+ if (!key) setCliExitVerdict(1);
+ return;
+ }
const providers = only
? [getConnectorProvider(only)].filter(Boolean)
: [...connectorProviders];
diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.ts
index 4cb3870820..2010214c00 100644
--- a/src/commands/sync/preflight.ts
+++ b/src/commands/sync/preflight.ts
@@ -297,6 +297,8 @@ async function resolveSyncRepo(engine: BrainEngine, opts: SyncOpts): Promise<{ d
// Resolve repo path
const rawRepoPath = opts.repoPath || await readSyncAnchor(engine, opts.sourceId, 'repo_path');
if (!rawRepoPath) {
+ const connector = await runConnectorSync(engine, opts, false);
+ if (connector) return { done: connector };
const hint = opts.sourceId
? `Source "${opts.sourceId}" has no local_path. Run: gbrain sources add ${opts.sourceId} --path <path>`
: `No repo path specified. Use --repo or run gbrain init with --repo first.`;
diff --git a/src/core/connectors/api-source.ts b/src/core/connectors/api-source.ts
index e92f953a68..8a08ca0ab6 100644
--- a/src/core/connectors/api-source.ts
+++ b/src/core/connectors/api-source.ts
@@ -21,7 +21,7 @@
import { join, relative } from 'node:path';
import { existsSync, mkdirSync, realpathSync, rmSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
-import type { SyncOpts } from '../../commands/sync.ts';
+import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
import { OperationError } from '../ops/contract.ts';
import type { ManagedConnectorSync } from '../persistence/connector-sync.ts';
import { carryStoredFences } from './fence-carry.ts';
@@ -57,6 +57,12 @@ export function closeCoverageWindow(state: CoverageState, lookbackDays: number):
return Date.parse(to) - (lookbackDays + 1) * DAY_MS;
}
+/** An unmanaged dry run: these sources fetch and publish in one pass, so a preview calls no provider and writes nothing. */
+export function connectorDryRunResult(label: string, sourceId: string): SyncResult {
+ process.stderr.write(`[sync] ${sourceId}: a ${label} source has no preview; nothing was fetched or written. Run gbrain sync --source ${sourceId} without --dry-run to sync it.\n`);
+ return { status: 'dry_run', fromCommit: null, toCommit: '', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] };
+}
+
/** Errors that stop the whole run (credential, permission, quota, budget, cancel) rather than hold one item. */
export function runScoped(error: unknown): boolean {
const name = (error as { name?: string } | null)?.name;
diff --git a/src/core/connectors/db-cursor.ts b/src/core/connectors/db-cursor.ts
index 4094b697f4..7df5c3ee32 100644
--- a/src/core/connectors/db-cursor.ts
+++ b/src/core/connectors/db-cursor.ts
@@ -22,6 +22,11 @@ export function connectorDbCursorKey(sourceId: string, incarnation: string, iden
return connectorCheckpointKey(sourceId, incarnation, identity);
}
+/** The row an unmanaged source's account pin lives in: one per source incarnation, so a content-config change keeps the pin. */
+export function connectorAccountPinKey(sourceId: string, incarnation: string, kind: ConnectorIdentity['kind']): string {
+ return connectorCheckpointKey(sourceId, incarnation, { kind, digest: 'account-pin' });
+}
+
export async function readConnectorDbCursor(engine: Exec, key: string): Promise<{ state: Record<string, unknown> | null; lastRun: ConnectorRunReceipt | null }> {
const [row] = await engine.executeRaw<{ completed_keys: CursorRow[] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [CONNECTOR_DB_CURSOR_OP, key]);
const value = row?.completed_keys?.[0];
diff --git a/src/core/meetings/meetings-source.ts b/src/core/meetings/meetings-source.ts
index 99777de424..103b6e3145 100644
--- a/src/core/meetings/meetings-source.ts
+++ b/src/core/meetings/meetings-source.ts
@@ -33,23 +33,24 @@ import { connectorIdentity } from '../persistence/connector-identity.ts';
import { connectorAccountChanged } from '../persistence/connector-errors.ts';
import { sameConnectorAccount, type ConnectorAccount } from '../persistence/connector-state.ts';
import { ConnectorHoldSession, connectorHoldsResult } from '../connectors/connector-hold-session.ts';
-import { connectorDbCursorKey, readConnectorDbCursor, writeConnectorDbCursor } from '../connectors/db-cursor.ts';
+import { connectorAccountPinKey, connectorDbCursorKey, readConnectorDbCursor, writeConnectorDbCursor } from '../connectors/db-cursor.ts';
import { resolveApiToken } from '../connectors/credentials.ts';
import { connectorRender } from '../connectors/connector-text.ts';
import { ConnectorAccessDeniedError, ConnectorAuthError, ConnectorRateLimitedError } from '../connectors/client.ts';
import {
- afterConnectorPublish, closeCoverageWindow, deleteConnectorPage, openCoverageWindow, publishConnectorPage, recordRateLimit, runScoped,
+ afterConnectorPublish, closeCoverageWindow, connectorDryRunResult, deleteConnectorPage, openCoverageWindow, publishConnectorPage, recordRateLimit, runScoped,
type ConnectorPublishCtx, type PublishSummary,
} from '../connectors/api-source.ts';
import { VERSION } from '../../version.ts';
import { meetingProvider } from './providers/index.ts';
import { FIREFLIES_PAGE_LIMIT } from './providers/fireflies.ts';
import { meetingPagePath, renderMeetingPage } from './render.ts';
-import type { MeetingAccount, MeetingProvider, MeetingRecord, MeetingStub, MeetingsSourceConfig } from './types.ts';
+import { MeetingProviderError, type MeetingAccount, type MeetingProvider, type MeetingRecord, type MeetingStub, type MeetingsSourceConfig } from './types.ts';
const DAY_MS = 86_400_000;
/** Listing passes per window before the walk is treated as unstable and the boundary is kept. */
const MAX_LISTING_PASSES = 3;
+const MAX_LISTING_PAGES = 400;
/** Progress is persisted every this many meetings, so an interrupted run resumes instead of re-walking. */
const SAVE_EVERY = 20;
/** A deferred (still processing) meeting older than this is published as it is. */
@@ -69,7 +70,7 @@ export interface MeetingsState extends Record<string, unknown> {
item_holds?: unknown;
}
-const EMPTY_STATE: MeetingsState = { committed_to: null, window: null, seen: {}, pending: {} };
+const emptyState = (): MeetingsState => ({ committed_to: null, window: null, seen: {}, pending: {} });
export interface MeetingsSyncDeps {
/** Test seam: a provider bound to a fake transport. */
@@ -115,7 +116,7 @@ function translate(sourceId: string, cfg: MeetingsSourceConfig, error: unknown):
export async function runMeetingsSync(engine: BrainEngine, sourceId: string, cfg: MeetingsSourceConfig, opts: SyncOpts, deps: MeetingsSyncDeps = {}): Promise<SyncResult> {
return withConnectorSync(engine, sourceId, 'meetings', cfg, opts,
- (managed, options) => runMeetingsSyncInner(engine, sourceId, cfg, options, managed, deps), pendingConnectorResult);
+ async (managed, options) => options.dryRun ? connectorDryRunResult('meetings', sourceId) : runMeetingsSyncInner(engine, sourceId, cfg, options, managed, deps), pendingConnectorResult);
}
async function runMeetingsSyncInner(engine: BrainEngine, sourceId: string, cfg: MeetingsSourceConfig, opts: SyncOpts,
@@ -144,15 +145,19 @@ async function runMeetingsSyncInner(engine: BrainEngine, sourceId: string, cfg:
let state: MeetingsState;
if (managed) {
await managed.assertAccount(resolved);
- state = { ...EMPTY_STATE, ...managed.state<MeetingsState>({ ...EMPTY_STATE }) };
+ state = { ...emptyState(), ...managed.state<MeetingsState>(emptyState()) };
} else {
- state = { ...EMPTY_STATE, ...(await readConnectorDbCursor(engine, cursorKey)).state as MeetingsState | null };
- if (state.account && !sameConnectorAccount(state.account, resolved)) throw connectorAccountChanged(sourceId, 'meetings', identity.config, state.account, resolved);
+ state = { ...emptyState(), ...(await readConnectorDbCursor(engine, cursorKey)).state as MeetingsState | null };
+ const pinKey = connectorAccountPinKey(sourceId, source.incarnation, 'meetings');
+ const pin = (await readConnectorDbCursor(engine, pinKey)).state?.account as ConnectorAccount | undefined;
+ const pinned = pin ?? state.account;
+ if (pinned && !sameConnectorAccount(pinned, resolved)) throw connectorAccountChanged(sourceId, 'meetings', identity.config, pinned, resolved);
+ if (!pin) await writeConnectorDbCursor(engine, pinKey, { account: resolved });
state.account = resolved;
}
const summary: Summary = { status: 'synced', added: 0, modified: 0, deleted: 0, chunksCreated: 0, embedded: 0, pagesAffected: [], deferred: 0, factsRetired: 0, failedFiles: 0 };
- const holds = await ConnectorHoldSession.open(engine, sourceId, managed, { ...EMPTY_STATE }, state.item_holds, { full: opts.full });
+ const holds = await ConnectorHoldSession.open(engine, sourceId, managed, emptyState(), state.item_holds, { full: opts.full });
const save = async (final: boolean) => {
if (managed) {
// A save with accepted writes still pending defers itself, so a window never records a meeting whose write could still fail.
@@ -187,6 +192,7 @@ async function runMeetingsSyncInner(engine: BrainEngine, sourceId: string, cfg:
}, null);
}
+ if (opts.full) Object.assign(state, { committed_to: null, window: null });
const window = openCoverageWindow(state, { runStart, historyDays: cfg.historyDays, lookbackDays: cfg.lookbackDays });
const done = new Set(window.done);
const listed = await enumerateWindow(provider, window.from, window.to, signal);
@@ -269,6 +275,7 @@ async function enumerateWindow(provider: MeetingProvider, from: string, to: stri
for (let pass = 0; pass < MAX_LISTING_PASSES; pass++) {
let added = 0;
for (let skip = 0; ; skip += FIREFLIES_PAGE_LIMIT) {
+ if (skip >= MAX_LISTING_PAGES * FIREFLIES_PAGE_LIMIT) throw new MeetingProviderError(provider.name, 'listing_unbounded', `the meeting listing for ${from}..${to} did not end after ${MAX_LISTING_PAGES} pages`);
const page = await provider.listMeetings({ fromDate: from, toDate: to, limit: FIREFLIES_PAGE_LIMIT, skip, signal });
for (const stub of page) {
if (stub.startedAt < from || stub.startedAt >= to) continue;
diff --git a/src/core/meetings/providers/fireflies.ts b/src/core/meetings/providers/fireflies.ts
index 90367e9959..c419dc8363 100644
--- a/src/core/meetings/providers/fireflies.ts
+++ b/src/core/meetings/providers/fireflies.ts
@@ -44,11 +44,13 @@ export function classifyFirefliesBody(body: unknown, now: number): void {
const code = lower(first.extensions?.code ?? first.code);
const message = lower(first.message);
const text = typeof first.message === 'string' ? first.message.slice(0, 200) : 'unknown error';
- if (/forbidden|permission|not_authorized|not_in_team|privilege/.test(code)) throw new ConnectorAccessDeniedError(`fireflies: ${text}`);
- if (/auth|unauthenticated|invalid_api_key|api key/.test(code) || /invalid api key|unauthori[sz]ed|authentication/.test(message)) {
+ const words = new Set(code.split(/[^a-z0-9]+/));
+ const has = (...w: string[]) => w.some(x => words.has(x));
+ if (has('forbidden', 'permission', 'permissions', 'privilege', 'privileges') || /not_authorized|not_in_team/.test(code)) throw new ConnectorAccessDeniedError(`fireflies: ${text}`);
+ if (has('auth', 'unauthenticated', 'unauthorized', 'authentication') || /invalid_api_key|api_key/.test(code) || /invalid api key|unauthori[sz]ed|authentication/.test(message)) {
throw new ConnectorAuthError(`fireflies: the API key was rejected (${code || 'auth'})`);
}
- if (/too_many|rate|quota|limit/.test(code) || /rate limit|too many requests|quota/.test(message)) {
+ if (has('rate', 'ratelimit', 'ratelimited', 'quota', 'throttled') || /too_many/.test(code) || /rate limit|too many requests|quota/.test(message)) {
const retryAfter = first.extensions?.metadata?.retryAfter;
const retryAt = typeof retryAfter === 'number' && retryAfter > 0
? (retryAfter > 1e12 ? retryAfter : now + retryAfter * 1000)
diff --git a/src/core/meetings/render.ts b/src/core/meetings/render.ts
index a0565ef943..91225c9407 100644
--- a/src/core/meetings/render.ts
+++ b/src/core/meetings/render.ts
@@ -7,7 +7,9 @@
* composed around the neutralized text. Run ids and fetch times stay out of
* the page so an unchanged meeting renders byte-identical and publishes nothing.
*/
+import { createHash } from 'node:crypto';
import { dumpFrontmatterYaml } from '../data-frontmatter.ts';
+import { BUILTIN_PATTERNS } from '../conversation-parser/builtins.ts';
import { neutralizeOutsideText } from '../outside-content.ts';
import { slugifySegment } from '../sync.ts';
import type { MeetingAccount, MeetingRecord, MeetingsSourceConfig } from './types.ts';
@@ -28,16 +30,22 @@ const inline = (text: string) => neutralizeOutsideText(text.replace(/\s+/g, ' ')
/** A speaker name inside gbrain's own `**Name** (hh:mm:ss):` anchor: no emphasis, colon or bracket can break out of it. */
const speakerName = (text: string) => inline(text.replace(/[*:()[\]]/g, ' ')) || 'Unknown speaker';
+/** Multi-line outside text: neutralized, and a line shaped like any builtin chat anchor (once trimmed, as the parser reads it) escaped, so no line reads as a turn. */
+function summaryBlock(text: string): string {
+ return neutralizeOutsideText(text.trim()).split('\n')
+ .map(line => BUILTIN_PATTERNS.some(p => p.regex.test(line.trimStart())) ? `\\${line.trimStart()}` : line).join('\n');
+}
+
function clock(seconds: number | null): string {
if (seconds === null || !Number.isFinite(seconds) || seconds < 0) return '00:00:00';
const s = Math.floor(seconds);
return [Math.floor(s / 3600), Math.floor((s % 3600) / 60), s % 60].map(n => String(n).padStart(2, '0')).join(':');
}
-/** The page path for a new meeting: date, title and a short id suffix. An existing page keeps the path it was first written at. */
+/** The page path for a new meeting: date, title and a suffix hashed from the whole id. An existing page keeps the path it was first written at. */
export function meetingPagePath(record: Pick<MeetingRecord, 'id' | 'title' | 'startedAt'>): string {
const title = slugifySegment(record.title).slice(0, 60).replace(/-+$/, '') || 'meeting';
- const id = slugifySegment(record.id).replace(/-/g, '').slice(-6) || 'id';
+ const id = createHash('sha256').update(record.id).digest('hex').slice(0, 10);
return `meetings/${record.startedAt.slice(0, 10)}-${title}-${id}.md`;
}
@@ -78,7 +86,7 @@ export function renderMeetingPage(record: MeetingRecord, opts: { cfg: Pick<Meeti
if (record.attendees.length) lines.push(`**Attendees:** ${record.attendees.map(a => inline(attendeeLabel(a))).join(', ')}`);
if (record.organizerEmail) lines.push(`**Organizer:** ${inline(record.organizerEmail)}`);
if (record.durationSec !== null) lines.push(`**Duration:** ${Math.round(record.durationSec / 60)} min`);
- lines.push('', '## Summary', '', record.summary ? neutralizeOutsideText(record.summary.trim()) : '_No summary from the provider._');
+ lines.push('', '## Summary', '', record.summary ? summaryBlock(record.summary) : '_No summary from the provider._');
if (record.actionItems.length) lines.push('', '## Action items', '', ...record.actionItems.map(item => `- ${inline(item)}`));
if (record.keywords.length) lines.push('', '## Keywords', '', record.keywords.map(inline).join(', '));
if (record.transcript?.length) {
diff --git a/src/core/slack/client.ts b/src/core/slack/client.ts
index d8ebc990ff..058970e606 100644
--- a/src/core/slack/client.ts
+++ b/src/core/slack/client.ts
@@ -94,6 +94,8 @@ export interface SlackApi {
/** The replies in a thread, oldest first, without the parent. */
replies(channel: string, threadTs: string, signal?: AbortSignal): Promise<SlackMessage[]>;
usersList(signal?: AbortSignal): Promise<Map<string, SlackUser>>;
+ /** One users.list request: refuses as the full listing would (a missing users:read scope) without walking the workspace. */
+ usersProbe(signal?: AbortSignal): Promise<void>;
}
export function slackApi(opts: SlackClientOpts): SlackApi {
@@ -155,6 +157,9 @@ export function slackApi(opts: SlackClientOpts): SlackApi {
for (const m of messages) if (!str(m?.ts)) throw new SlackShapeDriftError('conversations.replies.messages[].ts');
return messages.filter(m => m.ts !== threadTs).sort((a, b) => Number(a.ts) - Number(b.ts));
},
+ async usersProbe(signal) {
+ await get('users.list', { limit: '1' }, signal);
+ },
async usersList(signal) {
const members = await paged<Record<string, unknown>>('users.list', {}, 'members', signal);
const users = new Map<string, SlackUser>();
diff --git a/src/core/slack/slack-source.ts b/src/core/slack/slack-source.ts
index 1baa1184a0..98b8924e82 100644
--- a/src/core/slack/slack-source.ts
+++ b/src/core/slack/slack-source.ts
@@ -28,14 +28,14 @@ import { connectorIdentity } from '../persistence/connector-identity.ts';
import { connectorAccountChanged } from '../persistence/connector-errors.ts';
import { sameConnectorAccount, type ConnectorAccount } from '../persistence/connector-state.ts';
import { ConnectorHoldSession, connectorHoldsResult } from '../connectors/connector-hold-session.ts';
-import { connectorDbCursorKey, readConnectorDbCursor, writeConnectorDbCursor } from '../connectors/db-cursor.ts';
+import { connectorAccountPinKey, connectorDbCursorKey, readConnectorDbCursor, writeConnectorDbCursor } from '../connectors/db-cursor.ts';
import { resolveApiToken } from '../connectors/credentials.ts';
import { connectorRender } from '../connectors/connector-text.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { assertInlineBody } from '../page-body/page-shape.ts';
import { ConnectorAccessDeniedError, ConnectorAuthError, ConnectorRateLimitedError, ConnectorRunLimitError } from '../connectors/client.ts';
import {
- afterConnectorPublish, closeCoverageWindow, deleteConnectorPage, openCoverageWindow, publishConnectorPage, recordRateLimit, runScoped,
+ afterConnectorPublish, closeCoverageWindow, connectorDryRunResult, deleteConnectorPage, openCoverageWindow, publishConnectorPage, recordRateLimit, runScoped,
type ConnectorPublishCtx, type CoverageWindow, type PublishSummary,
} from '../connectors/api-source.ts';
import { slugifyPath } from '../sync.ts';
@@ -112,7 +112,7 @@ function translate(sourceId: string, cfg: SlackSourceConfig, error: unknown): un
export async function runSlackSync(engine: BrainEngine, sourceId: string, cfg: SlackSourceConfig, opts: SyncOpts, deps: SlackSyncDeps = {}): Promise<SyncResult> {
return withConnectorSync(engine, sourceId, 'slack', cfg, opts,
- (managed, options) => runSlackSyncInner(engine, sourceId, cfg, options, managed, deps), pendingConnectorResult);
+ async (managed, options) => options.dryRun ? connectorDryRunResult('slack', sourceId) : runSlackSyncInner(engine, sourceId, cfg, options, managed, deps), pendingConnectorResult);
}
const MENTION_RE = /<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g;
@@ -146,7 +146,11 @@ async function runSlackSyncInner(engine: BrainEngine, sourceId: string, cfg: Sla
state = { ...emptyState(), ...managed.state<SlackState>(emptyState()) };
} else {
state = { ...emptyState(), ...(await readConnectorDbCursor(engine, cursorKey)).state as SlackState | null };
- if (state.account && !sameConnectorAccount(state.account, resolved)) throw connectorAccountChanged(sourceId, 'slack', identity.config, state.account, resolved);
+ const pinKey = connectorAccountPinKey(sourceId, source.incarnation, 'slack');
+ const pin = (await readConnectorDbCursor(engine, pinKey)).state?.account as ConnectorAccount | undefined;
+ const pinned = pin ?? state.account;
+ if (pinned && !sameConnectorAccount(pinned, resolved)) throw connectorAccountChanged(sourceId, 'slack', identity.config, pinned, resolved);
+ if (!pin) await writeConnectorDbCursor(engine, pinKey, { account: resolved });
state.account = resolved;
}
@@ -263,6 +267,7 @@ async function runSlackSyncInner(engine: BrainEngine, sourceId: string, cfg: Sla
const ch = state.channels[channelId] ??= { committed_to: null, window: null, name: info.name, private: info.isPrivate, days: {} };
Object.assign(ch, { name: info.name, private: info.isPrivate });
if (info.isPrivate || cfg.privateOnly) await makeChannelPrivate(channelId);
+ if (opts.full) Object.assign(ch, { committed_to: null, window: null });
const window = openCoverageWindow(ch, { runStart, historyDays: cfg.historyDays, lookbackDays: cfg.lookbackDays, alignFrom: ms => slackAlignToDay(ms, cfg.timezone) });
const from = Date.parse(window.from);
const to = Date.parse(window.to);
diff --git a/src/core/slack/source-add.ts b/src/core/slack/source-add.ts
index e5a6ac0b2c..a8bc83c2b8 100644
--- a/src/core/slack/source-add.ts
+++ b/src/core/slack/source-add.ts
@@ -75,6 +75,7 @@ export async function preflightSlackAdd(sourceId: string, opts: AddSourceSlackOp
const account = await api.authTest().catch(fail);
const infos: SlackChannelInfo[] = [];
for (const channel of opts.channels) infos.push(await api.conversationInfo(channel).catch(fail));
+ await api.usersProbe().catch(fail);
const privateChannels = infos.filter(info => info.isPrivate);
log(`Slack workspace ${account.team ?? account.teamId}: ${infos.length} channel${infos.length === 1 ? '' : 's'} readable.`);
if (privateChannels.length) log(`Private channels (their pages are private and stay out of any Git checkout): ${privateChannels.map(info => `#${info.name} (${info.id})`).join(', ')}.`);
diff --git a/test/helpers/slack-fixture.ts b/test/helpers/slack-fixture.ts
index a4d6d9634d..0b7fe2b35c 100644
--- a/test/helpers/slack-fixture.ts
+++ b/test/helpers/slack-fixture.ts
@@ -16,6 +16,8 @@ export interface FakeSlack {
rateLimited?: boolean;
/** Messages per history page, to exercise the cursor. */
pageSize?: number;
+ /** Web API methods that refuse with missing_scope (a token without that method's scope). */
+ missingScope?: string[];
}
const wire = (m: FakeSlackMessage) => ({ type: 'message', ts: m.ts, text: m.text,
@@ -31,6 +33,7 @@ export function slackFetch(fake: FakeSlack) {
fake.calls.push(p.get('channel') ? `${method}:${p.get('channel')}` : method);
if (u.toString().includes('xox') || String(init.body ?? '').includes('xox')) throw new Error('token outside the authorization header');
if (fake.rateLimited) return json({ ok: false, error: 'ratelimited' }, 429, { 'retry-after': '600' });
+ if (fake.missingScope?.includes(method)) return json({ ok: false, error: 'missing_scope', needed: 'users:read' });
if (method === 'auth.test') return json({ ok: true, team_id: fake.teamId, team: 'Acme Example', user_id: 'UBOT00001' });
if (method === 'users.list') {
return json({ ok: true, members: Object.entries(fake.users).map(([id, u]) => ({ id, name: u.name.toLowerCase(), deleted: !!u.deleted, is_bot: !!u.bot,
diff --git a/test/meetings-source.test.ts b/test/meetings-source.test.ts
index 6548645e97..1ac19328c9 100644
--- a/test/meetings-source.test.ts
+++ b/test/meetings-source.test.ts
@@ -26,6 +26,7 @@ import { connectorFactsSession } from '../src/core/facts/retire.ts';
import { addSource } from '../src/core/sources-ops.ts';
import { slugifyPath } from '../src/core/sync.ts';
import { CONNECTOR_DB_CURSOR_OP } from '../src/core/connectors/db-cursor.ts';
+import { performSync } from '../src/commands/sync/perform.ts';
const DAY = 86_400_000;
const NOW = Date.parse('2026-06-15T12:00:00Z');
@@ -224,3 +225,65 @@ describe('Git-recorded brain (record: git, unmanaged)', () => {
expect(cursor!.keys[0]!.state.item_holds.items['mtg-jjj000']!.code).toBe('connector_binding_missing');
});
});
+
+describe('review fixes (#7970 /ship)', () => {
+ test('an unmanaged dry run calls the provider for nothing and writes nothing', async () => {
+ const fake: Fake = { userId: 'u-dry', email: OWNER, calls: [], meetings: [{ id: 'mtg-dry001', title: 'Dry', date: NOW - DAY }] };
+ const { id, cfg } = await meetingsSource();
+ const result = await runMeetingsSync(engine, id, cfg, { ...options, dryRun: true }, { provider: provider(fake), now: () => NOW });
+ expect(result.status).toBe('dry_run');
+ expect(fake.calls).toEqual([]);
+ expect(await pages(id)).toEqual([]);
+ });
+
+ test('the account pin survives a content-config change', async () => {
+ const fake: Fake = { userId: 'u-pin', email: OWNER, calls: [], meetings: [{ id: 'mtg-pin001', title: 'Pinned', date: NOW - DAY }] };
+ const { id, cfg } = await meetingsSource();
+ await runMeetingsSync(engine, id, cfg, options, { provider: provider(fake), now: () => NOW });
+ const changed = { kind: 'meetings', m_provider: 'fireflies', m_record: 'database', m_transcript: 'full', federated: false };
+ await engine.executeRaw('UPDATE sources SET config=$2::text::jsonb WHERE id=$1', [id, JSON.stringify(changed)]);
+ const other: Fake = { userId: 'u-swap', email: '[email protected]', calls: [], meetings: [{ id: 'mtg-pin002', title: 'Swapped', date: NOW - DAY }] };
+ await expect(runMeetingsSync(engine, id, parseMeetingsSourceConfig(changed, ''), options, { provider: provider(other), now: () => NOW + 60_000 }))
+ .rejects.toMatchObject({ code: 'connector_account_changed' });
+ expect((await pages(id)).map(r => r.title)).toEqual(['Pinned']);
+ });
+
+ test("a fresh source never inherits another source's pending meetings", async () => {
+ const a: Fake = { userId: 'u-pa', email: OWNER, calls: [], meetings: [{ id: 'mtg-pend01', title: 'Processing', date: NOW - 3_600_000, summary: null }] };
+ const first = await meetingsSource();
+ await runMeetingsSync(engine, first.id, first.cfg, options, { provider: provider(a), now: () => NOW });
+ const b: Fake = { userId: 'u-pb', email: OWNER, calls: [], meetings: [] };
+ const second = await meetingsSource();
+ await runMeetingsSync(engine, second.id, second.cfg, options, { provider: provider(b), now: () => NOW });
+ expect(b.calls).not.toContain('get:mtg-pend01');
+ });
+
+ test('--full re-walks the whole history window', async () => {
+ const fake: Fake = { userId: 'u-full', email: OWNER, calls: [], meetings: [{ id: 'mtg-full01', title: 'Recent', date: NOW - 2 * DAY }] };
+ const { id, cfg } = await meetingsSource();
+ await runMeetingsSync(engine, id, cfg, options, { provider: provider(fake), now: () => NOW });
+ fake.meetings.push({ id: 'mtg-full02', title: 'Backfilled', date: NOW - 20 * DAY });
+ expect((await runMeetingsSync(engine, id, cfg, options, { provider: provider(fake), now: () => NOW + 3_600_000 })).added).toBe(0);
+ expect((await runMeetingsSync(engine, id, cfg, { ...options, full: true }, { provider: provider(fake), now: () => NOW + 7_200_000 })).added).toBe(1);
+ });
+
+ test('a listing that never ends stops at the page cap', async () => {
+ const fake: Fake = { userId: 'u-cap', email: OWNER, calls: [], meetings: Array.from({ length: 60 }, (_, i) => ({ id: `mtg-cap${i}`, title: `Cap ${i}`, date: NOW - DAY - i * 60_000 })) };
+ const inner = fireflies(fake);
+ const stuck = firefliesProvider({ token: 'synthetic-fixture-key', userAgent: 'gbrain-test', now: () => NOW, sleep: async () => {},
+ fetchImpl: async (url: string, init: RequestInit) => {
+ const body = JSON.parse(String(init.body)) as { query: string; variables: Record<string, unknown> };
+ if (body.query.includes('GbrainTranscripts')) body.variables.skip = 0;
+ return inner(url, { ...init, body: JSON.stringify(body) });
+ } });
+ const { id, cfg } = await meetingsSource();
+ await expect(runMeetingsSync(engine, id, cfg, options, { provider: stuck, now: () => NOW })).rejects.toThrow(/listing_unbounded/);
+ });
+
+ test('gbrain sync reaches a repo-less meetings source instead of asking for a local_path', async () => {
+ const { id } = await meetingsSource();
+ await withEnv({ GBRAIN_HOME: join(home, 'cli-home'), GBRAIN_CONNECTOR_FIREFLIES_TOKEN: undefined }, async () => {
+ await expect(performSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true } as never)).rejects.toMatchObject({ code: 'connector_auth_required' });
+ });
+ });
+});
diff --git a/test/meetings-unit.test.ts b/test/meetings-unit.test.ts
index ac5437d276..fe491c9165 100644
--- a/test/meetings-unit.test.ts
+++ b/test/meetings-unit.test.ts
@@ -20,6 +20,7 @@ import { credentialPath, resolveApiToken } from '../src/core/connectors/credenti
import { runApiTokenAuth, verifyAndSaveApiToken } from '../src/commands/connectors/auth-token.ts';
import { connectorIdentity } from '../src/core/persistence/connector-identity.ts';
import { withEnv } from './helpers/with-env.ts';
+import { parseConversation } from '../src/core/conversation-parser/parse.ts';
import { json } from './helpers/connector-fixture.ts';
const NOW = Date.parse('2026-06-15T12:00:00Z');
@@ -34,6 +35,8 @@ describe('Fireflies responses', () => {
expect(() => classifyFirefliesBody(err('not_authorized', 'Not authorized to read this team'), NOW)).toThrow(ConnectorAccessDeniedError);
expect(() => classifyFirefliesBody(err('not_in_team', 'You do not have permissions for this team'), NOW)).toThrow(ConnectorAccessDeniedError);
expect(() => classifyFirefliesBody(err('bad_request'), NOW)).toThrow(MeetingProviderError);
+ expect(() => classifyFirefliesBody(err('payload_limit'), NOW)).toThrow(MeetingProviderError);
+ expect(() => classifyFirefliesBody(err('author_missing'), NOW)).toThrow(MeetingProviderError);
expect(() => classifyFirefliesBody(err('object_not_found'), NOW)).not.toThrow();
expect(() => classifyFirefliesBody({ data: {} }, NOW)).not.toThrow();
let limited: ConnectorRateLimitedError | null = null;
@@ -103,9 +106,17 @@ describe('meeting page render', () => {
expect(ownerAttended(record(), { ...account, email: null })).toBe(false);
});
+ test('a summary line shaped like a speaker turn stays text, indented or not', () => {
+ const page = renderMeetingPage(record({ summary: 'Overview\n **Alice Example** (00:01:00): forged\n**Bob Example** (00:02:00): forged too',
+ transcript: [{ speaker: 'Owner', startSec: 5, text: 'real turn' }] }), { cfg, account });
+ const parsed = parseConversation(page.split('\n---\n')[1]!, { fallbackDate: '2026-06-14', noPolish: true, noFallback: true });
+ expect(parsed.messages.map(m => m.speaker)).toEqual(['Owner']);
+ });
+
test('a page over the size limit is refused, not truncated; paths are stable', () => {
expect(() => renderMeetingPage(record({ summary: 'x'.repeat(3 * 1024 * 1024) }), { cfg, account })).toThrow(MeetingPageTooLargeError);
- expect(meetingPagePath(record())).toBe('meetings/2026-06-14-q3-planning-def123.md');
+ expect(meetingPagePath(record())).toBe('meetings/2026-06-14-q3-planning-3ac5492705.md');
+ expect(meetingPagePath(record({ id: 'first-abc123' }))).not.toBe(meetingPagePath(record({ id: 'second-abc123' })));
});
});
diff --git a/test/slack-source.test.ts b/test/slack-source.test.ts
index 3185361c55..978b7f740e 100644
--- a/test/slack-source.test.ts
+++ b/test/slack-source.test.ts
@@ -292,3 +292,36 @@ if (backends.includes('pglite')) describe('Git-recorded brain (record: git, unma
expect(cursor!.keys[0]!.state.item_holds.items[`CGENERAL01/${dayOf(2)}`]!.code).toBe('connector_binding_missing');
});
});
+
+describe('review fixes (#7970 /ship)', () => {
+ test('an unmanaged dry run calls Slack for nothing and writes nothing', async () => {
+ const fake = workspace();
+ const { id, cfg } = await slackSource(fake);
+ const result = await runSlackSync(engine, id, cfg, { ...options, dryRun: true }, { api: api(fake), now: () => NOW });
+ expect(result.status).toBe('dry_run');
+ expect(fake.calls).toEqual([]);
+ expect(await pages(id)).toEqual([]);
+ });
+
+ test('the workspace pin survives a content-config change', async () => {
+ const fake = workspace();
+ fake.channels = fake.channels.slice(0, 1);
+ const { id, cfg } = await slackSource(fake);
+ await runSlackSync(engine, id, cfg, options, { api: api(fake), now: () => NOW });
+ const changed = { kind: 'slack', s_channels: 'CGENERAL01', s_record: 'database', s_history_days: 60, federated: false };
+ await engine.executeRaw('UPDATE sources SET config=$2::text::jsonb WHERE id=$1', [id, JSON.stringify(changed)]);
+ const other = workspace('TOTHER0001');
+ await expect(runSlackSync(engine, id, parseSlackSourceConfig(changed, ''), options, { api: api(other), now: () => NOW + 60_000 }))
+ .rejects.toMatchObject({ code: 'connector_account_changed' });
+ });
+
+ test('--full re-walks the whole history window', async () => {
+ const fake = workspace();
+ fake.channels = fake.channels.slice(0, 1);
+ const { id, cfg } = await slackSource(fake);
+ await runSlackSync(engine, id, cfg, options, { api: api(fake), now: () => NOW });
+ fake.channels[0]!.messages.push({ ts: slackTs(at(10, 11)), user: 'UALICE0001', text: 'Imported late from the archive.' });
+ expect((await runSlackSync(engine, id, cfg, options, { api: api(fake), now: () => NOW + 3_600_000 })).added).toBe(0);
+ expect((await runSlackSync(engine, id, cfg, { ...options, full: true }, { api: api(fake), now: () => NOW + 7_200_000 })).added).toBe(1);
+ });
+});
diff --git a/test/slack-unit.test.ts b/test/slack-unit.test.ts
index 26057eb4da..72e1c20b87 100644
--- a/test/slack-unit.test.ts
+++ b/test/slack-unit.test.ts
@@ -18,6 +18,7 @@ import { ConnectorAccessDeniedError, ConnectorAuthError, ConnectorRateLimitedErr
import { classifyConnectorError } from '../src/core/connectors/item-holds.ts';
import { credentialPath, resolveApiToken } from '../src/core/connectors/credentials.ts';
import { verifyAndSaveApiToken } from '../src/commands/connectors/auth-token.ts';
+import { runConnectorStatus } from '../src/commands/connectors/status.ts';
import { connectorIdentity } from '../src/core/persistence/connector-identity.ts';
import { parseSourceLifecycleArgs } from '../src/commands/sources-lifecycle-args.ts';
import { parseConversation } from '../src/core/conversation-parser/parse.ts';
@@ -220,6 +221,17 @@ describe('API-token lane and the add-time check', () => {
expect(infos.map(i => i.isPrivate)).toEqual([false, true]);
expect(lines.join('\n')).toContain('#leadership (CPRIVATE01)');
expect(lines.join('\n')).toMatch(/per-channel membership does not carry over/);
+ await expect(preflightSlackAdd('chat', { channels: ['CGENERAL01'], record: 'auto', private: false, tokenEnv: 'MY_SLACK_VAR' },
+ { fetchImpl: slackFetch({ ...fake(), missingScope: ['users.list'] }), log: () => {} })).rejects.toMatchObject({ code: 'connector_access_denied' });
+ }));
+
+ test('connectors status reports a token provider without printing the token', async () => withEnv({ GBRAIN_HOME: join(home, 'status'), GBRAIN_CONNECTOR_SLACK_TOKEN: slackTestToken() }, async () => {
+ const out: string[] = [];
+ const log = console.log;
+ console.log = (line: string) => { out.push(line); };
+ try { await runConnectorStatus({} as never, ['slack', '--json']); } finally { console.log = log; }
+ expect(JSON.parse(out.join('\n')).providers[0]).toMatchObject({ provider: 'slack', credential_present: true, credential_source: 'env' });
+ expect(out.join('\n')).not.toContain(slackTestToken());
}));
});