Skip to content

Commit 4645ab7

Browse files
committed
feat: implement custody journal for agent execution tracking
- Add CustodyJournal class to manage execution records with atomic persistence. - Introduce CustodyRecord interface to define the structure of custody records. - Implement recovery logic for interrupted turns and handle various custody states. - Create tests for CustodyJournal to ensure correct behavior during recovery and state management. feat: add custody service for Electron integration - Create custody service to manage journal access and authority verification. - Implement scopeKeyFor and authorityOf functions to handle session keys and authority normalization. - Add scopeViolation function to check the validity of granted workspace roots. feat: develop custody halt banner component - Implement CustodyHaltBanner component to display halt notifications with preserved evidence. - Provide user feedback for reauthorization actions and display relevant details about the halt. feat: enhance crew integration presentation logic - Create functions to present crew integration status with user-friendly messages. - Implement tests to verify the presentation logic for different integration states. feat: introduce crew review fingerprinting - Implement crewReviewFingerprint function to track changes in lane ownership. - Ensure that runtime status updates do not affect the review evidence display. chore: add shared custody types for consistency - Define custody invariant types and violation structures for shared use across main and renderer processes.
1 parent 7e7f5d2 commit 4645ab7

65 files changed

Lines changed: 3312 additions & 191 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎AGENTS.md‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,54 @@ src/renderer/src/
7171

7272
Always use the primary working directory (the worktree) for all file reads and edits. Never follow absolute paths from subagent results that point to the main repo.
7373

74+
## GOVERNING DOCTRINE: Execution Custody
75+
76+
Binding on every privileged surface in this repository, current and future. Full
77+
rationale and implementation map in `docs/execution-custody.md`.
78+
79+
Granting authority is decided at the gates in `docs/security-model.md`. This
80+
doctrine governs the other half of the lifecycle: **withdrawing authority once it
81+
has already been granted.**
82+
83+
When **authority / identity / scope / provenance / execution custody** becomes
84+
unknown, stale, contradictory, or changes unexpectedly:
85+
86+
```
87+
-> refuse new privileged actions on the affected scope
88+
-> contain or terminate owned execution where safe
89+
-> preserve evidence and current workspace state
90+
-> report the exact failed invariant and affected scope
91+
-> require explicit human reauthorization before resuming
92+
```
93+
94+
Never, under any circumstance, infer a successful outcome from the absence of a
95+
failure signal:
96+
97+
```
98+
silence != success
99+
timeout != success
100+
lost telemetry != success
101+
missing process state != success
102+
clean Git state != behavioral correctness
103+
```
104+
105+
Rules for new code:
106+
107+
- An operation whose outcome was never observed is recorded as `interrupted` or
108+
`halted`. It is never back-filled as complete, and never on restart.
109+
- Long-lived executions carry a persisted custody record. Process-local runtime
110+
ids are cleared on restart; in-flight work becomes `interrupted`, not success.
111+
- Authority must not change underneath an execution that is already running.
112+
Refuse and defer the mutation; do not apply it mid-flight.
113+
- Every sanctioned authority mutation is written to the custody record. An
114+
unrecorded divergence is drift and must trip.
115+
- Reports name the exact failed invariant and the exact affected scope. Never a
116+
generic error.
117+
- A halt is cleared only by explicit human reauthorization. Halted records are
118+
stamped, never deleted — resuming work must not erase why it stopped.
119+
- Read-only inspection of custody state is never gated by a halt. A halt must
120+
not hide the evidence it was raised to preserve.
121+
74122
Crew merges must not equate a clean Git merge with behavioral correctness. Keep the cross-lane collision analysis explainable and advisory, preserve the explicit review gate, and persist source worktree/commit provenance before starting a merge. On restart, process-local runtime ids must be cleared and a still-running merge audit or verification check must become `interrupted`, never inferred successful. Verification IPC accepts only main-discovered `typecheck`/`test` ids, displays the exact command and package script before execution, and must never become arbitrary command execution. See `docs/behavioral-merge-review.md`.
75123

76124
## Cross-Platform Support

