Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

14.4 KB
Raw Blame
// Swarm Auditor (Phase D2, docs/mission-control.md §18): a second bot challenges a task with
// evidence, the owner answers once, and the risks left unresolved stay listed on the task until the
// person closes them. An audit never marks work passed or failed; only checks do. Pure helpers,
// shared by the app and the node tests.
import type { AwayItem, AwayLink } from './away';
import { localClock } from './clock';

export type AuditStatus = 'queued' | 'challenge' | 'rebuttal' | 'done' | 'skipped' | 'failed' | 'interrupted';
export type RiskStatus = 'open' | 'disputed' | 'resolved' | 'dismissed';
export type RiskResolution = 'resolved' | 'dismissed';

export interface Risk {
  id: string;
  audit_id: string;
  task_id: string;
  seq: number;
  risk: string;
  evidence: string;
  evidence_ids?: string[];
  stance: string | null;
  answer: string | null;
  answer_evidence: string | null;
  status: RiskStatus;
  resolved_by: string | null;
  resolved_at: string | null;
  note: string | null;
  created_at: string;
  unresolved?: boolean;
}

export interface Audit {
  id: string;
  task_id: string;
  attempt: number;
  trigger: string;
  challenger_kwant_id: string;
  owner_kwant_id: string;
  status: AuditStatus;
  reason: string | null;
  challenge_tokens: number;
  rebuttal_tokens: number;
  created_at: string;
  finished_at: string | null;
  risks: Risk[];
  /** 0.8.0 B3: the raw fresh-eyes label (fresh-eyes-audit.md §3.2); read with parseFreshEyes. */
  fresh_eyes?: unknown;
}

export interface TaskRisks {
  audits: Audit[];
  open_risks: number;
}

/** Shown wherever audits show: what an audit is and isn't. */
export const NOT_A_PASS_TEXT = 'An audit never marks work passed or failed. Only checks do that, so “no risks raised” is not a pass.';
export const SETTING_HINT =
  'On important tasks, or ones nothing outside the bot will check, a second bot challenges the work with evidence and the owner answers once. Routine runs without a check are double-checked on their first run and then at most once a week. An audit never marks work passed or failed, and each audit uses tokens.';

/** A running audit turn, as `GET /api/turns` and the turn-started event carry it (14a). */
export interface AuditTurn {
  audit_id: string;
  task_id: string;
  task_title: string;
  source_kind: string;
  trigger: string;
  stage: string;
  challenger_kwant_id: string;
  owner_kwant_id: string;
}

/** What is being double-checked, in the person's words. */
const WORK_KIND: Record<string, string> = { routine: 'routine run', delegation: 'hand-off' };
/** Why it earned a second check. */
export const AUDIT_WHY: Record<string, string> = {
  low_confidence: 'nothing else checks it',
  high_impact: 'it’s marked high priority',
  manual: 'you asked for it',
};

export interface AuditWho {
  challenger?: string | null;
  owner?: string | null;
  /** The task's title; a routine run's "Routine: " prefix is dropped. */
  title?: string | null;
  sourceKind?: string | null;
  trigger?: string | null;
  /** `rebuttal`: the owner is answering. Anything else: the challenger is checking. */
  stage?: string | null;
}

const possessive = (n: string) => (n.endsWith('s') ? `${n}’` : `${n}’s`);

/** "routine run “Daily digest”", "hand-off", "task “Fix the footer”". */
export function auditWork(sourceKind: string | null | undefined, title: string | null | undefined): string {
  const kind = WORK_KIND[sourceKind ?? ''] ?? 'task';
  const t = (title ?? '').replace(/^Routine:\s*/, '').trim();
  return t ? `${kind} “${t}”` : kind;
}

export type AuditTense = 'now' | 'will' | 'started' | 'done';

/**
 * One plain line for who is double-checking whose work, and why (14a). `subject: false` drops the
 * first name, for places already under that bot's name (the sidebar). `tense`: `started` for the
 * activity log, `done` for a finished audit, `will` for a queued one. A missing name reads
 * "A teammate" / "a teammate’s"; the audit's internals are never named.
 */
export function auditWhyLine(w: AuditWho, opts: { subject?: boolean; tense?: AuditTense } = {}): string {
  const subject = opts.subject !== false;
  const tense = opts.tense ?? 'now';
  const challenger = w.challenger?.trim() || null;
  const owner = w.owner?.trim() || null;
  const work = auditWork(w.sourceKind, w.title);
  const why = AUDIT_WHY[w.trigger ?? ''];
  const tail = why ? `: ${why}.` : '.';
  const cap = (v: string) => v[0].toUpperCase() + v.slice(1);
  if (w.stage === 'rebuttal' && tense === 'now') {
    const by = challenger ? `${possessive(challenger)} double-check` : 'a double-check';
    const head = subject ? `${owner ?? 'A teammate'} is answering` : 'Answering';
    return `${head} ${by} of the ${work}${tail}`;
  }
  const whose = owner ? possessive(owner) : 'a teammate’s';
  const verb = { now: 'is double-checking', will: 'will double-check', started: 'started double-checking', done: 'double-checked' }[tense];
  const head = subject ? `${challenger ?? 'A teammate'} ${verb}` : cap(verb.replace(/^is /, ''));
  return `${head} ${whose} ${work}${tail}`;
}

/** The heading of one audit on its task (the task itself is on screen, so no title). */
export function auditHeaderLine(a: Pick<Audit, 'status' | 'trigger' | 'challenger_kwant_id' | 'owner_kwant_id'>, names: Record<string, string>, sourceKind?: string | null): string {
  const tense: AuditTense = a.status === 'queued' ? 'will' : auditLive(a) ? 'now' : a.status === 'done' ? 'done' : 'started';
  return auditWhyLine({ challenger: names[a.challenger_kwant_id], owner: names[a.owner_kwant_id], sourceKind, trigger: a.trigger }, { tense });
}

/** The line for a running audit turn, with names looked up. */
export function auditTurnLine(a: AuditTurn, names: Record<string, string>, opts: { subject?: boolean } = {}): string {
  return auditWhyLine(
    { challenger: names[a.challenger_kwant_id], owner: names[a.owner_kwant_id], title: a.task_title, sourceKind: a.source_kind, trigger: a.trigger, stage: a.stage },
    opts,
  );
}

/**
 * The short line for compact places (sidebar busy line, Live now chip, header pill): the bot is
 * already the row's name, so it says which work, with no reason and no period (14a). The full
 * `auditTurnLine` goes in the tooltip.
 */
export function auditShortLine(a: AuditTurn, names: Record<string, string>): string {
  const t = (a.task_title ?? '').replace(/^Routine:\s*/, '').trim();
  const owner = names[a.owner_kwant_id]?.trim();
  const what = t ? `“${t}”` : `${owner ? possessive(owner) : 'a teammate’s'} ${WORK_KIND[a.source_kind] ?? 'task'}`;
  return a.stage === 'rebuttal' ? `Answering the double-check of ${what}` : `Double-checking ${what}`;
}

/** "today at 8:15 PM" today, "on Nov 7, 8:15 PM" another day. */
const when = (iso: string | null | undefined, now: number): string | null => {
  const c = localClock(iso, now);
  return c ? `${c.includes(',') ? 'on' : 'today at'} ${c}` : null;
};

/** Why a routine run went unchecked: "this routine was double-checked today at 9:00 AM; next check from Nov 14, 9:00 AM". */
export function routineSkipText(lastAuditAt: string | null | undefined, nextFrom: string | null | undefined, now: number = Date.now()): string {
  const last = when(lastAuditAt, now);
  const next = when(nextFrom, now);
  if (last && next) return `this routine was double-checked ${last}; next check from ${next.replace(/^on /, '')}`;
  if (last) return `this routine was double-checked ${last}`;
  return 'this routine was double-checked in the last week';
}

