/** * Decision ask ledger — append-only call record for `aiwg decision ask`. * * Extends the existing decision CLI surface (#2946) rather than adding a new * subsystem: the ledger is one JSON-lines file under the project AIWG * artifact root (`.aiwg/decision/ledger.jsonl`, resolved the same way as * `aiwg artifacts path`). * * Writing the ledger is intentionally decoupled from `askDecision()` itself * (`./ask.js`): `recordDecisionAsk` is a small wrapper the CLI `ask` handler * and the MCP `decision-ask` tool both call after they already have a * `DecisionAskResult`, tagged with their transport. This keeps `askDecision` * free of I/O and keeps internal reuse (e.g. `setupJev`'s `--verify` probe) * out of the ledger: only completed `ask` calls — `answered` or `fallback` — * are recorded. CLI/MCP usage errors (bad flags, oversized context) never * reach a `DecisionAskResult` and are never recorded. * * Trust boundary (review r1/r2 #2946): this file defends against an * ACCIDENTAL hazard — a stray symlink, a hard link, loose permissions left * by another tool, a previous crash's partial write — all under the * assumption that the artifact root is owned and written by the SAME local * user running `aiwg`, or its stat-verified shared workspace group. It does not and cannot defend against a HOSTILE * process running as that same user: such a process already has read/write * access to everything the ledger could protect. Appenders, rotation and * readers share the existing cross-process directory-lock helper. There is * no privilege boundary here. Every filesystem * check below uses only portable Node primitives (no `/proc`, no handle * anchoring): `mkdir`/`lstat` for the directory, `open`+`fstat` for the * file, with `O_NOFOLLOW` applied when the platform defines it (POSIX; not * Windows). On a POSIX platform a small TOCTOU window exists between the * directory `lstat` and the file `open`; on Windows the symlink check is a * plain `lstat` pre-check with no kernel-enforced equivalent to * `O_NOFOLLOW`. Both are accepted given the trust boundary above. An * existing file or directory that fails a safety check is never modified — * recording is skipped and reported once via `warn`, never "fixed" by * chmod or truncation. * * Record size is capped at a level that stays below the conservative * single-write atomicity boundary most platforms also honor for `PIPE_BUF` * (4096 bytes on Linux): this makes a single, non-interleaved write the * overwhelmingly likely outcome for one record, but it is not a guarantee. * The lock covers opening, checking the trailing newline, writing every * byte and closing. Rotation holds that same lock through live-file * replacement. `history`/`stats` count malformed lines as skipped; retention * preserves their original bytes. * * Recording — attribution resolution and the write — is bounded by a short * deadline (`DECISION_LEDGER_RECORD_TIMEOUT_MS`). On timeout, the in-flight * attempt is not cancelled (Node has no way to abort an in-flight `open`), * so its outcome is genuinely unknown: the record may or may not eventually * land. The warning says exactly that ("completion unknown"), and no * attribution-to-append stage starts once the deadline has fired. An append * already waiting for the ledger lock can still complete after that deadline. */ import { type FileHandle } from 'node:fs/promises'; import { type ProviderResolution } from '../cli/provider-resolution.js'; import type { DecisionAskInput, DecisionAskResult } from './ask.js'; import { type DecisionSavingsMethod, type DecisionSavingsWeights } from './savings.js'; export declare const DECISION_LEDGER_SCHEMA = "aiwg-decision-ledger-record/v2"; export declare const DECISION_LEDGER_SCHEMA_V1 = "aiwg-decision-ledger-record/v1"; export type DecisionLedgerTransport = 'cli' | 'mcp'; export type DecisionLedgerKind = 'yes-no' | 'choices' | 'scale'; export interface DecisionLedgerRecord { schema: typeof DECISION_LEDGER_SCHEMA | typeof DECISION_LEDGER_SCHEMA_V1; id: string; timestamp: string; transport: DecisionLedgerTransport; provider: string; sessionId: string; sessionSource?: string; projectRoot: string; decisionKind: DecisionLedgerKind; choiceIds: string[] | null; /** Index of the selected option within the caller's full (un-truncated) choice/scale list, or null (yes-no, or no match). */ answerIndex: number | null; /** Total choice/scale option count before the MAX_RECORDED_CHOICE_IDS cap; null for yes-no. */ choiceCount: number | null; /** True when `choiceIds` is a truncated prefix of the full list (choiceCount > MAX_RECORDED_CHOICE_IDS). */ choiceIdsTruncated: boolean; questionDigest: string; contextDigest: string | null; questionText?: string; contextText?: string; /** Present (and true) only when `--record-text` truncated a text field to fit the record-size cap. */ textTruncated?: boolean; status: DecisionAskResult['status']; answer: DecisionAskResult['answer']; confidence: DecisionAskResult['confidence']; answeredBy?: DecisionAskResult['answeredBy']; threshold: number; fallbackReason: string | null; model: DecisionAskResult['model']; usage: DecisionAskResult['usage']; latencyMs: number; passesRequested?: number; escalationPasses?: number; passesRun?: number; escalated?: boolean; earlyStop?: 'certain-failure' | 'timeout' | null; agreementRatio?: number; minAgreement?: number | null; agreementConfidenceFloor?: number; passConfidenceSummary?: NonNullable['confidenceSummary']; estimatedLlmTokensAvoided: number; /** Legacy v1 figure above is retained for comparison only. */ estimationMethodV1?: string; llm_tokens_avoided?: number; jev_tokens?: number; cost_weighted_net_usd?: number; estimationMethod: string | DecisionSavingsMethod; caller: string | null; } /** * Legacy v1 per-kind allowance, retained only for comparison and replay. * Named and recorded with * every estimate (not just referenced) so the figure can be recomputed * later per the issue's proposal item 3. */ export declare const DECISION_SAVINGS_REASONING_ALLOWANCE_TOKENS: Readonly>; export declare const DECISION_SAVINGS_ESTIMATION_METHOD: string; export declare const MAX_ATTRIBUTION_FIELD_LENGTH = 96; export declare const ATTRIBUTION_FIELD_PATTERN: RegExp; /** The ledger records at most this many choice ids, regardless of how many the `ask` call itself allowed (up to 255); see `choiceCount`/`choiceIdsTruncated`. */ export declare const MAX_RECORDED_CHOICE_IDS = 10; /** Post-redaction, post-truncation cap per opt-in text field (`--record-text`). */ export declare const MAX_RECORD_TEXT_BYTES = 600; /** * Hard cap on one serialized record line. Kept below 4096 (`PIPE_BUF` on * Linux) as a conservative single-write-atomicity margin — see the module * doc comment. Not a guarantee: see the module doc comment on concurrent * writers. */ export declare const MAX_LEDGER_RECORD_BYTES = 4000; /** Bounds how long `recordDecisionAsk` waits on attribution resolution and the write. On timeout the outcome is reported as unknown, not "abandoned" — see the module doc comment. */ export declare const DECISION_LEDGER_RECORD_TIMEOUT_MS = 250; /** Ordered harness session markers; never substitute provider/process ids. */ export declare const DECISION_SESSION_ENV_VARS: readonly ["AIWG_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CODEX_THREAD_ID", "CODEX_SESSION_ID", "HERMES_SESSION_ID", "OPENCODE_SESSION_ID", "MUSE_SESSION_ID", "GROK_SESSION_ID", "WARP_SESSION_ID"]; export declare function resolveDecisionSession(explicitSessionId: string | undefined, env: NodeJS.ProcessEnv): { sessionId: string; sessionSource: string; }; export declare function resolveDecisionSessionId(explicitSessionId: string | undefined, env: NodeJS.ProcessEnv): string; export interface DecisionLedgerBuildContext { transport: DecisionLedgerTransport; provider: string; sessionId: string; sessionSource?: string; savingsWeights?: DecisionSavingsWeights; /** Project root; stored (redacted) as the record's own `projectRoot` field. */ projectRoot: string; caller?: string | null; /** Opt-in: include redacted, length-capped question/context text. Never on by default. */ recordText?: boolean; /** Injectable clock for tests. */ now?: () => number; /** Injectable id generator for tests. */ id?: () => string; } /** Pure, synchronous and side-effect free: builds the record this call would append, fully sanitized. */ export declare function buildDecisionLedgerRecord(input: DecisionAskInput, result: DecisionAskResult, context: DecisionLedgerBuildContext): DecisionLedgerRecord; export type LedgerWriteChunk = (handle: FileHandle, buffer: Buffer) => Promise; export interface AppendDecisionLedgerOptions { projectRoot: string; warn?: (message: string) => void; /** Test-only: override the low-level write primitive to simulate short writes. */ writeChunk?: LedgerWriteChunk; } /** * Best-effort append. A failure here must never change the decision result * or exit code — every failure is caught and reported through `warn` (at * most once; see `makeOnceWarn`), never thrown. Returns `true` once the * record is durably appended, `false` on a handled (warned) failure. */ export declare function appendDecisionLedgerRecord(record: DecisionLedgerRecord, options: AppendDecisionLedgerOptions): Promise; export interface RotateDecisionLedgerOptions { projectRoot: string; /** Activity-log syntax: positive entry count or duration in days. Default: 90d. */ keepLast?: string; /** Explicit authorization to archive everything, including malformed lines. */ all?: boolean; /** Artifact-relative or absolute .jsonl path beneath archive/decision/. */ to?: string; now?: () => number; } export declare function parseDecisionLedgerRetention(keepLast?: string, all?: boolean): { count?: number; ms?: number; }; /** Retention preserves each raw line, including invalid UTF-8, CRLF and an unterminated final line. */ export declare function rotateDecisionLedger(options: RotateDecisionLedgerOptions): Promise<{ archived: number; retained: number; malformed: number; archivePath: string | null; }>; export interface RecordDecisionAskOptions { transport: DecisionLedgerTransport; /** Project root; used both to resolve the ledger location and to resolve the active provider. */ projectRoot: string; env?: NodeJS.ProcessEnv; /** `--provider` override. */ explicitProvider?: string; /** `--session` override; both transports also resolve harness environment ids. */ explicitSessionId?: string; /** Pre-validated attribution tag; an invalid shape is coerced to `null` defensively. */ caller?: string | null; recordText?: boolean; now?: () => number; id?: () => string; warn?: (message: string) => void; /** Overrides `DECISION_LEDGER_RECORD_TIMEOUT_MS`; test-only. */ timeoutMs?: number; /** Test injection point for provider resolution; defaults to `resolveActiveProvider`. */ resolveProvider?: (options: { cwd: string; explicitProvider?: string; env?: NodeJS.ProcessEnv; }) => Promise; /** Test-only: forwarded to `appendDecisionLedgerRecord` to simulate short writes. */ writeChunk?: LedgerWriteChunk; } /** * Build and append exactly one ledger record for one `askDecision()` call. * Called by the CLI `ask` handler and the MCP `decision-ask` tool — the * "same function" referenced in the issue's MCP-parity requirement — each * tagging its own `transport`. Attribution resolution (provider/session) and * the write both happen inside this one bounded step: never throws, warns at * most once, and never waits longer than `timeoutMs` (default * `DECISION_LEDGER_RECORD_TIMEOUT_MS`) before returning `null` to the * caller. The in-flight attempt itself is not cancelled on timeout (Node * cannot abort an in-flight filesystem call); its own later stages simply * never start (checked via a cancellation flag before each one), and its * eventual settlement — successful or not — is swallowed rather than * reported. The caller's own decision result and exit code are therefore * always untouched, whether this returns the appended record or `null`. */ export declare function recordDecisionAsk(input: DecisionAskInput, result: DecisionAskResult, options: RecordDecisionAskOptions): Promise; export interface DecisionLedgerFilters { includeArchives?: boolean; since?: Date; provider?: string; sessionId?: string; kind?: DecisionLedgerKind; status?: DecisionAskResult['status']; /** Exact caller-tag match (`--caller `). Mutually exclusive with `callerPrefix`/`noCaller`. */ caller?: string; /** Prefix match: `--caller '*'` with the trailing `*` stripped. Mutually exclusive with `caller`/`noCaller`. */ callerPrefix?: string; /** Select only records with no caller tag (`--no-caller`). Mutually exclusive with `caller`/`callerPrefix`. */ noCaller?: boolean; } /** Exposed for direct unit testing; `decisionLedgerHistory`/`decisionLedgerStats` apply this per streamed record instead. */ export declare function filterDecisionLedgerRecords(records: readonly DecisionLedgerRecord[], filters: DecisionLedgerFilters): DecisionLedgerRecord[]; export interface DecisionLedgerHistoryResult { schema: 'aiwg-decision-ledger-history/v1'; count: number; /** Lines that failed JSON parsing or record validation and were excluded. */ skipped: number; records: DecisionLedgerRecord[]; /** The filters applied to produce this result, so a `--json` consumer can see what was selected. */ filters: DecisionLedgerFilters; } /** Reads, validates and filters the ledger offline, streaming line-by-line; no network, no Jev call. Tolerates a missing ledger file (empty result). */ export declare function decisionLedgerHistory(projectRoot: string, filters?: DecisionLedgerFilters): Promise; export type DecisionLedgerGroupBy = 'provider' | 'session' | 'kind' | 'caller' | 'passes' | 'escalation'; export interface DecisionLedgerStatsFilters extends DecisionLedgerFilters { groupBy?: DecisionLedgerGroupBy; } export interface DecisionLedgerStatsGroup { llm_tokens_avoided: number; jev_tokens: number; cost_weighted_net_usd: number; /** v1 inputs recovered from the legacy credit, using the current config. */ legacyReestimatedCalls: number; ratesUsed: Array<{ calls: number; method: Omit; }>; /** `null` only for the caller group when no record in the group carries a `--caller` tag — distinct from the literal string "unattributed". */ key: string | null; totalCalls: number; answered: number; fallback: number; /** Fraction of this group's calls that fell back; denominator is `totalCalls`. */ fallbackRate: number; hitRate: number; agreement: { count: number; mean: number | null; }; escalatedCalls: number; passesRun: number; /** Raw per-reason fallback counts. */ fallbackCountByReason: Record; /** Per-reason fallback counts as a fraction of `totalCalls` (same denominator as `fallbackRate`). */ fallbackRateByReason: Record; confidence: { count: number; mean: number | null; min: number | null; max: number | null; }; jevUsage: { inputTokens: number; outputTokens: number; }; /** All recorded Jev tokens, including fallbacks, divided by answered calls; null with no answers. */ tokensPerAnsweredDecision: number | null; estimatedLlmTokensAvoidedTotal: number; /** * `estimatedLlmTokensAvoidedTotal` minus the Jev usage actually spent on * ANSWERED calls only: each fallback record's own estimate already * subtracts that call's Jev usage, so re-subtracting all usage here would * double-count it. */ netSavingsTokens: number; } export interface DecisionLedgerStatsResult { schema: 'aiwg-decision-ledger-stats/v1'; groupBy: DecisionLedgerGroupBy | null; skipped: number; groups: DecisionLedgerStatsGroup[]; /** The filters applied to produce this result, so a `--json` consumer can see what was selected. */ filters: DecisionLedgerStatsFilters; /** Applied only to v1 records; v2 records retain their recorded weights. */ legacyEstimationWeights: DecisionSavingsWeights; } /** Reads, validates, filters and aggregates the ledger offline, streaming line-by-line with incremental min/max; no network, no Jev call. Tolerates a missing ledger file (empty result). */ export declare function decisionLedgerStats(projectRoot: string, filters?: DecisionLedgerStatsFilters): Promise; export declare class DecisionLedgerSinceError extends Error { constructor(message: string); } /** Strict `--since` parser: bare `YYYY-MM-DD` and offsetless timestamps are UTC; invalid calendar dates are rejected regardless of whether an offset is present. */ export declare function parseDecisionLedgerSince(raw: string): Date; //# sourceMappingURL=ledger.d.ts.map