‎docs/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ internal references).
2929
| Doc | What it covers |
3030
| --- | --- |
3131
| [security-model.md](./security-model.md) | Authority-boundary audit: untrusted content -> agent -> MCP/plugin -> exec -> Git/SSH, per-hop gates, tests, and residual risk |
32+
| [execution-custody.md](./execution-custody.md) | Withdrawing authority after it was granted: invariant tripwire, custody journal, halt/contain/preserve/report, explicit reauthorization |
3233
| [remote-ssh-workspaces.md](./remote-ssh-workspaces.md) | Opening projects over SSH: setup, auth, host pinning, what works remotely |
3334
| [canvas-mode.md](./canvas-mode.md) | Workbench: multiple chats and terminals side by side on one worktree _(nav label: "Workbench")_ |
3435
| [chat-archiving.md](./chat-archiving.md) | Right-click a chat to archive it; the Archive page, restoring, and retention flagging |

‎docs/behavioral-merge-review.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,17 @@ A passing candidate is retained by an internal Git ref. **Apply checked integrat
2929

3030
Only then does CrewCode use `git merge --ff-only` to apply the checked commit. A changed input makes the candidate stale and requires another verification.
3131

32+
The sidebar reports the result as a **candidate decision**, not as whether CrewCode itself worked. **Candidate rejected** means the safety gate ran and prevented an incompatible or otherwise failing combination from reaching the base. **Ready to apply** means the combined candidate passed the discovered checks. Failed check output is expanded beneath the check so the rejection reason is visible without opening developer tools.
33+
3234
## Restart recovery and evidence
3335

3436
The main process atomically persists a merge journal under CrewCode's user-data directory before combination begins and at every phase transition. Each record contains the session, base branch/SHA, lane label, branch, worktree path, owned files and SHA, current phase, discovered check commands, outputs, status, and timestamps.
3537

3638
After restart, an in-flight operation is shown as `interrupted` instead of implying that its process survived. Any running check is likewise marked interrupted. A candidate that had already passed is reconciled against Git; moved base/lane/ref inputs make it stale. If CrewCode stopped while applying but the base now equals the retained integration SHA, reconciliation records the operation as applied. The base is never inferred to be updated merely because a subprocess had started.
3739

38-
Crew session ownership is also persisted locally. Process-local bridge and terminal IDs are cleared on recovery, and lanes that previously said `running` recover as `ready`; the UI never claims an agent process survived without evidence.
40+
Crew session ownership is also persisted locally. Each lane has an explicit **enabled / paused** switch and an editable **next action** checkpoint, automatically seeded from its latest assignment. Pausing stops the lane runtime but retains its worktree, transcript, and checkpoint; resuming does not auto-submit work. Process-local bridge and terminal IDs are cleared on recovery, lanes that previously said `running` recover as `ready`, and persisted pause/checkpoint state remains visible. The UI never claims an agent process survived without evidence.
41+
42+
Compare and Merge cache their loaded Git evidence by stable lane ownership (lane ID, branch, and path). Runtime status, usage-timer, pause, and checkpoint updates therefore no longer reset those surfaces to a loading state or replay their entry UI while they are open.
3943

4044
## Limits
4145

‎docs/crewcoder-provider.md‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,18 @@ has no native compact RPC.
5151
| repeated `tool_call` for the same id | `tool_update` |
5252
| running `tool_call_update` | `tool_update` |
5353
| completed/failed `tool_call_update` | `tool_end` |
54+
| `_crewcoder/compaction_update` | `compaction_event` |
55+
56+
CrewCoder's compaction update is an additive namespaced ACP extension carrying
57+
started/completed/failed status, automatic intent, progress, and a human-readable
58+
message. The bridge treats it as authoritative and does not also infer
59+
compaction from the later context-token drop. The compacted summary remains in
60+
CrewCoder's durable session and is not copied into CrewCode's transcript.
61+
CrewCode deliberately retains the full visible transcript as history; it is not
62+
the provider context. On authoritative completion, CrewCode clears the stale
63+
live context occupancy from memory, disk, and the latest visible usage strip
64+
without fabricating `0` tokens. The next CrewCoder usage report repopulates the
65+
meter with the compacted context's measured size.
5466

5567
CrewCoder emits genuine reasoning, so the Hermes cosmetic-thinking filter must
5668
not be applied. Gated tools are announced as pending before the permission
@@ -63,7 +75,9 @@ the bridge prefers that detail instead of appending a misleading generic error a
6375
failure.
6476

6577
CrewCoder ACP respects CrewCoder's persisted `autoCompact` setting. CrewCode does not force
66-
compaction or retry context-window failures. When automatic compaction is off, the user explicitly
78+
compaction or retry context-window failures. Automatic and provider-neutral safety compaction are
79+
reported live through `_crewcoder/compaction_update`, allowing CrewCode to show the compaction meter
80+
while CrewCoder summarizes in the background. When automatic compaction is off, the user explicitly
6781
runs `/compact` before continuing; this policy does not affect Pi or other providers.
6882

6983
A prompt has a ten-minute **inactivity** watchdog rather than a wall-clock turn

‎docs/current-state.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ Workspaces, worktrees, git operations, terminals, settings, and crew sessions ar
66

77
## CrewCoder
88

9-
CrewCoder is a first-class ACP provider implemented separately in `crewcoder-bridge.ts`; CrewCode is the client and spawns `crewcoder acp --approval review`. Keep Hermes untouched. CrewCoder is native-resume, discovers `provider:model` choices through `session/new`, maps namespaced usage `lastInputTokens` to live context occupancy, and uses once-only permission choices so remembered agent decisions cannot bypass later composer-mode changes. Its prompt watchdog measures ACP inactivity, not total turn duration, and pauses while Build permission is awaiting user input; a genuine timeout must send `session/cancel` before CrewCode ends the turn so another prompt cannot overlap live CrewCoder work. CrewCoder ACP must respect CrewCoder's persisted `autoCompact` setting; CrewCode must not force compaction or retry context-window failures for CrewCoder, Pi, or other providers. ACP `Internal error` responses can carry the actionable CrewCoder failure in `error.data.message`, which the bridge must prefer over the generic envelope text. Local ACP file reads currently use saved disk bytes while SSH reads/writes route through SFTP; do not claim dirty editor-buffer support until a renderer-host route exists. Session-scoped `externalDirectories` are synchronized after ACP new/load through `session/set_external_directories`, including `[]` to revoke stale native-session grants; changing them must restart the bridge. CrewCoder validates and persists the roots, while CrewCode's picker remains unavailable for SSH roots. It is deliberately excluded from disposable editor completion. See `docs/crewcoder-provider.md`.
9+
CrewCoder is a first-class ACP provider implemented separately in `crewcoder-bridge.ts`; CrewCode is the client and spawns `crewcoder acp --approval review`. Keep Hermes untouched. CrewCoder is native-resume, discovers `provider:model` choices through `session/new`, maps namespaced usage `lastInputTokens` to live context occupancy, reports authoritative background compaction lifecycle through `_crewcoder/compaction_update` (never duplicate it with usage-drop inference), clears stale context occupancy on successful compaction until the next measured usage while retaining the full CrewCode transcript as display history, and uses once-only permission choices so remembered agent decisions cannot bypass later composer-mode changes. Its prompt watchdog measures ACP inactivity, not total turn duration, and pauses while Build permission is awaiting user input; a genuine timeout must send `session/cancel` before CrewCode ends the turn so another prompt cannot overlap live CrewCoder work. CrewCoder ACP must respect CrewCoder's persisted `autoCompact` setting; CrewCode must not force compaction or retry context-window failures for CrewCoder, Pi, or other providers. ACP `Internal error` responses can carry the actionable CrewCoder failure in `error.data.message`, which the bridge must prefer over the generic envelope text. Local ACP file reads currently use saved disk bytes while SSH reads/writes route through SFTP; do not claim dirty editor-buffer support until a renderer-host route exists. Session-scoped `externalDirectories` are synchronized after ACP new/load through `session/set_external_directories`, including `[]` to revoke stale native-session grants; changing them must restart the bridge. CrewCoder validates and persists the roots, while CrewCode's picker remains unavailable for SSH roots. It is deliberately excluded from disposable editor completion. See `docs/crewcoder-provider.md`.
1010

