Repository navigation
Add audit-only daemon incarnation evidence - #11606
Conversation
📝 WalkthroughWalkthroughThe change adds structured daemon readiness and PID identity metadata, including Linux start ticks and boot identity. It introduces platform-specific process-incarnation evidence probing and audit observation classification. Daemon process listing now records authenticated inventory and publishes audit eligibility observations, while adapter APIs expose identity and audit state events. A new telemetry schema records audit observations. Startup, launcher, health parsing, routing, degraded-provider, and adapter tests cover the new identity, evidence, audit, and failure-handling behavior. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (7)
src/main/daemon/daemon-incarnation-evidence-types.ts (1)
6-15: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
DAEMON_GONE_PROOFSnames don't match any emittedgonereason, so the oracle contract is unenforceable. The constant usesboot_identity_changed/raw_start_ticks_mismatch/matching_identity_zombie/cim_*while classification emitslinux_boot_changed,linux_start_ticks_mismatch,linux_zombie,windows_process_missing,windows_creation_time_mismatch, andwindows_named_pipe_missing.
src/main/daemon/daemon-incarnation-evidence-types.ts#L6-L15: rename the literals to the actual reason values and constrain the constant withsatisfiesagainst thegonereason union so new reasons force an update.src/main/daemon/daemon-incarnation-evidence.test.ts#L41-L52: assert the proofs against the reason union (or the classifier's gone outputs) instead of re-listing the same literals.src/main/daemon/daemon-process-inspection.ts (1)
39-45: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winEmpty procfs
cmdlineshould fall through tops.Zombies and kernel threads yield an empty
/proc/<pid>/cmdline, which is returned as''and then classified ascommand_line_mismatchrather than falling back topsor reporting unavailability.♻️ Proposed fix
if (platform === 'linux') { try { - return await readFile(`/proc/${pid}/cmdline`, 'utf8') + const cmdline = await readFile(`/proc/${pid}/cmdline`, 'utf8') + if (cmdline) { + return cmdline + } } catch { // Fall through to ps for procfs privilege or mount restrictions. } }src/main/daemon/daemon-incarnation-evidence.test.ts (1)
41-52: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThis pin duplicates the constant instead of tying it to emitted reasons.
Because the literals differ from the actual
gonereasons, this test passes for any future reason set; see the note ondaemon-incarnation-evidence-types.ts.src/main/daemon/daemon-audit-classifier.ts (3)
98-111: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExpose the probe dependencies so audit classification is testable without touching the host.
probeDaemonProcessIdentityacceptsDaemonProcessProbeDependencies, but the classifier never forwards them, sodaemon-incarnation-evidence.test.tsLines 288-308 actually signal a live pid and shell out (ps/powershell.exe) on the CI host. Threading an optional parameter through keeps production behavior identical and makes the classifier deterministic on all three platforms.♻️ Proposed change
export async function classifyDaemonAuditFailure( context: DaemonAuditContext, trigger: Exclude<DaemonAuditTrigger, 'inventory_answered'>, exactIncarnation: ExactDaemonIncarnation | null, additionalEvidenceSources: readonly DaemonEvidenceSource[] = [], - endpointGoneProof?: 'windows_named_pipe_missing' + endpointGoneProof?: 'windows_named_pipe_missing', + probeDependencies: DaemonProcessProbeDependencies = {} ): Promise<DaemonAuditObservation> { const [processEvidence, endpointState] = await Promise.all([ - probeDaemonProcessIdentity(exactIncarnation, { - socketPath: context.endpoint, - tokenPath: context.tokenPath - }), + probeDaemonProcessIdentity( + exactIncarnation, + { socketPath: context.endpoint, tokenPath: context.tokenPath }, + probeDependencies + ), inspectEndpointState(context) ])
118-133: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winGate
endpointGoneProofon the named-pipe endpoint kind.A
unix-socketcontext passedwindows_named_pipe_missingwould emit a Windows-only conclusive-gone reason withendpointState: 'missing', overriding the actuallstatresult.🛡️ Proposed fix
- if (endpointGoneProof && exactIncarnation) { + if (endpointGoneProof && exactIncarnation && context.endpointKind === 'windows-named-pipe') {
193-201: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
first[0], ...first.slice(1)is just...first.♻️ Simplification
- return [...new Set([first[0], ...first.slice(1), ...rest.flat()])] as [ + return [...new Set([...first, ...rest.flat()])] as [ DaemonEvidenceSource, ...DaemonEvidenceSource[] ]src/shared/telemetry-events.ts (1)
421-502: 🗄️ Data Integrity & Integration | 🔵 Trivial | 🏗️ Heavy liftDerive these enums from shared constants to avoid silent telemetry drift.
The
reason,process_reason, andevidence_sourcesliterals restate unions owned bydaemon-audit-classifier.ts/daemon-incarnation-evidence-types.ts, and.max(12)hardcodes the current source cardinality. Adding a source or gone reason there compiles cleanly but starts failingvalidate()at runtime. The neighboringdaemonLifecycleSchemaalready uses shared const arrays (DAEMON_REPLACE_REASONS); exporting equivalent arrays for evidence sources and audit reasons and building both the TS unions and these enums from them would make drift a type error.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 0335b449-5962-461f-9a40-4471166bef9a
📒 Files selected for processing (23)
src/main/agent-hooks/managed-hook-owner-identity.tssrc/main/daemon/daemon-audit-classifier.tssrc/main/daemon/daemon-audit-eligibility-event.test.tssrc/main/daemon/daemon-audit-eligibility-event.tssrc/main/daemon/daemon-entry.tssrc/main/daemon/daemon-health.test.tssrc/main/daemon/daemon-health.tssrc/main/daemon/daemon-incarnation-evidence-types.tssrc/main/daemon/daemon-incarnation-evidence.test.tssrc/main/daemon/daemon-incarnation-evidence.tssrc/main/daemon/daemon-init.test.tssrc/main/daemon/daemon-init.tssrc/main/daemon/daemon-process-inspection.tssrc/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-pty-router.test.tssrc/main/daemon/daemon-ready-identity.test.tssrc/main/daemon/daemon-ready-identity.tssrc/main/daemon/daemon-spawner.tssrc/main/daemon/degraded-daemon-pty-provider.test.tssrc/main/daemon/production-launcher.test.tssrc/main/daemon/production-launcher.tssrc/shared/telemetry-events.ts
| if (platform === 'linux') { | ||
| try { | ||
| return await readFile(`/proc/${pid}/cmdline`, 'utf8') | ||
| } catch { | ||
| // Fall through to ps for procfs privilege or mount restrictions. | ||
| } |
There was a problem hiding this comment.
Broad catch silently swallows ENOENT on
/proc/$pid/cmdline
When the process exits between the /proc/$pid/stat read and this readFile call, the kernel removes /proc/$pid/cmdline and this throws ENOENT. The bare catch {} falls through to ps, which also fails (process gone), ultimately returning undefined → unknown('command_line_unavailable', ...) instead of surfacing the process exit. Because /proc/$pid/stat is confirmed present immediately before this call, the race window is tiny and the result is fail-closed (unknown, never gone), so there is no safety regression. However, distinguishing ENOENT (process gone) from permission errors would allow the classification to return a more precise 'inspection_failed' vs. process-exit signal — worth tracking if the audit dashboard shows unexplained command_line_unavailable spikes.
Greptile SummaryAdds an audit-only daemon incarnation evidence model that classifies each daemon adapter's state as
Confidence Score: 5/5Safe to merge: the classifier is observational only, all changed lifecycle paths are regression-tested, and the only new public-facing behavior is a fire-and-forget telemetry event that cannot affect adapter availability or routing. The audit boundary is rigorously enforced — no adapter removals, no daemon signals beyond signal-zero, no session mutations. The tri-state unknown → fail-safe invariant is upheld at every inspection-failure branch across all three platforms. The lastAuditObservation snapshot race noted above is purely cosmetic: telemetry and event listeners receive events in correct real-time order, and no routing or lifecycle code reads the snapshot field. Regression coverage for the four previously-untested scenarios is solid. Files Needing Attention: The transport_closed → reconnect → lastAuditObservation ordering in daemon-pty-adapter.ts is worth a second look if future callers start using getLastAuditObservation() for anything beyond debugging.
|
| Filename | Overview |
|---|---|
| src/main/daemon/daemon-pty-adapter.ts | Adds audit observation/listener infrastructure and wraps listProcesses in try/catch to publish present or unknown/gone observations; a fire-and-forget transport_closed probe can overwrite lastAuditObservation with a stale result after a successful reconnect (audit-only, no lifecycle impact). |
| src/main/daemon/daemon-incarnation-evidence.ts | Core tri-state process-identity probe per platform; Linux uses raw ticks + boot-id, macOS maps lstart mismatch to unknown, Windows uses CIM. Fail-safe semantics (inspection errors → unknown) are consistent throughout. |
| src/main/daemon/daemon-audit-classifier.ts | Orchestrates process probe + endpoint stat; Windows named-pipe early-return correctly hardcodes endpointState: missing overriding the placeholder inspectDaemonEndpointState return; combineEvidenceSources non-empty tuple cast is safe because first[0] guarantees ≥1 element. |
| src/main/daemon/daemon-process-inspection.ts | New file; queryWindowsProcess interpolates PID into PowerShell only after validating it is a safe positive integer (injection not possible); Linux procfs read falls through to ps on empty result; broad catch correctly maps to undefined/unavailable (fail-closed). |
| src/main/daemon/daemon-ready-identity.ts | Reads /proc/self/stat synchronously at daemon startup (boot-time, not a hot path), rejects partial Linux identity (ticks without boot-id or vice versa) to prevent persisting a false proof. |
| src/main/agent-hooks/managed-hook-owner-identity.ts | Fixes parseLinuxStartTicks to use lastIndexOf(')') + .trim() instead of lastIndexOf(') ') + fixed offset, correctly handling process names that contain spaces or ) characters. Exports readBootIdentity for reuse in new evidence module. |
| src/shared/daemon-audit-eligibility.ts | New shared constants and union types for all audit states, triggers, evidence sources, and gone/present/unknown reasons; used by both the telemetry schema and the classifier. |
| src/shared/telemetry-events.ts | Adds the daemon_audit_eligibility Zod schema; all enum values align with the shared constants; process_reason correctly accepts .nullable() to cover the present-state null case. |
Sequence Diagram
sequenceDiagram
participant DA as DaemonPtyAdapter
participant DC as DaemonClient
participant AC as DaemonAuditClassifier
participant PI as ProcessIdentityProbe
participant TE as Telemetry
DA->>DC: ensureConnected()
DC-->>DA: connected (fires recordAuthenticatedIdentity)
DA->>DA: readMatchingPidRecord(identity)
DA->>DA: exactDaemonIncarnation set
DA->>DC: listSessions RPC
DC-->>DA: sessions result
DA->>AC: recordAuthenticatedInventory(context, exactIncarnation)
AC-->>DA: "DaemonAuditObservation{state:'present'}"
DA->>TE: trackDaemonAuditEligibility(present)
DA->>DA: notify auditObservationListeners
note over DA,TE: Transport closes (crash/restart)
DC-->>DA: emit 'close'
DA->>AC: classifyDaemonAuditFailure('transport_closed') [async]
AC->>PI: probeDaemonProcessIdentity(exactIncarnation)
PI->>PI: readLinuxStat / queryWindowsProcess / ps
PI-->>AC: "DaemonProcessEvidence{state:'gone'|'unknown'}"
AC-->>DA: "DaemonAuditObservation{state:'gone'|'unknown'}"
DA->>TE: trackDaemonAuditEligibility(gone/unknown)
note over DA,TE: listProcesses fails (token missing after auth disconnect)
DA->>AC: classifyDaemonAuditFailure('token_missing_after_authenticated_disconnect') [async]
AC->>PI: probeDaemonProcessIdentity + inspectEndpointState
PI-->>AC: evidence
AC-->>DA: "DaemonAuditObservation{state:'unknown'}"
DA->>TE: trackDaemonAuditEligibility(unknown)
Reviews (2): Last reviewed commit: "fix(daemon): isolate audit evidence obse..." | Re-trigger Greptile
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/daemon/daemon-pty-adapter.ts (1)
2313-2321: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider logging swallowed audit-listener exceptions.
notifyAuditListenerssilently discards listener errors. This correctly preserves the "audit can't break daemon operations" invariant (the previously flagged critical issue is fixed), but a silently-swallowed throw inonDaemonIdentityChanged/onAuditEligibilityObservationleaves no trace for debugging.♻️ Proposed logging addition
function notifyAuditListeners<T>(listeners: readonly ((value: T) => void)[], value: T): void { for (const listener of listeners.slice()) { try { listener(value) - } catch { - // Audit observers cannot affect daemon operations. + } catch (err) { + // Audit observers cannot affect daemon operations. + console.warn('[daemon] audit listener threw', err) } } }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: bfa66e23-533c-40b6-b045-d744df654b75
📒 Files selected for processing (11)
src/main/daemon/daemon-audit-classifier.tssrc/main/daemon/daemon-incarnation-evidence-types.tssrc/main/daemon/daemon-incarnation-evidence.test.tssrc/main/daemon/daemon-incarnation-evidence.tssrc/main/daemon/daemon-process-inspection.test.tssrc/main/daemon/daemon-process-inspection.tssrc/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/runtime/worktree-teardown.test.tssrc/shared/daemon-audit-eligibility.tssrc/shared/telemetry-events.ts
* feat(daemon): add audit incarnation evidence * fix(daemon): isolate audit evidence observers
Summary
Adds audit-only daemon incarnation evidence for #9138 without changing daemon lifecycle or routing behavior.
Screenshots
No visual change.
Testing
pnpm lintpnpm typecheckpnpm testpnpm buildExecuted:
pnpm run typecheck--config config/vitest.config.ts --maxWorkers=2: 13 files, 340 tests passedpnpm run check:max-lines-ratchetgit diff --checkThe repository changed-code wrapper could not parse the local pnpm engine warning under Node 26, so its equivalent normal and type-aware Oxlint scans were run directly and passed.
AI Review Report
Reviewed the complete diff against the audit-only boundary, evidence polarity, exact-incarnation requirements, event triggers, and current routing/aggregate behavior. The review found one Windows edge where signal-zero PID absence could bypass CIM; the probe now requires the platform oracle and has regression coverage. Cross-platform review confirmed Linux
/procreads are platform-gated and use raw ticks plus boot identity, macOS weak start-time mismatch remains unknown, Windows keeps CIM CreationDate tolerance and null command-line/start-time fail-closed behavior, and touched paths use platform-aware path handling; no UI shortcuts, labels, shell behavior, or renderer behavior changed.Security Audit
The classifier is observational and cannot remove adapters, signal daemons beyond non-mutating signal zero, retire processes, or shut down sessions. Exact evidence is bound to authenticated endpoint identity and matching pidfile nonce/start metadata; incomplete, unreadable, permission-denied, and contradictory probes remain unknown. Process inspection uses fixed executable/argument forms, the interpolated Windows PID is numeric, telemetry excludes endpoint paths, profile paths, nonces, and command lines, and no dependencies or new external inputs were added.
Notes
This is PR 1 of the daemon generation-leak safety sequence. PRs 2–5 follow the contract below and remain out of scope for this PR.
Safety Invariants
unknownalways preserves the adapter and blocks destructive decisions.goneoracle. Classification is tri-state end to end: inspection failure isunknown. A signal-0 permission error proves only that some process occupies the pid — the incarnation classification staysunknownunless command line, start time, or nonce independently match. An authoritative start-time mismatch at the same pid is what proves the old incarnationgone; a match proves presence, not death.goneproofs and must not be reused for them.killStaleDaemonskips the kill whenisDaemonProcessis inconclusive but still unlinks the pidfile unconditionally — leaving a live daemon permanently untracked with no recorded identity. An inconclusive identity check preserves the pidfile.shutdown { killSessions: true }.CLEAN_DISCONNECT_PROTOCOL_VERSION) must not be shut down automatically without equivalent atomic retirement authority.PR 1: Evidence Model, Audit-Only Classifier, Regression Tests
This PR must not change daemon lifecycle behavior.
Changes
DegradedDaemonPtyProvider.listProcessesrejection;present: the daemon is authoritatively available — an authenticated connection answers inventory. Exact incarnation identity is not required here: responsive pre-v24 daemons have noDaemonEndpointIdentityyet still provide authenticated, authoritative inventory.gone: conclusive evidence proves the exact incarnation has exited. Exact incarnation evidence is required specifically for this transition.unknown: evidence is incomplete, unavailable, or contradictory.launchNoncethroughparseDaemonPidFile;readypayload (read from/proc/self— zero pid-reuse window), and the parent persists them in the pidfile alongside the current fields. Reuse the existing agent-hooks identity abstraction; the tick proof is additive where available, and Windows keeps CIMCreationDate+ tolerance (a wholesale replacement would regress Windows);appVersion, so launcher-written pidfiles always read stale-for-bundle on the next boot — fix in passing;DaemonEndpointIdentityon the adapter across disconnect;isDaemonProcess's ingredients (command-line match, start-time tolerance), with inspection failure mapping tounknown; permission-denied signal-0 proves the pid is occupied but leaves the incarnationunknownwithout an independent identity match; an authoritative start-time mismatch at the same pid provesgone;daemon_lifecycle: that event's schema means an actual replaced/retired transition, and mixing in eligibility observations would make lifecycle dashboards and counts semantically false.Decision Gate
Document the conclusive
goneproofs available for each supported platform. If exact disappearance cannot be proved for a protocol/platform combination, it remainsunknownand receives no containment behavior.Constraints validated empirically on 2026-07-29 (macOS local; Linux via privileged container over SSH with deterministic pid reuse; Windows via a remote non-elevated box):
Linux:
/proc/<pid>/statstart-time ticks for exact equality, paired with a boot id (ticks are boot-relative); both are already produced by the existing agent-hooks identity abstraction. Never derive milliseconds. Integer division byCLK_TCKtruncates to whole seconds: under deterministic fast pid reuse the derived ms values were bit-identical for two different incarnations in 12/12 trials, while the raw ticks always differed. Even a zero tolerance fails on the derived value.goneon a live daemon.)in the stat line; whitespace-split parsing breaks on process names containing spaces.kill(pid, 0)succeeds and the start time is unchanged on a dead, unreaped process (a non-reaping PID 1 — thedocker runSSH-target shape — never reaps orphans). StateZwith matching identity is itself conclusivegoneevidence (the process has exited); signal success alone is neverpresent.macOS:
ps lstarthas 1-second resolution — the same reuse-masking hazard as the Linux truncation. Exact-incarnation matching needs a finer source (e.g.proc_pidinfo/sysctl kern.proc.pidstart time in microseconds); withlstartalone the tolerance is required and the proof is weaker.goneproof, the existing check would classify a live current daemon dead today; the false-gonerisk is observed, not hypothetical. One pidfile (v23) predateslaunchNonce— older identity formats exist in the field and must classify asunknown-capable, not error.kill -0errno semantics and stale-socket behavior match Linux (verified: EPERM on root-owned live pid; ESRCH after kill; socket file lingers after SIGKILL with ECONNREFUSED, ENOENT only after unlink).POSIX sockets (both):
stat()/S_ISSOCK, not the connect errno.Windows (non-elevated, the realistic oracle view):
CreationDateis the primary identity: 100ns underlying resolution, zero read-to-read jitter, ~20ms agreement with a parent-side spawn stamp; a dead pid is totally absent from CIM (no zombie state).goneproof, and no stale-endpoint ambiguity exists.General: