Safety decisions, explanations, and audit trail
The decision and audit system turns command analysis into a safety outcome, a clear explanation, and a short-lived record of what happened. It keeps enforcement separate from diagnostics so a missing trace or a log write problem does not change the command decision. See Command safety evaluation, Command parsing, Semantic command analysis and guards, and Programmatic safety API for the related command flow and integration surfaces.
Evaluation outcomes
The evaluation engine answers whether a command can proceed and, when it cannot, gives the reason and the command evidence that caused the block. The result is shared by runtime guards and read-only diagnostic surfaces.
Decision evidence and intent
A safety decision is either allow or deny. A denial carries a human-readable reason, an optional rule ID, the matched command or segment, and a block intent that tells an integration how the user should respond.
The intent is part of the user contract rather than a second decision. It distinguishes a hard stop from a safer alternative, a narrower scope, manual approval, or a command that must be simplified before analysis can continue.
| Decision data | Purpose |
|---|---|
| Result | States whether the command may proceed. |
| Reason | Explains the safety concern in user terms. |
| Evidence | Identifies the command and the blocked segment. |
| Rule ID | Connects the result to a built-in or custom rule. |
| Block intent | Guides the next safe action. |
References: src/…/decision.ts• L1-22 src/…/format.ts• L17-63
Fail-closed records
When analysis cannot safely complete, the runtime reports a failed-closed denial instead of treating the command as safe. The audit record keeps the evaluation stage and a small error category so an engineer can tell an analysis limit from a normal dangerous-command match.
The runtime writes the diagnostic before it rethrows the evaluation error. This preserves a record of the safety failure while keeping the failure visible to the integration that requested the evaluation.
| Failure field | Meaning |
|---|---|
failureStage | Guard stage where the unexpected failure occurred. |
errorCode | Bounded category such as an input, path, or syntax limit. |
configFallback | The decision used a fallback policy rather than the configured policy. |
References: src/…/runtime.ts• L47-97 src/…/audit.ts• L4-18 src/…/denial.ts• L42-60
Diagnostic traces
The command trace records how the evaluator reached its outcome. It is passive: the evaluator emits trace steps while the same analysis path makes the decision, but the trace is never consulted to allow or block a command.
Trace scope and terminal state
src/…/evaluate-command.ts is the main traced evaluation path. It records the parsed command as a global step, then groups analysis steps by command segment. A terminal value states allowed or blocked and includes the block reason and evidence when needed.
The trace can show transformations and checks such as environment removal, wrapper or interpreter descent, rule checks, fallback scans, custom-rule checks, and skipped segments after an earlier block. This gives a reader the path through the analysis without exposing the evaluator's internal control flow as a second source of truth.
The recorder bounds event count, text size, list size, object size, and nesting depth. Events beyond the event limit or events that cannot be sanitized are omitted. A completed trace is frozen so later evaluation work cannot change the diagnostic record.
References: src/…/evaluate-command.ts• L17-61 src/…/trace.ts• L8-72 src/…/trace.ts• L107-167 src/…/trace.ts• L315-320
Secret sanitization
Diagnostic text is sanitized before it can reach a trace, a user-facing explanation, or an audit field that the writer handles. Sanitization covers assignment values, database connection values, credentials in URLs, authorization and cookie headers, private keys, signed query values, provider tokens, JWTs, and cloud access-key IDs.
Trace sanitization also finds secret values in environment assignments and remembers safe fingerprints of those values. It shares those fingerprints with evaluation branches, so a value found in one reading stays redacted if a later reading emits it in a derived event. It can then redact the same value if a parser emits it again in a derived event. All trace text is bounded after redaction, and object traversal stops at configured limits or cycles.
The audit writer applies redaction to the command, segment, tool name, and working directory before it caps them or derives the log path. It also turns a session ID into a safe filename component and accepts an audit home only when it is an absolute path. The persisted reason and metadata fields are not passed through this field redactor, so reason producers must keep those fields safe.
References: src/…/sanitize.ts• L25-86 src/…/sanitize.ts• L88-154 src/…/trace.ts• L159-303 src/…/writer.ts• L21-43 src/…/writer.ts• L67-92 src/…/redaction.ts• L24-80
User-facing explanations
The explain service runs the same policy-aware evaluation without executing the command. It combines the result with the trace, the active policy view, and any custom-rule metadata so an engineer can understand both the outcome and the policy context.
Explain result
explainCommand returns an allowed or blocked result. A blocked result includes sanitized reason, segment, and rule data. The result also reports the policy source and validity, the selected safety preset, effective capabilities, rule customizations, and a mode-gated rule activation when one affects the candidate command. Custom-rule metadata is sanitized before it is returned.
The service checks protections that must run before ordinary command analysis. These checks cover changes to safety policy, policy-apply requests, protected Git metadata, and sensitive targets. It then evaluates the command with the passive trace. An empty command returns an error step but remains an allowed result because there is no command to execute.
When the explanation reads configuration from disk, it reports the project rules file before the user rules file. A project file can therefore be the reported source even when the user file also exists. A temporary policy snapshot can still supply the policy used for a preview.
This flow is useful for policy editors because the GUI can create a temporary policy snapshot and ask the same service what that draft would do. It does not write an audit entry merely because a command was explained.
References: src/…/explain.ts• L44-134 src/…/explain.ts• L151-191 src/…/explain.ts• L197-325 src/…/explain.ts• L13-45 src/…/index.ts• L573-600
Explanation surfaces
The CLI exposes cc-safety-net explain <command>. Human output presents the input, segment boundaries, visible analysis steps, result, reason, and policy summary. JSON output returns the structured explain result for tools and other interfaces.
The same result can be rendered by the GUI policy preview. Runtime denials use a shorter blocked message that includes the reason and safe next-action text based on the block intent. These surfaces sanitize command evidence before display and cap ordinary command excerpts in the integration message.
This diagram shows how one policy-aware evaluation supplies both detailed explanations and short runtime messages.
flowchart LR
A[Command] --> B[Policy-aware evaluation]
B --> C[Decision]
B --> D[Passive trace]
C --> E[CLI or GUI explanation]
D --> E
C --> F[Integration denial message]
References: src/…/explain.ts• L3-27 src/…/run.ts• L27-58 src/…/format.ts• L15-229 src/…/format.ts• L17-68
Audit trail
The audit trail preserves decisions made by integrations so users can review blocks, repeated attempts, policy context, and failed-closed events after the original request ends. It is local history for diagnosis, not a replacement for the live enforcement result.
Audit record creation
Runtime integrations project guard results into an audit descriptor. Denials are recorded with their evidence and rule context. Allowed command-route evaluations are recorded only when the guard enables allowed-command auditing; allowed non-command requests are not written through this path.
Each entry has a timestamp, random ID, session, decision, command, segment, reason, and optional agent, tool, policy level, rule, intent, and failure data. Entries use JSON Lines files below ~/.cc-safety-net/logs/<encoded-cwd>/<YYYY-MM>/. The audit home can be redirected by the CC_SAFETY_NET_AUDIT_HOME setting, and invalid session IDs do not create a file.
The writer redacts and bounds the command, segment, tool, and working-directory fields before it writes an entry. It marks an entry as truncated when a cap applies. Failure-stage entries keep the full command because they are the diagnostic of record for a failed-closed event; upstream input limits still bound that path. A write or cleanup error is ignored so it cannot change the live decision.
This diagram shows the separation between the live decision and the best-effort local history write.
sequenceDiagram
participant I as Integration
participant G as Guard evaluation
participant A as Audit projection
participant L as Local audit history
I->>G: Request command decision
G-->>A: Decision and context
A->>L: Redacted JSONL entry
L-->>A: Retention sweep after append
G-->>I: Allow or denial
References: src/…/audit.ts• L30-136 src/…/writer.ts• L45-128 src/…/audit.ts• L17-39
Audit scans and activity views
The audit reader walks the current nested layout and legacy root-level JSONL files. It recursively collects JSONL files, parses valid lines, and counts unreadable files, directories, and malformed records as skipped sources. A missing audit directory means empty history. A non-zero skip count means the answer is partial.
The reader accepts a record only when its timestamp and command fields are strings and its supported optional fields have string values when present. Invalid JSON lines and records with the wrong shape are skipped and increase the same partial-result count. This lets callers show usable records while stating that the view may not contain the full history.
The CLI logs command normally shows denials in a time window. It can include allows, filter by agent, rule, session, or project, look up one entry by ID, return JSON, or select suspect denials. Suspect mode marks failed-closed entries and repeated denials with the same session and command signature. A command signature uses the executable and, when present, a simple subcommand while ignoring leading environment assignments. Repeats are counted across the full matched window before the output limit is applied.
The GUI activity feed uses the same scan and reports counts, daily totals, rule and command summaries, unreadable sources, and a newest-first entry list capped at 500. Doctor uses the same history for a small recent-block summary. Relative time labels make recent blocks easy to scan, while suspect entries identify failed evaluations and repeated denials. These views report scan gaps instead of presenting surviving entries as complete history.
This diagram shows how the shared reader feeds operator, GUI, and health views while keeping partial results visible.
flowchart TD
A[Audit files] --> B[Recursive reader]
B --> C[Valid entries and skipped-source count]
C --> D[CLI logs]
C --> E[GUI activity]
C --> F[Doctor summary]
C --> G[Suspect and command summaries]
References: src/…/reader.ts• L5-59 src/…/display.ts• L1-45 src/…/audit-log.ts• L142-203 src/…/audit-log.ts• L325-357 src/…/activity.ts• L31-107 src/…/activity.ts• L16-82 src/…/main.ts• L623-639 src/…/main.ts• L832-870
Retention and cleanup
Audit retention is an opportunistic cleanup policy. The configured window defaults to 30 days and is limited to 1 through 365 days. The writer runs cleanup after it appends an entry, while read paths run it before they scan history.
The sweep runs at most once per UTC day for each audit root. It removes dated files only when their whole encoded UTC day is outside the window. It also removes wholly expired legacy root files when both their contents and modification time prove that they are old. It does not follow symlinks, touch unknown layouts, create a missing root, or block a decision when cleanup fails.
The explicit logs --prune-legacy command permanently removes root-level legacy JSONL files and leaves nested logs unchanged. Its dry-run form reports the files and bytes without deleting them. Normal retention cleanup is separate from this destructive migration aid.
References: src/…/audit-retention-days.ts• L1-16 src/…/schema.ts• L247-257 src/…/retention.ts• L24-121 src/…/audit-log.ts• L207-268
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the decision evidence fields aligned with the integration denial fields and the persisted audit entry fields. A mismatch can remove the blocked segment or rule from one surface without changing enforcement.
- Keep trace step types, trace projection, and both human and JSON explain formats aligned. A new diagnostic step can be recorded yet remain invisible to users.
- Keep every new diagnostic string on the sanitization path before it reaches trace output, denial text, or persisted command context. Remember that the audit writer does not redact
reasonor arbitrary metadata. - Keep the audit file layout, scan traversal, retention matching, and legacy cleanup rules consistent. A layout change can make records readable but invisible to cleanup or to the
logsand GUI views. - Keep retention bounds shared by policy validation, cleanup, CLI
--since, and GUI activity windows. A change in one limit can make a valid policy unreadable by a consumer. - Preserve partial-result signals when scan sources fail. Returning only surviving records without the skipped-source count can misstate the audit history.
- Keep project-first config-source reporting aligned with the policy snapshot used for the explanation. A preview can show a draft policy while its displayed source still describes disk configuration.
- Keep command-signature rules aligned across CLI filters, GUI filters, summaries, and suspect detection. A change can make the same audit record appear under different command groups.
- Keep trace recorder limits and sanitization behavior aligned with every trace renderer. A bounded or omitted event must not make the displayed explanation claim that it is a complete analysis record.
- Keep session filename sanitization, absolute audit-home checks, and path encoding aligned with the reader and retention sweep. A change can write records that other audit paths cannot find or safely clean.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Audit root or file cannot be read | CLI, doctor, or GUI history is partial. | Count skipped sources and warn or expose unreadable. |
| Audit record is malformed or has an invalid field type | The record is omitted from scan results. | Increase the skip count so callers mark the result as partial. |
| Trace recorder reaches an event, text, list, object, or depth limit | Some diagnostic steps or values are omitted. | Keep the trace bounded and preserve the available terminal result. |
| Trace event sanitization fails | The affected diagnostic event is omitted. | Keep sanitization best effort and do not use the trace to make the safety decision. |
| Audit append or retention cleanup fails | The command still receives its normal decision. | Swallow audit I/O failures and keep cleanup after append. |
| Invalid or missing retention value | Cleanup could be disabled or made unbounded if accepted directly. | Use the 30-day default and clamp valid values to 1–365 days. |
| Session ID contains path syntax or is empty | A log could escape its audit root or become unusable. | Sanitize the session filename and skip invalid IDs. |
| Persisted field exceeds its cap | Long command context could grow local history without bound. | Cap the field and mark the entry truncated, with the failure-entry exception. |
| Explanation policy source is read from disk while a draft snapshot is active | The result can show draft behavior with a disk path that does not describe the draft source. | Treat the policy snapshot as the evaluation input and the config source as separate provenance. |
| Command grouping ignores a new command form | Filters, summaries, and suspect detection can disagree about repeated commands. | Use the shared command-signature function for every displayed command grouping. |
| Audit home is relative or unavailable | No audit file is written for that environment. | Require an absolute home path and keep the write path best effort. |
Key files
| File | Why to read it |
|---|---|
| src/…/evaluate-command.ts | Shows the authoritative decision path with passive trace collection. |
| src/…/trace.ts | Defines trace steps, event scope, bounds, secret redaction, shared secret fingerprints across branches, and immutable trace output. |
| src/…/sanitize.ts | Defines the shared secret-redaction boundary for diagnostics. |
| src/…/explain.ts | Combines evaluation, policy context, pre-analysis protections, and trace data for explanations. |
| src/…/audit.ts | Maps runtime outcomes into persisted audit records. |
| src/…/writer.ts | Defines audit path selection, session-safe filenames, field redaction and caps, and write failure behavior. |
| src/…/retention.ts | Defines retention cleanup timing, dated-file matching, and legacy-file treatment. |
| src/…/reader.ts | Defines recursive scanning, record-shape validation, and skipped-source handling. |
| src/…/display.ts | Defines command signatures, relative time labels, and suspect detection for displayed history. |
| src/…/audit-log.ts | Defines the operator view for searching, filtering, exporting, and cleaning history. |
| src/…/activity.ts | Defines the GUI activity window, aggregates, cap, and partial-history signal. |
| src/…/activity.ts | Defines the recent blocked-activity summary used by health checks. |
| src/…/main.ts | Defines activity labels, filters, relative-time display, and incomplete-history messaging. |
| src/…/audit.ts | Defines the persisted audit contract and failed-evaluation categories. |
| src/…/redaction.ts | Defines the secret patterns applied to persisted command context and diagnostics. |
| src/…/command-trace.ts | Defines trace steps, segment scope, terminal outcomes, and passive context. |