1111
## ACP Grok Build
1212

@@ -24,9 +24,9 @@ Supervisor reporting is incremental, not batched: `useCrewSupervisor` feeds each
2424

2525
Task distribution (`session.distribution`, default `split`) is a live header toggle separate from `mode`. `split` = each worker gets a distinct sub-task: the supervisor's per-turn run-selection snapshot carries `distributionDirective()`, and `validateDirectivePolicy()` hard-blocks `"to":"all"`, targets that resolve to multiple workers, unavailable/skipped targets, and exact duplicate task text before dispatch. No-supervisor shared mode renders one composer per worker in `CrewTimeline`, and split timeline rounds show each lane's own prompt inside that lane card rather than collapsing to one shared prompt. `broadcast` = same message to all (`handleBroadcast`) and the supervisor may use `"to":"all"`. `set_distribution` is legal at any phase, so it can flip mid-run.
2626

27-
Crew control stops are scoped intentionally: `stop all` in `CrewSurface` aborts every runtime, the supervisor composer stop button calls `abortSupervisor()` only, and lane composer stop buttons call `restartLane()` for that lane only. The supervisor sidebar width is local UI state in `CrewSurface` and is resized with the shared `Splitter`; the supervisor thread also has a scroll-to-bottom affordance. Shared timeline lane groups (`crew-lane-group`) are locally collapsible with chevrons so dense multi-agent rounds remain scannable.
27+
Crew control stops are scoped intentionally: `stop all` in `CrewSurface` aborts every runtime, the supervisor composer stop button calls `abortSupervisor()` only, and lane composer stop buttons call `restartLane()` for that lane only. The per-lane enabled/paused switch is durable: pausing releases that runtime while retaining the worktree, transcript, and editable `nextAction`; every assignment seeds the checkpoint, restart recovery preserves it, and supervisor status snapshots include paused lanes without making them delegation targets. The supervisor sidebar width is local UI state in `CrewSurface` and is resized with the shared `Splitter`; the supervisor thread also has a scroll-to-bottom affordance. Shared timeline lane groups (`crew-lane-group`) are locally collapsible with chevrons so dense multi-agent rounds remain scannable. Every direct lane composer lazily supports `@` file search scoped to that lane's effective worktree/base path and auto-grows from one line to a bounded 220px before scrolling.
2828

29-
Isolated crew review treats clean Git merges as unverified. Cross-lane Diff shows branch/commit ownership, runtime state, exact file overlap, and narrow cross-file contract heuristics; the crew merge sidebar requires explicit acknowledgment when signals exist. Crew sessions persist locally so restart retains lane/worktree provenance while clearing process-local runtime ids. A merge audit is written before Git starts and recovers a leftover `running` operation as `interrupted`. After a clean merge, the sidebar discovers and visibly presents allowlisted package `typecheck`/`test` scripts; main runs only those discovered ids with `CI=1`, and persists pass/fail/interrupted evidence for local and SSH workspaces. See `docs/behavioral-merge-review.md`.
29+
Isolated crew review treats clean Git merges as unverified. Cross-lane Diff shows branch/commit ownership, runtime state, exact file overlap, and narrow cross-file contract heuristics; the crew merge sidebar requires explicit acknowledgment when signals exist. Crew sessions persist locally so restart retains lane/worktree provenance while clearing process-local runtime ids. Compare/Merge Git fetches are keyed to a stable ownership fingerprint rather than the once-per-second runtime/usage updates, preventing loaded review evidence from flashing back to a loading state. A merge audit is written before Git starts and recovers a leftover `running` operation as `interrupted`. After a clean merge, the sidebar discovers and visibly presents allowlisted package `typecheck`/`test` scripts; main runs only those discovered ids with `CI=1`, and persists pass/fail/interrupted evidence for local and SSH workspaces. See `docs/behavioral-merge-review.md`.
3030

3131
## Delegated Threads
3232

0 commit comments

Comments
 (0)