Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 2 (L5): public_category beside category, from classifyTerminal everywhere
garrytan6c27e846b8f1
diff --git a/src/commands/doctor/checks/sync-failures.ts b/src/commands/doctor/checks/sync-failures.tsindex 4ee1496a1f..9dd2c96558 100644--- a/src/commands/doctor/checks/sync-failures.ts+++ b/src/commands/doctor/checks/sync-failures.ts@@ -7,6 +7,7 @@ import { makeRemediationStep } from '../../../core/remediation-step.ts';import { classifyManagedSyncOrphans, type ManagedSyncOrphan } from '../../../core/persistence/managed-sync-orphans.ts';import { readManagedMode } from '../../../core/persistence/ownership.ts';import { legacyLedgerNote } from '../../../core/persistence/legacy-sync-failures.ts';+import { classifyRecordedFault } from '../../../core/persistence/terminal-classify.ts';/** #6518 [R18 vi]: the fast check cannot verify a mirror row; a warning there is uncertainty, never recovery. */const MIRROR_UNVERIFIED = (count: number) => `${count} mirrored managed sync failure(s) could not be verified without a database connection: `@@ -74,7 +75,12 @@ export async function checkSyncFailures(engine: BrainEngine | null, opts: { sour? `${resumable.length || !orphans.length ? `Fix the cause, then run ${retries.length ? retries.join(' ; ') : 'gbrain sync --no-pull --retry-failed with the same source and options'}. Completed full runs do not resolve a different unfinished cursor.` : ''}${orphanNote}${unreadNote}`.trim(): `Fix the file(s) and re-run 'gbrain sync', or use 'gbrain sync --skip-failed' to acknowledge legacy file failures.${orphanNote}${unreadNote}`;const legacyNote = managedBrain ? legacyLedgerNote(unresolvedLegacy) : '';+ // #6712 PR 2 (L5): each managed failure with the classifier's category and the public category beside it.+ const failures = managed.map(row => {+ const v = classifyRecordedFault({ source_id: row.source_id, code: row.code, request_id: row.request_id, error_detail: row.write_error_detail ?? null, message: row.message });+ return { source_id: row.source_id, path: row.path, code: row.code, category: v.category, public_category: v.public_category, class: v.class, needs_human: v.needs_human };+ });return { name: 'sync_failures', status: severity.status, message: `${summary} ${details.join('; ')} ${recovery}${legacyNote}`,- remediation, remediation_status: remediation ? 'remediable' : 'blocked', ...(orphans.length ? { details: { orphans } } : {}),+ remediation, remediation_status: remediation ? 'remediable' : 'blocked', ...(orphans.length || failures.length ? { details: { ...(orphans.length ? { orphans } : {}), ...(failures.length ? { failures } : {}) } } : {}),...(engine ? {} : { message: `${summary} Durable sync state is unavailable without a database connection; the local ledger is only a compatibility mirror.${mirrorNote}` }) };}diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.tsindex 95273bb392..e48beb1300 100644--- a/src/core/ops/persistence.ts+++ b/src/core/ops/persistence.ts@@ -126,7 +126,7 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: Woperation: row.operation, source_id: row.source_id, slug: row.slug,...(mismatch ? { owner_build: mismatch } : {}),...(diagnostic ? { write_error: row.error_code, write_error_message: diagnostic.message, write_error_reason: diagnostic.reason, suggestion: diagnostic.suggestion } : {}),- ...(terminal ? { diagnosis: { category: terminal.category, code: terminal.code, class: terminal.class, safe_actions: terminal.safe_actions, needs_human: terminal.needs_human,+ ...(terminal ? { diagnosis: { category: terminal.category, public_category: terminal.public_category, code: terminal.code, class: terminal.class, safe_actions: terminal.safe_actions, needs_human: terminal.needs_human,...(terminal.human_reason ? { human_reason: terminal.human_reason } : {}), escalate: terminal.escalate, historical: terminal.historical,fix: renderAction(terminal.action, render) } } : {}),...(withdrawn ? { withdrawn } : {}),diff --git a/src/core/persistence/public-category.ts b/src/core/persistence/public-category.tsnew file mode 100644index 0000000000..e2967a6145--- /dev/null+++ b/src/core/persistence/public-category.ts@@ -0,0 +1,72 @@+/**+ * #6712 PR 2 (L5): the public category of a fault, a small closed vocabulary an operator or agent can branch on without+ * knowing gbrain's internal codes. It sits beside the existing `category` (`terminal-classify.ts` `TerminalCategory`, the+ * diagnosis vocabulary), which is unchanged. The mapping is total: every terminal category, every `SYNC_FAULT_TABLE` code+ * and every registry code has one (a code this build does not know is `defect`), so `public_category` is never absent.+ *+ * drift the file or the database moved under the write (a working-tree edit, a page that changed since import)+ * conflict two writers changed the same page; a person or the caller picks+ * content_refused the file's own content was refused (frontmatter, fences, size, a gate)+ * file_missing the page's file is gone (a ghost page)+ * permission the principal may not do this+ * storage the database or the worktree refused or needs recovery+ * config a setting, a cap or a choice on the brain host decides+ * superseded another run or request made this one moot; nothing to fix+ * transient retry: a connection, a lease, back-pressure or a stalled preparation+ * defect a gbrain fault to report (or a cause this build cannot name)+ */+import { CODES } from '../error-registry.ts';+import type { TerminalCategory } from './terminal-classify.ts';++export const PUBLIC_CATEGORIES = ['drift', 'conflict', 'content_refused', 'file_missing', 'permission', 'storage', 'config', 'superseded', 'transient', 'defect'] as const;+export type PublicCategory = typeof PUBLIC_CATEGORIES[number];++/** Every terminal category; `sync_fault` and `caller_refusal` refine by code. */+export const PUBLIC_BY_TERMINAL: Readonly<Record<TerminalCategory, PublicCategory>> = {+ recovery_pending: 'transient', recovery_blocked: 'storage',+ knock_on: 'superseded', run_replaced: 'superseded', outside_fence: 'defect',+ operator_cancelled: 'superseded', caller_conflict: 'conflict', file_conflict: 'drift', canonical_file_missing: 'file_missing', fence_unrenderable: 'defect',+ writer_guard: 'defect', database_refusal: 'config', owner_exception: 'defect', legacy_publication_refusal: 'superseded',+ sync_fault: 'defect', transport: 'transient', caller_refusal: 'content_refused', gbrain_defect: 'defect', diagnosis_required: 'defect',+};++/** Fault codes (holds, run stops, receipts) by name; a test pins that every `SYNC_FAULT_TABLE` code is here. */+export const PUBLIC_BY_CODE: Readonly<Record<string, PublicCategory>> = {+ worktree_dirty: 'drift', file_drift: 'drift', source_changed: 'drift', pinned_git_worktree_conflict: 'drift',+ concurrent_write: 'conflict', revision_conflict: 'conflict', page_identity_changed: 'conflict',+ invalid_fence: 'content_refused', invalid_frontmatter: 'content_refused', frontmatter_slug_conflict: 'content_refused', rename_held: 'content_refused',+ file_too_large: 'content_refused', content_rejected: 'content_refused', managed_image_sync_unsupported: 'content_refused',+ purged_content: 'content_refused', write_gate_rejected: 'content_refused',+ canonical_file_missing: 'file_missing',+ parser_regression: 'defect', outside_fence: 'defect', preparation_systemic: 'defect', drain_stalled: 'defect',+ cancelled: 'superseded', knock_on: 'superseded', run_replaced: 'superseded', knock_on_exhausted: 'superseded', cursor_incarnation_retired: 'superseded',+ preparation_stalled: 'transient', sync_incomplete: 'transient', connection_lost: 'transient', database_contention: 'transient', write_capacity: 'transient',+ write_capacity_backpressure: 'transient', capacity_paused: 'transient', sync_drain_lease_held: 'transient', graduation_in_progress: 'transient',+ storage_error: 'storage', recovery_required: 'storage',+ permission_denied: 'permission',+ owner_unavailable: 'config', writer_coordinator_required: 'config', write_quota_exhausted: 'config', write_quota_insufficient: 'config', plan_stale: 'config',+ slug_root_mode_mismatch: 'config', invalid_params: 'config',+};++/** A registry code's class, for a code neither table names. */+function byRegistryClass(code: string): PublicCategory {+ const entry = (CODES as Record<string, { class: string; retired_in?: string } | undefined>)[code];+ if (!entry) return 'defect';+ if (entry.retired_in) return 'superseded';+ switch (entry.class) {+ case 'retryable': case 'unavailable': return 'transient';+ case 'consent': case 'host_only': return 'config';+ case 'caller': return 'content_refused';+ default: return 'defect';+ }+}++/**+ * The public category of a verdict (`category` from `classifyTerminal`, when there is one) or of a bare code (a hold, a run+ * stop). A specific terminal category wins; `sync_fault`, `caller_refusal` and no category go by code.+ */+export function publicCategory(input: { category?: TerminalCategory | null; code: string }): PublicCategory {+ const category = input.category ?? null;+ if (category && category !== 'sync_fault' && category !== 'caller_refusal') return PUBLIC_BY_TERMINAL[category];+ return PUBLIC_BY_CODE[input.code] ?? (category === 'caller_refusal' ? (input.code.includes('permission') ? 'permission' : 'content_refused') : byRegistryClass(input.code));+}diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 367c0a7d7a..ed7b5da8cd 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -77,6 +77,9 @@ export interface ManagedSyncWriteDiagnostic {reason: string;message: string;suggestion: string;+ /** #6712 PR 2: a terminal receipt's `classifyTerminal` category and the public category beside it. */+ category?: import('./terminal-classify.ts').TerminalCategory;+ public_category?: import('./public-category.ts').PublicCategory;write_request: WriteReceipt;line_endings?: 'crlf_lf_only';ledger_recorded?: boolean;diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex d7942a6c28..da44544fed 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -38,10 +38,15 @@ import { laneFaultInMessage } from './sync-window.ts';import { cursorFenceCause, syncKnockOnSql } from './sync-knock-on.ts';import { listIncompleteSyncReceipts, type SyncSettledIndexes } from './checkpoint-validation.ts';import { drainEstimate } from './sync-drain.ts';+import { classifyRecordedFault, type TerminalCategory } from './terminal-classify.ts';+import type { PublicCategory } from './public-category.ts';import { resolveManagedSyncContext } from './sync-discovery.ts';export interface SyncStatusHold extends SyncFaultVerdict {code: string;+ /** #6712 PR 2: the `classifyTerminal` category of the hold's code and the public category beside it. */+ category: TerminalCategory;+ public_category: PublicCategory;slug: string | null;path: string;attempts: number;@@ -53,6 +58,9 @@ export interface SyncStatusHold extends SyncFaultVerdict {export interface SyncStatusError extends SyncFaultVerdict {code: string;+ /** #6712 PR 2: the `classifyTerminal` category of the recorded failure and the public category beside it. */+ category: TerminalCategory;+ public_category: PublicCategory;/** A refinement of `code`: a lane fault (`cancelled`), or #6513 the closed `reason` of a database refusal. */detail?: string;message: string;@@ -102,7 +110,7 @@ export type SyncTerminalSummary = { status: 'unknown'; reason: string } | {status: 'ok'; window_days: number; active_blockers: Array<{ kind: 'recovery' | 'checkpoint'; request_id: string; slug?: string; category: string }>;unresolved: { rows: number; distinct_slugs: number; distinct_intents: number; oldest_age_seconds: number | null };historical_rows: number; new_last_24h: number; defects: number;- categories: Array<{ category: string; code: string; origin: string | null; rows: number; unresolved: number }>; drill_down: string[];+ categories: Array<{ category: string; public_category: PublicCategory; code: string; origin: string | null; rows: number; unresolved: number }>; drill_down: string[];};/** #6650: the source's slice of the terminal-failure summary, with PR A's checkpoint blockers passed in rather than recomputed. */@@ -116,7 +124,7 @@ async function terminalSummary(engine: BrainEngine, sourceId: string, blockers:active_blockers: (s?.active_blockers ?? []).map(b => ({ kind: b.kind, request_id: b.request_id, ...(b.slug ? { slug: b.slug } : {}), category: b.category })),unresolved: { rows: s?.unresolved.rows ?? 0, distinct_slugs: s?.unresolved.distinct_slugs ?? 0, distinct_intents: s?.unresolved.distinct_intents ?? 0, oldest_age_seconds: s?.unresolved.oldest_age_seconds ?? null },historical_rows: s?.historical_rows ?? 0, new_last_24h: s?.new_last_24h ?? 0, defects: (s?.defects ?? []).reduce((sum, d) => sum + d.rows, 0),- categories: (s?.categories ?? []).slice(0, 10).map(c => ({ category: c.category, code: c.code, origin: c.origin, rows: c.rows, unresolved: c.unresolved })),+ categories: (s?.categories ?? []).slice(0, 10).map(c => ({ category: c.category, public_category: c.public_category, code: c.code, origin: c.origin, rows: c.rows, unresolved: c.unresolved })),drill_down: ['gbrain', 'sources', 'writer', 'failures', sourceId, '--group-by', 'category', '--json'] };}@@ -167,7 +175,8 @@ function holdVerdict(record: GitHoldRecord, auto: FenceAutoRepair | undefined):function holdStatus(record: GitHoldRecord, auto?: FenceAutoRepair): SyncStatusHold {const attempts = record.meta.attempts ?? 1;const verdict = holdVerdict(record, auto);- return { code: record.code, slug: record.slug, path: record.path, attempts, held_since: record.held_at, ...verdict,+ const terminal = classifyRecordedFault({ source_id: record.source_id, code: record.code, slug: record.slug });+ return { code: record.code, category: terminal.category, public_category: terminal.public_category, slug: record.slug, path: record.path, attempts, held_since: record.held_at, ...verdict,retry_after: verdict.safe_actions[0] === 'retry' || verdict.safe_actions[0] === 'retry_when_clean' ? null : 'after the named step', fix: gitHoldFix(record, auto) };}@@ -196,11 +205,13 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Proconst retired = failure || header ? null : await retiredCursorStands(engine, sourceId, source.incarnation);const repairPreview: Action = { argv: ['gbrain', 'repair', 'managed-sync-orphans', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,why: 'Previews the sync bookkeeping nothing current can resume or clear (an old incarnation\'s cursor and failure rows, stale mirror rows) with the hash its --apply takes; writes nothing.' };- const lastError: SyncStatusError | null = failure ? { code: failure.code, ...(laneFault ? { detail: laneFault } : {}), message: failure.message, ...(failure.write_error_detail ? { write_error_detail: failure.write_error_detail } : {}),+ const recorded = failure ? classifyRecordedFault({ source_id: sourceId, code: failure.code, request_id: failure.request_id, error_detail: failure.write_error_detail ?? null, message: failure.message }) : null;+ const lastError: SyncStatusError | null = failure ? { code: failure.code, category: recorded!.category, public_category: recorded!.public_category,+ ...(laneFault ? { detail: laneFault } : {}), message: failure.message, ...(failure.write_error_detail ? { write_error_detail: failure.write_error_detail } : {}),path: failure.path, phase: failure.phase, first_seen: failure.first_seen, attempts: failure.attempts,...(failure.request_id ? { request_id: failure.request_id } : {}), ...(rootCause ? { root_cause: rootCause } : {}),...classifySyncFault({ code: failure.code, detail: laneFault, message: failure.message }) }- : retired ? { code: 'cursor_incarnation_retired', message: `An unfinished sync cursor of ${sourceId} was recorded under an incarnation the source no longer has; no current sync selects it, and it says nothing about whether the current files are imported. `+ : retired ? { code: 'cursor_incarnation_retired', category: 'sync_fault', public_category: 'superseded', message: `An unfinished sync cursor of ${sourceId} was recorded under an incarnation the source no longer has; no current sync selects it, and it says nothing about whether the current files are imported. `+ `Retire it with ${repairPreview.argv!.join(' ')} (preview, then --apply with the printed hash).`, phase: 'resume', first_seen: retired.first_seen, attempts: 1, ...classifySyncFault({ code: 'cursor_incarnation_retired' }) } : null;const unfinished = !!header && !header.done;const remaining = header ? Math.max(0, Number(header.total) - Number(header.index)) : null;diff --git a/src/core/persistence/sync-write-diagnostic.ts b/src/core/persistence/sync-write-diagnostic.tsindex 5bc1734df7..f76b5f251d 100644--- a/src/core/persistence/sync-write-diagnostic.ts+++ b/src/core/persistence/sync-write-diagnostic.ts@@ -14,6 +14,7 @@ import { writeFailureDiagnostic } from './verb-errors.ts';import { checkpointRetryCommand } from './checkpoint-validation.ts';import { readSyncFile } from './sync-discovery.ts';import { sha256 } from './digest.ts';+import { classifyTerminal } from './terminal-classify.ts';export function managedSyncWriteDiagnostic(cursor: { sourceId: string; root: string; processingOptions?: SyncProcessingOptions; syncOptions: SyncCursorOptions | null },pending: { slug: string; intent: SyncIntent }, row: WriteRequest): ManagedSyncWriteDiagnostic {@@ -26,8 +27,13 @@ export function managedSyncWriteDiagnostic(cursor: { sourceId: string; root: strreason: blockedReason, message: 'The write is accepted but not committed; the sync checkpoint has not advanced.',suggestion: 'Re-run the same sync options to resume this request. Do not submit a replacement request or skip the pending write.',};+ // #6712 PR 2 (L5): a terminal receipt's diagnosis category, and the public one beside it, from the one classifier.+ const verdict = terminal ? classifyTerminal({ request_id: row.request_id, source_id: row.source_id, slug: row.slug, operation: row.operation, state: row.state, error_code: row.error_code,+ error_detail: row.error_detail ?? null, recovery: row.recovery, blocked_reason: row.blocked_reason, compacted: row.compacted, publication_started: row.publication_started,+ error_message: row.error_message, intent_kind: typeof row.intent?.kind === 'string' ? row.intent.kind : null }) : null;const diagnostic: ManagedSyncWriteDiagnostic = { source_id: cursor.sourceId, slug: pending.slug,- path: pending.intent.path, write_error: code, ...detail, write_request: publicWriteReceipt(receiptFor(row)) };+ path: pending.intent.path, write_error: code, ...detail, ...(verdict ? { category: verdict.category, public_category: verdict.public_category } : {}),+ write_request: publicWriteReceipt(receiptFor(row)) };// #6194: an import that lost to a database write the hold could not prove; --retry-failed re-imports the Git version over it.if (terminal && code === 'revision_conflict' && pending.intent.kind === 'managed_sync_import') diagnostic.suggestion = `The page changed in the database after this import was frozen. `+ `Before retrying, compare the file and the page with gbrain sources reconcile ${cursor.sourceId} ${pending.slug} --preview (it writes nothing): a retry re-imports the Git version over the database one. ${diagnostic.suggestion}`;diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.tsindex f8cc46b1d7..507cb4ce7d 100644--- a/src/core/persistence/terminal-classify.ts+++ b/src/core/persistence/terminal-classify.ts@@ -24,6 +24,7 @@ import { compareVersions } from '../migration-ledger.ts';import { classifySyncFault, SYNC_FAULT_TABLE, type SyncFaultClass, type SyncSafeAction } from './sync-fault-class.ts';import { isSyncKnockOn, knockOnRoot, SYNC_CURSOR_FENCE_ORIGIN, SYNC_KNOCK_ON_ORIGIN, cursorFenceCause, syncKnockOnSql } from './sync-knock-on.ts';import { writeFailureDiagnostic } from './verb-errors.ts';+import { publicCategory, type PublicCategory } from './public-category.ts';export type TerminalCategory =| 'recovery_pending' | 'recovery_blocked'@@ -56,6 +57,8 @@ export interface TerminalInput {export interface TerminalVerdict {category: TerminalCategory;+ /** #6712 PR 2: the closed public vocabulary beside `category` (`public-category.ts`); total. */+ public_category: PublicCategory;/** The code the verdict is keyed on: the row's `error_code`, or the refinement its origin names. */code: string;origin: string | null;@@ -120,7 +123,7 @@ function stringField(detail: Record<string, unknown> | null | undefined, key: streturn typeof value === 'string' ? value : null;}-type Partial_ = Omit<TerminalVerdict, 'defect' | 'fixed_in' | 'historical' | 'escalate'> & { escalate?: string };+type Partial_ = Omit<TerminalVerdict, 'defect' | 'fixed_in' | 'historical' | 'escalate' | 'public_category'> & { escalate?: string };/** The read-time verdict for one terminal receipt that did not commit; null for a committed receipt with no recovery record. */export function classifyTerminal(input: TerminalInput): TerminalVerdict | null {@@ -129,7 +132,7 @@ export function classifyTerminal(input: TerminalInput): TerminalVerdict | null {const fixedIn = (TERMINAL_FIXED_IN as Partial<Record<TerminalCategory, string>>)[verdict.category] ?? null;const ran = build(input);const historical = fixedIn !== null && (verdict.category === 'legacy_publication_refusal' || (ran !== null && compareVersions(ran, fixedIn) < 0));- return { ...verdict, escalate: verdict.escalate ?? escalateOf(verdict.code), defect: DEFECTS.has(verdict.category), fixed_in: fixedIn, historical };+ return { ...verdict, public_category: publicCategory(verdict), escalate: verdict.escalate ?? escalateOf(verdict.code), defect: DEFECTS.has(verdict.category), fixed_in: fixedIn, historical };}function fromTable(category: TerminalCategory, code: string, origin: string | null, action: Action, detail?: string | null, message?: string | null): Partial_ {@@ -326,3 +329,15 @@ export function dispositionOf(later: { state: string; same_intent: boolean } | nif (later.same_intent) return 'duplicate';return 'superseded';}++/**+ * #6712 PR 2 (L5): the verdict of a fault recorded without its receipt at hand (a hold, a managed-sync failure row, a run+ * stop), read as the failed receipt it stands for, so `last_error`, holds and doctor's `sync_failures` render the same+ * `category` / `public_category` as the receipt itself.+ */+export function classifyRecordedFault(input: { source_id: string; code: string; slug?: string | null; request_id?: string | null;+ error_detail?: Record<string, unknown> | null; message?: string | null }): TerminalVerdict {+ return classifyTerminal({ source_id: input.source_id, slug: input.slug ?? '', operation: 'submit_job', state: 'failed', error_code: input.code,+ error_detail: input.error_detail ?? null, recovery: null, blocked_reason: null, compacted: false, error_message: input.message ?? null,+ ...(input.request_id ? { request_id: input.request_id } : {}) })!;+}diff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.tsindex 44577879e4..65c796ea6f 100644--- a/src/core/persistence/terminal-failures.ts+++ b/src/core/persistence/terminal-failures.ts@@ -24,6 +24,7 @@ import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';import { isStatementTimeout } from './bounded-reads.ts';import { readReceiptRetentionDays, DEFAULT_RECEIPT_RETENTION_DAYS } from './limits.ts';+import type { PublicCategory } from './public-category.ts';import { classifyTerminal, dispositionOf, TERMINAL_FIXED_IN, supersessionOrderSql, supersessionSql, terminalInspectArgv, terminalKnockOnSql, type TerminalCategory,type TerminalDisposition, type TerminalVerdict, CONNECTION_MESSAGE_PATTERN, LEGACY_PUBLICATION_PREFIX } from './terminal-classify.ts';@@ -113,7 +114,7 @@ export interface TerminalSourceSummary {new_last_24h_older_builds: { rows: number; builds: string[] };daily_7d: number[];defects: Array<{ category: TerminalCategory; code: string; origin: string | null; rows: number; human_reason?: string; action: Action }>;- categories: Array<{ category: TerminalCategory; code: string; origin: string | null; rows: number; unresolved: number; historical: number; class: string; needs_human: boolean }>;+ categories: Array<{ category: TerminalCategory; public_category: PublicCategory; code: string; origin: string | null; rows: number; unresolved: number; historical: number; class: string; needs_human: boolean }>;}export type TerminalSummary = { status: 'ok'; window_days: number; window_clamped: boolean; retention_days: number; sources: TerminalSourceSummary[] } | { status: 'unknown'; window_days: number; reason: string };@@ -201,7 +202,7 @@ export async function readTerminalFailureSummary(engine: BrainEngine, opts: { so}const cat = s.categories.find(c => c.category === verdict.category && c.code === verdict.code && c.origin === verdict.origin);if (cat) { cat.rows += n; cat.unresolved += unresolved ? n : 0; cat.historical += historical ? n : 0; }- else s.categories.push({ category: verdict.category, code: verdict.code, origin: verdict.origin, rows: n, unresolved: unresolved ? n : 0, historical: historical ? n : 0,+ else s.categories.push({ category: verdict.category, public_category: verdict.public_category, code: verdict.code, origin: verdict.origin, rows: n, unresolved: unresolved ? n : 0, historical: historical ? n : 0,class: verdict.class, needs_human: verdict.needs_human });}for (const [sourceId, blockers] of opts.checkpointBlockers ?? []) {@@ -255,12 +256,12 @@ export interface TerminalFailureQuery {category?: string;}export interface TerminalFailureRow {- request_id: string; slug: string; operation: string; state: string; code: string; origin: string | null; category: TerminalCategory;+ request_id: string; slug: string; operation: string; state: string; code: string; origin: string | null; category: TerminalCategory; public_category: PublicCategory;class: string; safe_actions: string[]; needs_human: boolean; human_reason?: string; disposition: TerminalDisposition; blocking: boolean; historical: boolean;compacted: boolean; ended_at: string; cursor: string; inspect: Action; fix: Action; root_request_id?: string;}export interface TerminalFailureGroup {- code: string; origin: string | null; category: TerminalCategory; rows: number; class: string; needs_human: boolean; human_reason?: string;+ code: string; origin: string | null; category: TerminalCategory; public_category: PublicCategory; rows: number; class: string; needs_human: boolean; human_reason?: string;filter: { code: string; origin: string | null; category: TerminalCategory }; drill_down: string[]; fix: Action; samples: Array<Pick<TerminalFailureRow, 'request_id' | 'slug' | 'state' | 'ended_at' | 'inspect'>>;}export type TerminalFailureListing = {@@ -314,7 +315,7 @@ export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailuconst historical = !row.has_recovery && (disposition !== 'unknown' || v.historical);const matches = (!q.category || v.category === q.category) && (!q.code || v.code === q.code)&& (q.origin === undefined || (v.origin ?? NO_ORIGIN) === q.origin) && (state === 'all' || !historical);- if (matches) out.push({ request_id: row.request_id, slug: row.slug, operation: row.operation, state: row.state, code: v.code, origin: v.origin, category: v.category, class: v.class,+ if (matches) out.push({ request_id: row.request_id, slug: row.slug, operation: row.operation, state: row.state, code: v.code, origin: v.origin, category: v.category, public_category: v.public_category, class: v.class,safe_actions: v.safe_actions, needs_human: v.needs_human, ...(v.human_reason ? { human_reason: v.human_reason } : {}), disposition, blocking: row.has_recovery, historical,compacted: row.compacted, ended_at: row.ended_at, cursor: row.sequence, ...(v.root_request_id ? { root_request_id: v.root_request_id } : {}),inspect: { argv: terminalInspectArgv(row.request_id), consent: [], actor: 'agent', requires_exclusive: false, why: 'The receipt with its diagnosis and structured fix, read-only.' },@@ -336,7 +337,7 @@ export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailulet g = groups.get(key);if (!g) {const filter = { code: row.code, origin: row.origin, category: row.category };- groups.set(key, g = { code: row.code, origin: row.origin, category: row.category, rows: 0, class: row.class, needs_human: row.needs_human,+ groups.set(key, g = { code: row.code, origin: row.origin, category: row.category, public_category: row.public_category, rows: 0, class: row.class, needs_human: row.needs_human,...(row.human_reason ? { human_reason: row.human_reason } : {}), filter, fix: row.fix, samples: [],drill_down: terminalFailuresArgv({ sourceId: q.sourceId, state: q.state, sinceDays: q.sinceDays, category: row.category, code: row.code, origin: row.origin ?? NO_ORIGIN }) });}diff --git a/test/public-category.test.ts b/test/public-category.test.tsnew file mode 100644index 0000000000..87afbead07--- /dev/null+++ b/test/public-category.test.ts@@ -0,0 +1,46 @@+/**+ * #6712 PR 2 (L5): `public_category` is a closed public vocabulary beside the unchanged `category`. The mapping is total:+ * every terminal category, every fault-table code and every registry code maps into it, and the receipt, the hold, the+ * last error and doctor's failures all read it from the one classifier (`classifyTerminal`).+ */+import { describe, expect, test } from 'bun:test';+import { CODES } from '../src/core/error-registry.ts';+import { PUBLIC_BY_CODE, PUBLIC_BY_TERMINAL, PUBLIC_CATEGORIES, publicCategory } from '../src/core/persistence/public-category.ts';+import { SYNC_FAULT_TABLE } from '../src/core/persistence/sync-fault-class.ts';+import { classifyRecordedFault, classifyTerminal } from '../src/core/persistence/terminal-classify.ts';++const allowed = new Set<string>(PUBLIC_CATEGORIES);++describe('public_category', () => {+ test('the vocabulary is the ten named categories', () => {+ expect([...PUBLIC_CATEGORIES]).toEqual(['drift', 'conflict', 'content_refused', 'file_missing', 'permission', 'storage', 'config', 'superseded', 'transient', 'defect']);+ });++ test('every fault-table code has its own row (no fault code falls through to the registry class)', () => {+ const missing = SYNC_FAULT_TABLE.map(rule => rule.code).filter(code => !(code in PUBLIC_BY_CODE));+ expect(missing).toEqual([]);+ for (const value of Object.values(PUBLIC_BY_CODE)) expect(allowed.has(value)).toBe(true);+ for (const value of Object.values(PUBLIC_BY_TERMINAL)) expect(allowed.has(value)).toBe(true);+ });++ test('every registry code, and a code this build does not know, maps into the vocabulary', () => {+ for (const code of [...Object.keys(CODES), 'a_code_from_the_future']) expect(allowed.has(publicCategory({ code }))).toBe(true);+ expect(publicCategory({ code: 'a_code_from_the_future' })).toBe('defect');+ expect(publicCategory({ code: 'knock_on_exhausted' })).toBe('superseded');+ });++ test('a specific terminal category decides; sync faults go by code', () => {+ expect(publicCategory({ category: 'canonical_file_missing', code: 'source_changed' })).toBe('file_missing');+ expect(publicCategory({ category: 'sync_fault', code: 'worktree_dirty' })).toBe('drift');+ expect(publicCategory({ category: 'caller_refusal', code: 'permission_denied' })).toBe('permission');+ });++ test('classifyTerminal carries public_category beside the unchanged category, on receipts and on recorded faults', () => {+ const receipt = classifyTerminal({ source_id: 's', slug: 'notes/a', operation: 'submit_job', state: 'failed', error_code: 'source_changed', error_detail: { reason: 'canonical_file_missing' },+ recovery: null, blocked_reason: null, compacted: false })!;+ expect(receipt).toMatchObject({ category: 'canonical_file_missing', public_category: 'file_missing' });+ expect(classifyRecordedFault({ source_id: 's', code: 'file_drift' })).toMatchObject({ category: 'sync_fault', public_category: 'drift' });+ expect(classifyRecordedFault({ source_id: 's', code: 'connection_lost' }).public_category).toBe('transient');+ expect(classifyRecordedFault({ source_id: 's', code: 'concurrent_write' }).public_category).toBe('conflict');+ });+});