Skip to content

Add audit-only daemon incarnation evidence - #11606

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/pr1-daemon-evidence-model
Jul 30, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/pr1-daemon-evidence-model

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Summary

Adds audit-only daemon incarnation evidence for #9138 without changing daemon lifecycle or routing behavior.

  • Records Linux birth identity, preserves pidfile nonce and identity fields, and fixes launcher-written app version metadata.
  • Adds tri-state availability and process evidence with per-platform conclusive-gone rules.
  • Retains authenticated endpoint identity across disconnects and reports same-endpoint replacements.
  • Emits dedicated audit eligibility telemetry.
  • Pins the current router, degraded-provider, and session-id fall-through behavior with regression tests.

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Executed:

  • pnpm run typecheck
  • Targeted Vitest run with --config config/vitest.config.ts --maxWorkers=2: 13 files, 340 tests passed
  • Normal and type-aware Oxlint scans on all 23 changed TypeScript files
  • pnpm run check:max-lines-ratchet
  • git diff --check

The 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 /proc reads 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

  • unknown always preserves the adapter and blocks destructive decisions.
  • Unreachable does not mean dead. An empty response does not mean unowned.
  • Missing socket or token files do not prove process exit.
  • A boolean liveness probe whose failure paths collapse to "absent" must never serve as a gone oracle. Classification is tri-state end to end: inspection failure is unknown. A signal-0 permission error proves only that some process occupies the pid — the incarnation classification stays unknown unless command line, start time, or nonce independently match. An authoritative start-time mismatch at the same pid is what proves the old incarnation gone; a match proves presence, not death.
  • Fail-open shortcuts that are safe for adoption (e.g. Windows start-time tolerance accepting a null start time) have the wrong polarity for gone proofs and must not be reused for them.
  • Never destroy identity evidence for a process that failed identification. Today killStaleDaemon skips the kill when isDaemonProcess is inconclusive but still unlinks the pidfile unconditionally — leaving a live daemon permanently untracked with no recorded identity. An inconclusive identity check preserves the pidfile.
  • Session identifiers are not globally unique across protocol generations, and the routing fall-through to the current daemon is active today. Removing a route does not transfer its PTY to another daemon.
  • A stale event cannot affect a replacement daemon at the same endpoint.
  • Automatic cleanup must never use broad shutdown { killSessions: true }.
  • Pre-v24 daemons (CLEAN_DISCONNECT_PROTOCOL_VERSION) must not be shut down automatically without equivalent atomic retirement authority.
  • Local and remote providers are separate authorities: an unavailable SSH provider must not gate local destructive decisions, and vice versa. A destructive operation targeting a local worktree still requires authority from every local generation.
  • Folder workspaces and git worktrees use the same safety rules.

PR 1: Evidence Model, Audit-Only Classifier, Regression Tests

This PR must not change daemon lifecycle behavior.

Changes

  • Add regression coverage for the four currently untested core scenarios:
    1. a legacy daemon exits after adapter construction (the reported repro);
    2. DegradedDaemonPtyProvider.listProcesses rejection;
    3. cross-generation session-id collision through the routing fall-through;
    4. daemon identity change across a reconnect at the same endpoint.
  • Note: the existing router fail-closed test pins today's behavior; PR 3 revises its contract.
  • Add the explicit evidence state:
    • present: the daemon is authoritatively available — an authenticated connection answers inventory. Exact incarnation identity is not required here: responsive pre-v24 daemons have no DaemonEndpointIdentity yet 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.
  • Build the classifier from existing identity:
    • preserve launchNonce through parseDaemonPidFile;
    • record the exact incarnation at birth: the daemon self-reports raw start ticks + boot id in its existing ready payload (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 CIM CreationDate + tolerance (a wholesale replacement would regress Windows);
    • while touching the pidfile: the production launcher omits appVersion, so launcher-written pidfiles always read stale-for-bundle on the next boot — fix in passing;
    • retain the last authenticated DaemonEndpointIdentity on the adapter across disconnect;
    • construct a tri-state process-identity probe from isDaemonProcess's ingredients (command-line match, start-time tolerance), with inspection failure mapping to unknown; permission-denied signal-0 proves the pid is occupied but leaves the incarnation unknown without an independent identity match; an authoritative start-time mismatch at the same pid proves gone;
    • make identity change across reconnect an explicit, observable event.
  • Classification runs event-driven — adapter transport close, observed authenticated disconnect plus token ENOENT, and lazily on inventory failure — never on a timer alone.
  • Record the reason and evidence source for every classification.
  • Inventory protocol generation, provider, endpoint, profile scope, and exact incarnation where supported.
  • Keep reachability, inventory authority, and process liveness as separate facts.
  • Emit audit-only eligibility telemetry as its own event family. Do not reuse 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.
  • Run the classifier without removing adapters or shutting down daemons.

Decision Gate

Document the conclusive gone proofs available for each supported platform. If exact disappearance cannot be proved for a protocol/platform combination, it remains unknown and 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:

  • Compare the raw /proc/<pid>/stat start-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 by CLK_TCK truncates 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.
  • The 1500ms tolerance is miscalibrated in both directions: it masks fast reuse, and against a wall-clock spawn stamp its worst-case error measured 1458ms on an idle host — a loaded host produces false gone on a live daemon.
  • Parse field 22 from after the last ) in the stat line; whitespace-split parsing breaks on process names containing spaces.
  • Zombies: kill(pid, 0) succeeds and the start time is unchanged on a dead, unreaped process (a non-reaping PID 1 — the docker run SSH-target shape — never reaps orphans). State Z with matching identity is itself conclusive gone evidence (the process has exited); signal success alone is never present.
  • Errno discipline: EPERM means occupied-not-gone; ESRCH appears only after reaping; the shell exit code cannot distinguish them.