export const unresolved = (r: Pick<Risk, 'status'>) => r.status === 'open' || r.status === 'disputed';

export const RISK_STATE: Record<RiskStatus, { label: string; tone: 'amber' | 'rose' | 'emerald' | 'zinc' }> = {
  open: { label: 'Open', tone: 'amber' },
  disputed: { label: 'Disputed', tone: 'rose' },
  resolved: { label: 'Resolved', tone: 'emerald' },
  dismissed: { label: 'Dismissed', tone: 'zinc' },
};
export const riskState = (s: string) => RISK_STATE[s as RiskStatus] ?? { label: s, tone: 'zinc' as const };

/** Is the audit still going (so a card may be waiting on the person)? */
export const auditLive = (a: Pick<Audit, 'status'>) => a.status === 'queued' || a.status === 'challenge' || a.status === 'rebuttal';

/** The bot whose turn it is, or null when no turn is running. */
export function auditTurnBot(a: Pick<Audit, 'status' | 'challenger_kwant_id' | 'owner_kwant_id'>): string | null {
  if (a.status === 'challenge') return a.challenger_kwant_id;
  if (a.status === 'rebuttal') return a.owner_kwant_id;
  return null;
}

const name = (id: string, names: Record<string, string>) => names[id] || 'A bot';

/** One plain line for an audit's state. */
export function auditStatusText(a: Audit, names: Record<string, string> = {}): string {
  const challenger = name(a.challenger_kwant_id, names);
  const owner = name(a.owner_kwant_id, names);
  switch (a.status) {
    case 'queued':
      return `${challenger} will challenge it once the audit before it finishes.`;
    case 'challenge':
      return `${challenger} is challenging the work.`;
    case 'rebuttal':
      return `${owner} is answering the risks.`;
    case 'done':
      return a.risks.length === 0 ? `${challenger} raised no risks. That isn’t a pass.` : `${challenger} raised ${plural(a.risks.length, 'risk')}; ${owner} answered.`;
    case 'skipped':
      return `Skipped${a.reason ? `: ${a.reason}` : ''}.`;
    case 'failed':
      return `Didn’t finish${a.reason ? `: ${a.reason}` : ''}.`;
    case 'interrupted':
      return 'Stopped when the app restarted.';
    default:
      return a.status;
  }
}

export const TRIGGER_LABELS: Record<string, string> = {
  high_impact: 'high or urgent task',
  low_confidence: 'nothing outside the bot checks it',
  manual: 'started by you',
};
export const triggerLabel = (t: string) => TRIGGER_LABELS[t] ?? t.replace(/_/g, ' ');

const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? '' : 's'}`;

export function auditTokens(a: Pick<Audit, 'challenge_tokens' | 'rebuttal_tokens'>): number {
  return Math.max(0, (a.challenge_tokens || 0) + (a.rebuttal_tokens || 0));
}

/** Board badge: unresolved risks per task, from `GET /api/risks`. */
export function openRiskCounts(risks: Array<Pick<Risk, 'task_id' | 'status'>>): Record<string, number> {
  const out: Record<string, number> = {};
  for (const r of risks) if (unresolved(r)) out[r.task_id] = (out[r.task_id] ?? 0) + 1;
  return out;
}

export const riskBadgeText = (n: number) => (n === 1 ? '1 open risk' : `${n} open risks`);

/** A live audit's turn waiting on one of the person's approval cards. */
export interface AuditWaiting {
  audit_id: string;
  kwant_id: string;
  approval_id: string;
  /** Where the card is: its own chat when the server says, else the bot's direct chat. */
  link: AwayLink;
}

/**
 * The approval card a live audit is waiting on: a waiting approval from the bot whose turn it is,
 * asked after the audit started. Audit turns always ask, so this is what stalls an audit.
 */
export function auditWaiting(audits: Audit[], waiting: AwayItem[]): AuditWaiting | null {
  for (const a of audits) {
    const bot = auditTurnBot(a);
    if (!bot) continue;
    const since = Date.parse(a.created_at);
    const card = waiting
      .filter((i) => i.kind === 'approval' && i.kwant_id === bot && !(Date.parse(i.timestamp) < since))
      .sort((x, y) => Date.parse(y.timestamp) - Date.parse(x.timestamp))[0];
    if (!card) continue;
    const l = card.link;
    const link = l && (l.thread_id || l.channel_id || l.direct_kwant_id) ? l : { thread_id: null, channel_id: null, direct_kwant_id: bot };
    return { audit_id: a.id, kwant_id: bot, approval_id: card.id, link };
  }
  return null;
}

/** Where "Answer in chat" goes for a stalled audit: the card's chat, else the bot's direct chat. */
export function auditCardPlace(w: AuditWaiting): { channelId: string | null; kwantId: string | null; threadId: string | null } {
  const l = w.link;
  if (l.channel_id) return { channelId: l.channel_id, kwantId: null, threadId: l.thread_id };
  return { channelId: null, kwantId: l.direct_kwant_id ?? w.kwant_id, threadId: l.thread_id };
}

export type AuditorModel = 'fast' | 'balanced' | 'deep' | 'bot';

export interface AuditorSettings {
  auditor: 'on' | 'off';
  auditor_daily_cap: number;
  /** Absent on a server from before the setting: then it is neither shown nor saved. */
  auditor_model?: AuditorModel;
}
export const DAILY_CAP_MIN = 1;
export const DAILY_CAP_MAX = 50;
export const DAILY_CAPS = [1, 2, 3, 5, 10, 20, 50];

/** The model audit turns run on (`auditor_model`, §18). `fast` is the server default. */
export const AUDITOR_MODELS: Array<{ value: AuditorModel; label: string }> = [
  { value: 'fast', label: 'Fast' },
  { value: 'balanced', label: 'Balanced' },
  { value: 'deep', label: 'Deep' },
  { value: 'bot', label: 'Same as the bot' },
];
export const MODEL_HINT = 'Fast is cheapest; audits never mark work passed or failed.';
export const isAuditorModel = (v: unknown): v is AuditorModel => AUDITOR_MODELS.some((o) => o.value === v);

/** A save error that is about the audit model, so it can show next to that control. */
export const isAuditorModelError = (err: string | null | undefined): boolean => !!err && err.includes('auditor_model');
/** What the picker says after that 400, instead of the server's field name. */
export const MODEL_ERROR_TEXT = 'The server didn’t accept that audit model. Pick Fast, Balanced, Deep or Same as the bot.';

/** `auditor`, `auditor_daily_cap` and `auditor_model` from GET /api/settings; null on a server without the Auditor. */
export function parseAuditorSettings(data: unknown): AuditorSettings | null {
  if (!data || typeof data !== 'object') return null;
  const d = data as Record<string, unknown>;
  if (d.auditor !== 'on' && d.auditor !== 'off') return null;
  const cap = typeof d.auditor_daily_cap === 'number' ? Math.max(DAILY_CAP_MIN, Math.min(DAILY_CAP_MAX, Math.round(d.auditor_daily_cap))) : 5;
  const out: AuditorSettings = { auditor: d.auditor, auditor_daily_cap: cap };
  // An unknown value is kept as is: the picker shows it, and saving it back gets the server's 400.
  if (typeof d.auditor_model === 'string' && d.auditor_model) out.auditor_model = d.auditor_model as AuditorModel;
  return out;
}

/** Label for a saved audit model, including one this app doesn't know. */
export const auditorModelLabel = (m: string): string => AUDITOR_MODELS.find((o) => o.value === m)?.label ?? m;

/** What a resolve press says afterwards. */
export const riskResolvedText = (r: RiskResolution) => (r === 'resolved' ? 'Marked resolved. The task’s state doesn’t change.' : 'Dismissed. The task’s state doesn’t change.');