98d0c7f2d0
* fix(salary): align pain.001 salary file with the Swedish domestic bank dialect Verified against the Swedish Common Interpretation of ISO 20022 (Bankforeningen, Common Payment Types in Sweden, Appendix 1 Example 4: Salaries) and Nordea Corporate Access pain.001 examples v2.6 (2026-06-22), and XSD-validated against the official pain.001.001.03 schema: - drop SvcLvl SEPA (SEPA credit transfers are EUR-only; omitting SvcLvl gets the domestic NURG default) - drop RmtInf (not allowed for SALA salary payments; the beneficiary statement text comes from the Dataclearing LON code) - address employees domestically: clearing as CdtrAgt ClrSysMmbId SESBA, account WITHOUT clearing as CdtrAcct Othr with SchmeNm BBAN - share the clearing/account split (Swedbank 5-digit shift, Nordea personkonto prefix dedup) between the LB and pain.001 generators via splitDomesticBankAccount, fixing pain.001 duplicating the personkonto clearing - clamp MsgId/PmtInfId/InstrId/EndToEndId to Max35Text with the per-tx counter surviving truncation; carry the org number on Dbtr - return 400 from the pain001 route on an invalid clearing instead of emitting a broken file Also includes two unrelated decision-log lines from the parallel revisor-review session (DECISIONS.md is a shared append-only log). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(nav): surface the year-end chain in the sidebar Add Periodiseringar, Arsredovisning (aktiebolag only) and Inkomstdeklaration (INK2 for AB, NE-bilaga for EF) to the Skatt & bokslut group, in workflow order. Entity gating via a new entityOnly flag on NavItem; isActive carve-outs extended so exactly one row lights up for the new routes. Driven by an external revisor review that concluded these features did not exist because none of them were reachable from the nav. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(stripe): Stripe Connect integration behind config gate Connect OAuth per company (only the acct_ id is stored), automatic single-use Payment Links on invoice send, deterministic payment settlement against 1686 (BAS moved acquirer receivables 1580 -> 1686), payout booking with reverse-charge fees (6570 + 4535/4598 + 2645/2614), and a 15-minute sync cron. Non-deterministic events land as needs_review, never guessed at. Fully dark without STRIPE_CONNECT_CLIENT_ID: connect returns 503, the send hook and cron no-op, and the settings page shows 'Kommer snart' (hosted) until the Connect platform is verified. Self-hosted keeps the honest not-configured message. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(deadlines): add shared completeTaxDeadline and fix dead AGI deadline auto-complete generate-declaration.ts has updated non-existent columns (type/period/ status) since inception, so the arbetsgivardeklaration deadline was never auto-completed. Replace with a shared helper targeting the real schema (tax_deadline_type/tax_period/is_completed), also used by the kvittens crons and moms handlers in the follow-up commit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(rot-rut): import Skatteverket beslutsfil and record decisions on payout requests Parse the beslutsfil JSON from Skatteverkets rot/rut e-tjanst and record godkant belopp on the matching begaran: matched by stored skv_referensnummer first, then exact name among active undecided requests; arenden by fakturanummer then personnummer, exactly-one or the beslut errors (all-or-nothing). Never auto-settles: recording the beslut and booking the payout are separate acts. Exposed as an API route and the gnubok_import_rot_rut_beslut MCP tool. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(skatteverket): system auth for background reads, one-click VAT submit, kvittens notifications Hybrid auth program: system CCG (org certificate) for background reads while personal BankID stays for interactive submissions, since SKV per-flow refresh tokens live 65 min and crons structurally cannot run on them. All system-auth code sits behind SKATTEVERKET_SYSTEM_AUTH_MODE (default off) with a stub transport until the Expisoft cert and CCG avtal land; auth resolution is centralized in resolve-auth.ts. Also in this change: - One-click VAT submit chaining kontrollera -> utkast -> las server-side with a stage discriminator; step-by-step buttons demoted to the overflow menu. - Kvittens crons (AGI + new VAT schedule) with email-only notifications, deduped in notification_log under the new skv_kvittens type. - Ombud grant probe + verification UI in the connect panel, and a dashboard promo card for unconnected companies. - skatteverket_company_connections table with pg-real coverage. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(salary): auto-settle AGI tax payment from skattekonto and surface SKV reconnect on the tax card The "Skatt att betala" card only cleared via the manual mark-paid button on the run detail page; the promised automatic flip from the Skattekonto sync was never implemented, so paid periods stayed red. - settleAgiTaxPayments: during every skattekonto sync, a booked "Arbetsgivardeklaration YYYYMM" debit row settles the matching agi_declarations.tax_paid_at, but only when the amount equals the declared total to the ore and the account is not in deficit (deterministic; drift or deficit falls back to manual). - Salary overview card: reconnect hint when the SKV token needs re-consent (link to /settings/tax, silent when the extension is off), plus an inline "Markera som betald" button reusing the existing endpoint and salary_payments strings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Add cloud backup scheduling and alerting features - Implement unit tests for scheduling logic in `schedule.test.ts`, covering various scenarios for determining if a backup schedule is due. - Create a new module `backup-alert.ts` to handle failure alerts for cloud backup auto-sync, including email notifications for reauthentication and repeated failures. - Introduce `schedule.ts` to manage scheduling logic, including handling local time zones and converting between local and UTC hours. - Add CSV report generation functions in `archive-csv.ts` for trial balance, income statement, balance sheet, and general ledger, ensuring compatibility with Swedish Excel formats. - Create a README generator for the archive structure in `archive-readme.ts`, providing clear documentation for users accessing backup files. - Implement tests for CSV report generation in `archive-csv.test.ts`, ensuring correct formatting and content. - Establish a full-archive coverage contract test in `full-archive-coverage.pg.test.ts` to ensure all company-scoped tables are properly classified for backup. * fix(stripe): correct invoice clearing reference and improve type safety in sync logic * fix(invoices): narrow accountingMethod before resolveInvoicePaymentSourceType settleInvoicePayment takes accountingMethod as a raw settings string, but resolveInvoicePaymentSourceType requires the 'accrual' | 'cash' union. Normalize at the call site (anything but 'cash' books as accrual), matching the existing useCashEntry semantics. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix: address CodeRabbit review findings and nitpicks on PR #1004 Review findings: - backup settings redirect: always force view=export over incoming params - AGI/VAT kvittens crons: isolate best-effort post-submit calls, check the signed-state persist error, guard recovery calls in catch blocks so one company cannot abort the rest; surface grant_revoked in the run summary - kvittens notifications: atomic claim-first dedup with a partial unique index; map non-uuid reference keys to deterministic uuids - grant probe: record the actual 2xx status; mTLS transport: handle response-stream errors - stripe: amount-aware idempotency keys for payment links; emit stripe.disconnected on upstream revocations - ROT/RUT beslut import: mutate in-memory request state after apply, move item + header writes into an atomic apply_rot_rut_beslut RPC, add rot_rut_payout to JournalEntrySourceTypeSchema - migrations: use NOT VALID + VALIDATE CONSTRAINT for CHECK constraints on journal_entries, notification_log and rot_rut_payout_requests - cloud backup: hour_utc-only schedule updates clear stale hour_local Nitpicks: - stripe sync: enforce the cron time budget inside per-connection event processing with idempotent cursor progress; maybeSingle for settings; honest partial-customer DTO shared with the settlement boundary - shared applyPaymentLinkToInvoice helper for both invoice send routes, v1 docblock documents step 6b and PAYMENT_LINK_FAILED - settings panel: drop redundant decodeURIComponent - cloud backup: document worst-case archive memory headroom Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
309 lines
18 KiB
TypeScript
309 lines
18 KiB
TypeScript
import type {
|
|
JournalEntry,
|
|
Invoice,
|
|
Transaction,
|
|
Customer,
|
|
Supplier,
|
|
Article,
|
|
FiscalPeriod,
|
|
DocumentAttachment,
|
|
Receipt,
|
|
CreditNote,
|
|
ReconciliationMethod,
|
|
InvoiceInboxItem,
|
|
SupplierInvoice,
|
|
} from '@/types'
|
|
|
|
// ============================================================
|
|
// Core Event Types: discriminated union of all system events
|
|
// ============================================================
|
|
|
|
export type CoreEvent =
|
|
// Bookkeeping
|
|
| { type: 'journal_entry.drafted'; payload: { entry: JournalEntry; userId: string; companyId: string } }
|
|
| { type: 'journal_entry.committed'; payload: { entry: JournalEntry; userId: string; companyId: string } }
|
|
| { type: 'journal_entry.corrected'; payload: { original: JournalEntry; storno: JournalEntry; corrected: JournalEntry; userId: string; companyId: string } }
|
|
| { type: 'journal_entry.reversed'; payload: { originalEntry: JournalEntry; reversalEntry: JournalEntry; userId: string; companyId: string } }
|
|
| { type: 'journal_entry.deleted'; payload: { entryId: string; voucherSeries: string; voucherNumber: number; userId: string; companyId: string } }
|
|
// Documents
|
|
| { type: 'document.uploaded'; payload: { document: DocumentAttachment; userId: string; companyId: string } }
|
|
| { type: 'document.accessed'; payload: { document: { id: string; file_name: string }; userId: string; companyId: string } }
|
|
| { type: 'document.deleted'; payload: { document: { id: string; file_name: string }; userId: string; companyId: string } }
|
|
// Invoicing
|
|
| { type: 'invoice.created'; payload: { invoice: Invoice; userId: string; companyId: string } }
|
|
// Hard delete of an un-finalized, unnumbered draft (no F-series number was
|
|
// consumed). Carries only the identifiers (the row is gone) so the audit
|
|
// log can record who removed which draft and when. Numbered drafts are
|
|
// makulerade instead and surface via the journal, not this event.
|
|
| { type: 'invoice.draft_deleted'; payload: { invoiceId: string; userId: string; companyId: string } }
|
|
| { type: 'invoice.sent'; payload: { invoice: Invoice; userId: string; companyId: string } }
|
|
| { type: 'invoice.paid'; payload: { invoice: Invoice; paymentAmount: number; paymentDate: string; userId: string; companyId: string } }
|
|
| { type: 'credit_note.created'; payload: { creditNote: CreditNote; userId: string; companyId: string } }
|
|
// Recurring invoices: emitted by the daily cron after a schedule spawns
|
|
// an invoice. `autoSent` tells observers whether the email also went out
|
|
// (false means it was created as draft for manual review).
|
|
| { type: 'recurring_invoice.executed'; payload: {
|
|
scheduleId: string
|
|
invoice: Invoice
|
|
autoSent: boolean
|
|
warning: string | null
|
|
userId: string
|
|
companyId: string
|
|
} }
|
|
// Banking
|
|
| { type: 'transaction.synced'; payload: { transactions: Transaction[]; userId: string; companyId: string } }
|
|
| { type: 'transaction.categorized'; payload: { transaction: Transaction; account: string; taxCode: string; userId: string; companyId: string } }
|
|
| { type: 'transaction.reconciled'; payload: { transaction: Transaction; journalEntryId: string; method: ReconciliationMethod; userId: string; companyId: string } }
|
|
// Bank connection lifecycle: consent + account selection are the
|
|
// GDPR/PSD2 audit points; emitted to event_log for compliance trail.
|
|
| { type: 'bank_connection.consent_granted'; payload: { connectionId: string; bankName: string | null; accountCount: number; consentExpiresAt: string | null; userId: string; companyId: string } }
|
|
| { type: 'bank_connection.account_selection_changed'; payload: { connectionId: string; bankName: string | null; previousStatus: string; newStatus: string; enabledCount: number; totalCount: number; userId: string; companyId: string } }
|
|
| { type: 'bank_connection.revoked'; payload: { connectionId: string; bankName: string | null; userId: string; companyId: string } }
|
|
// Emitted when the PSD2 callback fails to mirror a returned account into
|
|
// cash_accounts. ASVS V16 / ISO 27001 A.8.15: security-relevant failures
|
|
// must land in a structured audit log (event_log, 30-day TTL) rather than
|
|
// being lost to console.error.
|
|
| { type: 'bank_connection.cash_account_mirror_failed'; payload: {
|
|
connectionId: string
|
|
bankName: string | null
|
|
accountUid: string
|
|
ledgerAccount: string
|
|
currency: string
|
|
reason: string
|
|
userId: string
|
|
companyId: string
|
|
} }
|
|
// Stripe Connect lifecycle: connect/disconnect are outward-facing consent
|
|
// transitions (a third party gains/loses access to payment data), so they
|
|
// land in event_log for the audit trail, mirroring bank_connection.*.
|
|
| { type: 'stripe.connected'; payload: { connectionId: string; stripeAccountId: string; livemode: boolean; userId: string; companyId: string } }
|
|
| { type: 'stripe.disconnected'; payload: { connectionId: string; stripeAccountId: string | null; reason: 'user' | 'revoked_upstream'; userId: string; companyId: string } }
|
|
// Periods
|
|
| { type: 'period.locked'; payload: { period: FiscalPeriod; userId: string; companyId: string } }
|
|
| { type: 'period.unlocked'; payload: { period: FiscalPeriod; userId: string; companyId: string } }
|
|
| { type: 'period.year_closed'; payload: { period: FiscalPeriod; userId: string; companyId: string } }
|
|
// Customers
|
|
| { type: 'customer.created'; payload: { customer: Customer; userId: string; companyId: string } }
|
|
// Articles (artikelregister)
|
|
| { type: 'article.created'; payload: { article: Article; userId: string; companyId: string } }
|
|
| { type: 'article.updated'; payload: { article: Article; userId: string; companyId: string } }
|
|
// Suppliers
|
|
| { type: 'supplier.created'; payload: { supplier: Supplier; userId: string; companyId: string } }
|
|
// Receipts
|
|
| { type: 'receipt.extracted'; payload: {
|
|
receipt: Receipt;
|
|
documentId: string | null;
|
|
confidence: number;
|
|
userId: string;
|
|
companyId: string;
|
|
}}
|
|
| { type: 'receipt.matched'; payload: {
|
|
receipt: Receipt;
|
|
transaction: Transaction;
|
|
confidence: number;
|
|
autoMatched: boolean;
|
|
userId: string;
|
|
companyId: string;
|
|
}}
|
|
| { type: 'receipt.confirmed'; payload: {
|
|
receipt: Receipt;
|
|
businessTotal: number;
|
|
privateTotal: number;
|
|
userId: string;
|
|
companyId: string;
|
|
}}
|
|
// Supplier Invoice Lifecycle
|
|
| { type: 'supplier_invoice.registered'; payload: { supplierInvoice: SupplierInvoice; userId: string; companyId: string } }
|
|
| { type: 'supplier_invoice.approved'; payload: { supplierInvoice: SupplierInvoice; userId: string; companyId: string } }
|
|
| { type: 'supplier_invoice.paid'; payload: { supplierInvoice: SupplierInvoice; paymentAmount: number; userId: string; companyId: string } }
|
|
| { type: 'supplier_invoice.credited'; payload: { supplierInvoice: SupplierInvoice; creditNote: SupplierInvoice; userId: string; companyId: string } }
|
|
| { type: 'supplier_invoice.uncredited'; payload: { supplierInvoice: SupplierInvoice; reversedCreditNoteId: string; reversalEntryId: string | null; userId: string; companyId: string } }
|
|
// Payment Matching
|
|
| { type: 'invoice.match_confirmed'; payload: { invoice: Invoice; transaction: Transaction; userId: string; companyId: string } }
|
|
| { type: 'supplier_invoice.match_confirmed'; payload: { supplierInvoice: SupplierInvoice; transaction: Transaction; userId: string; companyId: string } }
|
|
// Supplier Invoice Inbox
|
|
| { type: 'supplier_invoice.received'; payload: { inboxItem: InvoiceInboxItem; userId: string; companyId: string } }
|
|
| { type: 'supplier_invoice.extracted'; payload: { inboxItem: InvoiceInboxItem; confidence: number; userId: string; companyId: string } }
|
|
| { type: 'supplier_invoice.confirmed'; payload: { inboxItem: InvoiceInboxItem; supplierInvoice: SupplierInvoice; userId: string; companyId: string } }
|
|
// Salary
|
|
| { type: 'salary_run.created'; payload: { salaryRunId: string; periodYear: number; periodMonth: number; userId: string; companyId: string } }
|
|
| { type: 'salary_run.approved'; payload: { salaryRunId: string; approvedBy: string; userId: string; companyId: string } }
|
|
| { type: 'salary_run.approval_reverted'; payload: { salaryRunId: string; revertedBy: string; deletedAgiDeclarationId: string | null; userId: string; companyId: string } }
|
|
| { type: 'salary_run.booked'; payload: { salaryRunId: string; entryIds: string[]; userId: string; companyId: string } }
|
|
| { type: 'agi.generated'; payload: { agiId: string; periodYear: number; periodMonth: number; userId: string; companyId: string } }
|
|
| { type: 'agi.submitted'; payload: { salaryRunId: string; periodYear: number; periodMonth: number; userId: string; companyId: string } }
|
|
// Bolagsverket: digital inlämning av årsredovisning. Status values follow
|
|
// GUIDE §5.2.2 (arsred_inkommen → … → arsred_registrerad). `uploaded` fires
|
|
// when the iXBRL lands in eget utrymme; the undertecknare then signs the
|
|
// fastställelseintyg at Bolagsverket and the webhook drives the rest.
|
|
| { type: 'arsredovisning.uploaded'; payload: { submissionId: string; fiscalPeriodId: string; idnummer: string; environment: 'test' | 'accept' | 'prod'; userId: string; companyId: string } }
|
|
| { type: 'arsredovisning.status_changed'; payload: { submissionId: string; fiscalPeriodId: string | null; previousStatus: string; status: string; bolagsverketStatus: string; userId: string; companyId: string } }
|
|
| { type: 'arsredovisning.registered'; payload: { submissionId: string; fiscalPeriodId: string | null; userId: string; companyId: string } }
|
|
| { type: 'arsredovisning.forelagd'; payload: { submissionId: string; fiscalPeriodId: string | null; userId: string; companyId: string } }
|
|
// Skatteverket: Skattekonto sync
|
|
| { type: 'skattekonto.synced'; payload: { booked: number; upcoming: number; balanceSkv: number; balanceKfm: number; userId: string; companyId: string } }
|
|
| { type: 'skattekonto.balance.changed'; payload: { previousBalance: number; currentBalance: number; userId: string; companyId: string } }
|
|
| { type: 'skattekonto.transaction.upcoming'; payload: { transaktionsdatum: string; forfallodatum: string; transaktionstext: string; beloppSkatteverket: number; userId: string; companyId: string } }
|
|
| { type: 'skattekonto.connection.expired'; payload: { reason: 'REFRESH_EXHAUSTED' | 'SESSION_EXPIRED' | 'TOKEN_CORRUPTED'; userId: string; companyId: string } }
|
|
// Fired when the SKV saldo and GL 1630 sum diverge beyond the configured
|
|
// tolerance. The drift handler emails the company contact; UI surfaces a
|
|
// dashboard tile via /api/extensions/skatteverket/skattekonto/drift.
|
|
| { type: 'skattekonto.drift_detected'; payload: {
|
|
drift: number // SKV saldo - GL 1630 sum (signed)
|
|
saldoSkatteverket: number
|
|
glSum1630: number
|
|
fetchedAt: number // ms epoch from the snapshot
|
|
unbookedCount: number // skattekonto rows without journal_entry_id ≤ fetchedAt
|
|
userId: string
|
|
companyId: string
|
|
} }
|
|
// Company & account lifecycle
|
|
| { type: 'company.deleted'; payload: { companyId: string; userId: string; archivedAt: string } }
|
|
| { type: 'account.deleted'; payload: { userId: string; deletedAt: string } }
|
|
// MCP telemetry: fired from the MCP dispatcher.
|
|
// Persisted to event_log (180-day TTL for mcp.*/agent.* rows, vs 30 days for
|
|
// delivery events) for hot-tool / error-rate / latency analytics.
|
|
// Intentionally lightweight: no args, no result body, only metadata.
|
|
| { type: 'mcp.tool_called'; payload: {
|
|
tool: string // e.g. 'gnubok_create_invoice'
|
|
requiredScope: string | null // from TOOL_SCOPE_MAP, null if unscoped
|
|
actorType: 'user' | 'api_key' | 'mcp_oauth' | 'cron'
|
|
actorId: string | null // api_key id, oauth client, etc.
|
|
actorLabel: string | null // human-readable actor label
|
|
latencyMs: number // wall-clock time inside execute()
|
|
success: boolean // true iff the tool returned without throwing AND was invoked (not denied)
|
|
isError: boolean // matches the JSON-RPC tool-result isError flag returned to the client
|
|
errorCode: string | null // structured error code from tool-result.toToolError when applicable
|
|
errorKind: 'execution' | 'scope_denied' | 'capability_denied' | 'unknown_tool' | 'test_key_write_blocked' | null
|
|
errorMessage: string | null // human-readable error message (truncated to 500 chars), null on success.
|
|
// Raw material for clustering real agent failures into curated gotchas:
|
|
// errorCode alone can't distinguish "period locked" from "unbalanced".
|
|
requestId: string | number | null // JSON-RPC request id (helps correlate with client-side logs)
|
|
userId: string
|
|
companyId: string
|
|
sessionId: string | null // from Mcp-Session-Id header; null if absent
|
|
client: string | null // distribution-channel marker (X-Gnubok-Client header / ?client= param, e.g. 'openclaw').
|
|
// Client-supplied (allow-list-sanitized): telemetry only, never identity or authz.
|
|
}}
|
|
// tools/list: informs us whether agents are using progressive discovery
|
|
// (gnubok_search_tools) or pulling the full list. Tool counts vary with
|
|
// the caller's scope set.
|
|
| { type: 'mcp.tools_list_called'; payload: {
|
|
toolCount: number // tools actually returned (post scope filter)
|
|
actorType: 'user' | 'api_key' | 'mcp_oauth' | 'cron'
|
|
actorId: string | null
|
|
actorLabel: string | null
|
|
latencyMs: number
|
|
requestId: string | number | null
|
|
userId: string
|
|
companyId: string
|
|
sessionId: string | null // from Mcp-Session-Id header; null if absent
|
|
client: string | null // distribution-channel marker; null if absent
|
|
}}
|
|
// resources/read: informs us which skills/widgets/data resources actually
|
|
// get loaded by agents. `kind` discriminates by URI scheme so we can
|
|
// GROUP BY skill vs widget vs data without parsing URIs.
|
|
| { type: 'mcp.resource_read'; payload: {
|
|
uri: string // e.g. 'Accounted://skill/month-end-close'
|
|
kind: 'widget' | 'skill' | 'data' | 'unknown'
|
|
success: boolean
|
|
errorCode: string | null
|
|
latencyMs: number
|
|
actorType: 'user' | 'api_key' | 'mcp_oauth' | 'cron'
|
|
actorId: string | null
|
|
actorLabel: string | null
|
|
requestId: string | number | null
|
|
userId: string
|
|
companyId: string
|
|
sessionId: string | null // from Mcp-Session-Id header; null if absent
|
|
client: string | null // distribution-channel marker; null if absent
|
|
}}
|
|
// Workflow lifecycle: agents declare "I'm starting month-end-close" via
|
|
// gnubok_load_skill (or implicitly by following a skill's recommended tool
|
|
// sequence). Phase 3A captures these to measure: how often is a workflow
|
|
// started? How often does it complete? Where do agents abandon?
|
|
| { type: 'mcp.workflow_started'; payload: {
|
|
slug: string // e.g. 'month-end-close'
|
|
sessionId: string | null
|
|
actorType: 'user' | 'api_key' | 'mcp_oauth' | 'cron'
|
|
actorId: string | null
|
|
actorLabel: string | null
|
|
userId: string
|
|
companyId: string
|
|
}}
|
|
| { type: 'mcp.workflow_completed'; payload: {
|
|
slug: string
|
|
sessionId: string | null
|
|
outcome: 'success' | 'abandoned' | 'failed'
|
|
stepsCompleted: number | null // null when not tracked granularly
|
|
durationMs: number | null
|
|
actorType: 'user' | 'api_key' | 'mcp_oauth' | 'cron'
|
|
actorId: string | null
|
|
actorLabel: string | null
|
|
userId: string
|
|
companyId: string
|
|
}}
|
|
// Fires on EVERY successful gnubok_load_skill: all tiers, unlike
|
|
// mcp.workflow_started which fires only for workflow-tier skills. Records
|
|
// WHICH skill/atom bodies agents actually pull, the denominator needed to
|
|
// correlate a loaded atom with downstream tool-error rates (a skill can
|
|
// make the model worse: measure, don't assume).
|
|
| { type: 'mcp.skill_loaded'; payload: {
|
|
slug: string // e.g. 'modifier/holding-ab', 'month-end-close'
|
|
tier: 'workflow' | 'horizontal' | 'vertical' | 'modifier'
|
|
sessionId: string | null
|
|
actorType: 'user' | 'api_key' | 'mcp_oauth' | 'cron'
|
|
actorId: string | null
|
|
actorLabel: string | null
|
|
userId: string
|
|
companyId: string
|
|
}}
|
|
// Fires when the agent's next tool call matches the previous response's
|
|
// nextHint.tool: measures whether `next` hints are actually followed.
|
|
// Computed dispatcher-side by comparing the last response shape to the
|
|
// current call.
|
|
| { type: 'mcp.next_hint_followed'; payload: {
|
|
fromTool: string
|
|
toTool: string
|
|
sessionId: string | null
|
|
actorType: 'user' | 'api_key' | 'mcp_oauth' | 'cron'
|
|
actorId: string | null
|
|
actorLabel: string | null
|
|
userId: string
|
|
companyId: string
|
|
}}
|
|
// Agent self-reported feedback (gnubok_feedback tool). The product team
|
|
// queries event_log for `agent.feedback` and routes to a backlog.
|
|
| { type: 'agent.feedback'; payload: {
|
|
context: string
|
|
sentiment: 'positive' | 'negative' | 'neutral'
|
|
suggestion: string | null
|
|
toolName: string | null
|
|
skillSlug: string | null
|
|
sessionId: string | null
|
|
actorType: 'user' | 'api_key' | 'mcp_oauth' | 'cron'
|
|
actorId: string | null
|
|
actorLabel: string | null
|
|
userId: string
|
|
companyId: string
|
|
}}
|
|
|
|
// ============================================================
|
|
// Helper Types
|
|
// ============================================================
|
|
|
|
/** All possible event type strings */
|
|
export type CoreEventType = CoreEvent['type']
|
|
|
|
/** Extract the payload type for a given event type */
|
|
export type EventPayload<T extends CoreEventType> = Extract<CoreEvent, { type: T }>['payload']
|
|
|
|
/** Handler function for a specific event type */
|
|
export type EventHandler<T extends CoreEventType> = (payload: EventPayload<T>) => Promise<void> | void
|
|
|
|
/** Subscription: event type + handler */
|
|
export interface EventSubscription<T extends CoreEventType = CoreEventType> {
|
|
eventType: T
|
|
handler: EventHandler<T>
|
|
}
|