macOS:

  • ps lstart has 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.pid start time in microseconds); with lstart alone the tolerance is required and the proof is weaker.
  • Field census (2026-07-29, primary field machine, 7 live generations v23–v30): all 7 pidfiles parseable with matching command lines — 100% classifiable — but the LIVE current daemon's recorded stamp vs the lstart-derived value differs by ~2.5s, beyond the 1500ms tolerance. Used as a gone proof, the existing check would classify a live current daemon dead today; the false-gone risk is observed, not hypothetical. One pidfile (v23) predates launchNonce — older identity formats exist in the field and must classify as unknown-capable, not error.
  • kill -0 errno 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):

  • ECONNREFUSED means only "no listener": crash and clean-exit-without-unlink are indistinguishable by errno, and a non-socket squatter at the path also yields ECONNREFUSED. Classify the endpoint with stat()/S_ISSOCK, not the connect errno.

Windows (non-elevated, the realistic oracle view):

  • pid + CIM CreationDate is 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).
  • CommandLine is corroborating-only and never a negative signal: 136 of 544 live processes (25%) returned a null CommandLine across the privilege boundary while CreationDate was populated for 100%.
  • The 10s CreationDate tolerance is ~500x the observed need; it exists to absorb the stamp-source gap (daemon self-stamping after boot). Do not widen it; if the parent stamps at spawn it can tighten to 1–2s, shrinking the pid-reuse acceptance window.
  • Named pipes vanish with their process (verified both directions): pipe presence is positive liveness evidence, pipe absence is an independent second gone proof, and no stale-endpoint ambiguity exists.

General:

  • Token-unlink-after-authenticated-disconnect is a trigger and contributing evidence, not sole proof.
  • Remote providers have no process-table oracle today (see PR 4 scoping).

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: audit-only daemon incarnation evidence.
Description check ✅ Passed The description follows the template and covers summary, screenshots, testing, AI review, security, and notes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_PROOFS names don't match any emitted gone reason, so the oracle contract is unenforceable. The constant uses boot_identity_changed / raw_start_ticks_mismatch / matching_identity_zombie / cim_* while classification emits linux_boot_changed, linux_start_ticks_mismatch, linux_zombie, windows_process_missing, windows_creation_time_mismatch, and windows_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 with satisfies against the gone reason 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 win

Empty procfs cmdline should fall through to ps.

Zombies and kernel threads yield an empty /proc/<pid>/cmdline, which is returned as '' and then classified as command_line_mismatch rather than falling back to ps or 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 value

This pin duplicates the constant instead of tying it to emitted reasons.

Because the literals differ from the actual gone reasons, this test passes for any future reason set; see the note on daemon-incarnation-evidence-types.ts.

src/main/daemon/daemon-audit-classifier.ts (3)

98-111: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Expose the probe dependencies so audit classification is testable without touching the host.

probeDaemonProcessIdentity accepts DaemonProcessProbeDependencies, but the classifier never forwards them, so daemon-incarnation-evidence.test.ts Lines 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 win

Gate endpointGoneProof on the named-pipe endpoint kind.

A unix-socket context passed windows_named_pipe_missing would emit a Windows-only conclusive-gone reason with endpointState: 'missing', overriding the actual lstat result.

🛡️ 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 lift

Derive these enums from shared constants to avoid silent telemetry drift.

The reason, process_reason, and evidence_sources literals restate unions owned by daemon-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 failing validate() at runtime. The neighboring daemonLifecycleSchema already 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5fe3aaf and d5856ff.

📒 Files selected for processing (23)
  • src/main/agent-hooks/managed-hook-owner-identity.ts
  • src/main/daemon/daemon-audit-classifier.ts
  • src/main/daemon/daemon-audit-eligibility-event.test.ts
  • src/main/daemon/daemon-audit-eligibility-event.ts
  • src/main/daemon/daemon-entry.ts
  • src/main/daemon/daemon-health.test.ts
  • src/main/daemon/daemon-health.ts
  • src/main/daemon/daemon-incarnation-evidence-types.ts
  • src/main/daemon/daemon-incarnation-evidence.test.ts
  • src/main/daemon/daemon-incarnation-evidence.ts
  • src/main/daemon/daemon-init.test.ts
  • src/main/daemon/daemon-init.ts
  • src/main/daemon/daemon-process-inspection.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-ready-identity.test.ts
  • src/main/daemon/daemon-ready-identity.ts
  • src/main/daemon/daemon-spawner.ts
  • src/main/daemon/degraded-daemon-pty-provider.test.ts
  • src/main/daemon/production-launcher.test.ts
  • src/main/daemon/production-launcher.ts
  • src/shared/telemetry-events.ts

Comment thread src/main/daemon/daemon-pty-adapter.ts Resolved
Comment on lines +39 to +44
if (platform === 'linux') {
try {
return await readFile(`/proc/${pid}/cmdline`, 'utf8')
} catch {
// Fall through to ps for procfs privilege or mount restrictions.
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

Adds an audit-only daemon incarnation evidence model that classifies each daemon adapter's state as present, gone, or unknown without altering any lifecycle behavior. Classification triggers on transport close, authenticated-disconnect-then-token-ENOENT, inventory failure, or endpoint-identity change, and emits a dedicated daemon_audit_eligibility telemetry event.

  • Adds tri-state process-identity probes per platform (Linux /proc ticks + boot-id, macOS lstart-tolerance mapped to unknown-not-gone, Windows CIM CreationDate), preserving launchNonce, linuxStartTicks, and bootId in the pidfile; fixes the longstanding omission of appVersion in launcher-written pidfiles.
  • Retains the last authenticated DaemonEndpointIdentity across disconnects and emits an explicit identity-change event on same-endpoint reconnect to a different daemon.
  • Pins four previously-untested router/provider scenarios (legacy-exits-after-construction, DegradedDaemonPtyProvider rejection, cross-generation session-id fall-through, and identity change on reconnect) with new regression tests.

Confidence Score: 5/5

Safe 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.

Important Files Changed

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)
Loading

Reviews (2): Last reviewed commit: "fix(daemon): isolate audit evidence obse..." | Re-trigger Greptile

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/daemon/daemon-pty-adapter.ts (1)

2313-2321: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider logging swallowed audit-listener exceptions.

notifyAuditListeners silently 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 in onDaemonIdentityChanged/onAuditEligibilityObservation leaves 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

📥 Commits

Reviewing files that changed from the base of the PR and between d5856ff and ef5b075.

📒 Files selected for processing (11)
  • src/main/daemon/daemon-audit-classifier.ts
  • src/main/daemon/daemon-incarnation-evidence-types.ts
  • src/main/daemon/daemon-incarnation-evidence.test.ts
  • src/main/daemon/daemon-incarnation-evidence.ts
  • src/main/daemon/daemon-process-inspection.test.ts
  • src/main/daemon/daemon-process-inspection.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/runtime/worktree-teardown.test.ts
  • src/shared/daemon-audit-eligibility.ts
  • src/shared/telemetry-events.ts

@brennanb2025
brennanb2025 merged commit d4cfee7 into main Jul 30, 2026
48 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* feat(daemon): add audit incarnation evidence

* fix(daemon): isolate audit evidence observers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant