Skip to content

Self-hosted AI workspace.

Python

Merge frozen lab b1666951 (Wave 3) into Wave 4 effects provenance

Alexandre Teixeirada4bf3531f8b
diff --cc docs/runtime-decomposition/wave-4-effects-provenance-integration.md
index d0a175f7f,000000000..ce2c45858
mode 100644,000000..100644
--- a/docs/runtime-decomposition/wave-4-effects-provenance-integration.md
+++ b/docs/runtime-decomposition/wave-4-effects-provenance-integration.md
@@@ -1,305 -1,0 +1,327 @@@
+# Wave 4 effects, provenance, freshness and truthful completion
+
+Branch: `feature/effects-provenance-wave4`.
+Exact base: Wave 3 PR #60 head `80a962d96af5f85c785bd517ae6af8e90a8b0d38`
+(tree `bba4adfc9ff1628d96daeee57640be46a3f5d270`), clean at admission.
+Historical references: foundation `9012e208` (parent `1e3c50d2`),
+`wave-4-effects-provenance-foundation.md` and
+`wave-4-canonical-refresh-a80c164d.md` in the old worktree (read only).
+
+## Foundation decision: recreated, not cherry-picked
+
+`9012e208` was **not** cherry-picked. Its semantics were sound, but its types
+encoded assumptions that final Wave 3 made wrong:
+
+| Historical type | Problem against final Wave 3 | Recreated as |
+| --- | --- | --- |
+| `resource_keys: tuple[str, ...]` | Opaque string tokens; Wave 3 now has typed exact identities. Strings would make names/paths authority-shaped. | `ResourceRef`, built only by `resource_ref()` from typed Wave 3 objects; anything else is a `TypeError`. |
+| `may_have_changed: bool = False` | Defaults to "no impact"; conflates known no-op with unknown. | `Impact.NONE` only with `ExecutionOutcome.NOT_EXECUTED`; everything that reached a backend is `POSSIBLE`. |
+| `EffectStatus` (claimed/reported/verified/failed/unknown) | Mixes execution outcome with verification; one FAILED cannot carry "effect done, cleanup failed". | Separate `ExecutionOutcome`, `Impact`, `CleanupState`, and derived `EffectVerdict`. |
+| `verification_for` attestation | An adapter label asserted that an observation checked a postcondition. | `predicate_holds()` evaluates the explicit `Postcondition` against the observed state itself. |
+| `EvidenceOrigin` (3 labels) | Cannot express coverage, mechanism admission or lifecycle-only facts. | `ObservationMechanism` + `Coverage`; only admitted readback mechanisms can verify, per resource kind. |
+
+Preserved semantics: request ≠ admission ≠ dispatch ≠ execution ≠ verification;
+failed and unknown executions may have partially changed state; stale evidence
+stays historical and refresh appends; the newest check wins with no fallback to
+an earlier complete one; equal positions are rejected; unknown scope invalidates
+conservatively; receipts are never invalidated; matching state after unknown
+execution is observation, not causation.
+
+## Runtime chain
+
+```
+ExactOperation + Wave 3 bound operation (contextvars set by the dispatcher)
+ -> mark_dispatch(): durable EffectClaim (fsync) BEFORE execution_id/backend
+ -> backend invocation (unchanged producers)
+ -> record_action(): EffectOutcome from typed ProducerFacts (before receipt reduction)
+ -> admitted reads: Observation of the exact bound resource
+ -> EffectHistory: invalidation / freshness / assess()
+ -> EvidenceLedger.record_effects() -> existing evaluate() -> CompletionDecision
+ -> existing buffered presentation gate (completion_answer)
+```
+
+## Contracts (`src/agent_runtime/effects.py`)
+
+- `ResourceRef(kind, role, location, incarnation, snapshot_sha256)`. Location is
+ "where" including the sealed root/namespace identity; incarnation is the object
+ seen there. Kinds and their Wave 3 sources:
+ - filesystem: `FilesystemResource` — root scope/owner/path/device/inode + path;
+ incarnation = file/dir device:inode + ancestor-chain digest, or `absent:`.
+ - process: `ProcessResource` — namespace/owner/request/thread/PID/**start token**/role.
+ PID reuse is a different location.
+ - process_launch: `ProcessLaunchResource` — generation (the exact launch→job linkage
+ validated by `job_from_record`).
+ - background_job: `BackgroundJobResource` — job id + generation.
+ - owned: `OwnedResource` — namespace/owner/thread/collection/record; incarnation =
+ revision. `*` collection bindings overlap their records.
+ - external: `ExternalResource` — namespace/owner/endpoint/server/tool; incarnation.
+ - browser_session: `BrowserSessionResource` — owner/thread/session key; incarnation
+ = session incarnation. `BrowserPageResource` is refused.
+- `EffectClaim`: run/action identity, sequence, `OperationRef` (final normalized
+ tool/action/input digest/request), `impact_scope` (empty = unknown), `dependencies`,
+ `obligations` (each must target a claimed binding), `parent_run_id`, `external`.
+ No status field: a claim is intent, not dispatch.
+- `EffectOutcome`: `NOT_EXECUTED | REPORTED_SUCCESS | FAILED | TIMED_OUT | CANCELLED |
+ RUNNING | INTERRUPTED` (`ATTEMPTED` is derived for a claim without outcome), `Impact`,
+ bounded `ProducerFacts` (exact scalar types only), `CleanupState`, `replayed`.
+- `Observation`: exact resource, mechanism, coverage, source action/execution, `exists`,
+ complete-content digest. Admitted readbacks require their source action.
+- `EffectHistory`: unique positions; RUNNING may be followed by one settled outcome;
+ a settled outcome is never replaced.
+
+### Invalidation and freshness
+
+`invalidated_by(observation)` = later claims that may touch it (overlap or unknown
+scope; a refused no-op excluded) + later observations of the same location with a
+different incarnation (replacement). `freshness()` is STALE, UNSETTLED (an earlier
+overlapping effect was still attempted/running at observation time) or FRESH.
+Receipts/acknowledgements are never invalidated. Filesystem overlap is
+ancestor-or-self within one sealed root identity (listings, parents, rename-style
+dependencies); no alias discovery is attempted.
+
+### Verification
+
+`assess(claim)` per obligation uses the newest observation of the target **after
+settlement**, through a verifying mechanism for that kind (filesystem read, owned
+record read, remote readback). It must be FRESH, and the predicate must be decidable
+(partial coverage cannot decide content). Results: VERIFIED only with
+`REPORTED_SUCCESS`; STATE_OBSERVED for timed-out/cancelled/interrupted execution
+(causality unknown); FAILED execution never becomes success; CONTRADICTED when the
+fresh check is false; UNVERIFIED otherwise. Process ownership, job state, browser
+session, receipts and acknowledgements can stale evidence but never verify.
+
+## Durable persistence (`src/agent_runtime/effect_log.py`)
+
+- One append-only JSONL file per root run lineage under `DATA_DIR/effects`
+ (`0600`, directory `0700`, `O_NOFOLLOW`, `st_nlink == 1` required).
+- Every append takes an exclusive `flock` on the log, merges the durable records other
+ writers appended (repairing a torn tail left by a crashed writer), allocates the next
+ position from that merged tail, rejects a record the merged history makes invalid
+ (an outcome for an effect another writer already settled, a recovery outcome for a
+ claim another writer settled or marked RUNNING), then appends, fsyncs and releases.
+ Independent `EffectLog` objects, threads and processes therefore never reuse a
+ position and never settle an effect twice. `history()` merges others' records
+ under a shared lock.
+- `claim()` writes and fsyncs before returning; the first append of each log object
+ also fsyncs the log's directory, and every directory created for it is fsynced in
+ its parent, all under the lock and before the claim returns. A failed write or
+ directory fsync truncates the record back and raises
+ `EffectPersistenceError` (a `ResourceIdentityError`). `mark_dispatch` claims before
+ assigning `execution_id`, so the dispatcher returns BLOCKED and the backend is never
+ invoked; `dispatched()` closes the un-awaited coroutine.
+- Outcomes/observations are appended; a failed non-claim write sets `degraded` (the
+ on-disk claim then replays as unknown). Claim-free (read-only) runs create no file.
+- `load()` validates every record strictly, tolerates only a torn final line, and
+ fails closed on corruption, forged enum values, inconsistent history or aliasing.
+ `recover_interrupted()` appends INTERRUPTED/possible-impact outcomes for unsettled
+ claims, leaves RUNNING alone, and is idempotent. `open()` returns the live log or the
+ recovered durable one.
+- `launch-<generation>.json` maps a background launch generation to its claim so a
+ later run can settle it: temp file written and fsynced, `os.replace`d, then the
+ directory fsynced. Durability is POSIX-only (`flock`, directory fsync); neither is
+ claimed elsewhere.
+- The store is a Wave 3 control-plane path (prefix check), so filesystem tools cannot
+ read or write it. Hardlink aliases are caught by `_aliases_effect_store`: logs and
+ index files refuse `st_nlink != 1` and the store is flat, so only a multiply linked
+ regular file on the store's device is checked, by inode, against one non-recursive
+ listing. The store is never added to the recursive control-plane inventory, so cost
+ never grows with accumulated runs. Existing containment/process/job stores are not
+ reused.
+
+## Adapters (`src/agent_runtime/effect_adapters.py`)
+
+Inputs are only the bound operations live at `mark_dispatch` (filesystem, owned,
+process, backend, browser). Classification failure claims unknown scope; it never
+blocks dispatch.
+
+| Family | Claim | Observations / settlement | Verification available |
+| --- | --- | --- | --- |
+| Filesystem write/edit/patch | exact bindings; CONTENT_SHA256 of the exact bytes the producer's own transformation writes: `write_file` after fence unwrapping, `edit_file` via the shared pure `_edit_file_text` on the identity-checked pre-state (no newline translation), `apply_patch` add=content / delete=ABSENT / update=`_apply_patch_hunks` on the universal-newline pre-state. If any target's state cannot be derived (unreadable, oversized, undecodable, non-`\n` platform, hunk mismatch) the claim carries no postcondition and stays UNVERIFIED | — | via later admitted complete `read_file` |
+| `read_file` | none (admitted read) | re-reads the exact bound source (identity checked before/after) → COMPLETE digest, or PARTIAL for offset/limit/truncation/structured extraction | decides predicates when COMPLETE |
+| `ls`/`glob`/`grep` | none | PARTIAL existence of the search root | existence only |
+| bash/python launch | unknown scope + launch generation dependency | outcome from containment envelope: TIMED_OUT (`timed_out`), cleanup from `teardown.dead`, RUNNING for `bg_job_id` with a launch reservation, or the host bridge's server-set `detached` | none (process exit is not a postcondition) |
+| `manage_bg_jobs` read | none | JOB_STATE observation; settles the RUNNING launch of the exact generation | none |
+| `manage_bg_jobs` kill | job + its processes | settles the launch as CANCELLED | none |
+| Owned mutation | exact revisioned records (+attachments as dependencies) | — | none (no independent readback contract) |
+| Owned reads (`vault_get`, ...) | none | PARTIAL OWNED_RECORD_READ per exact revision | existence only |
+| External/MCP | external backend ref, `external=True`; `remote_acknowledged` on exit 0 | none | none: no independent authorized readback exists, so it stays UNVERIFIED |
+| Browser `session_info` | none | BROWSER_SESSION lifecycle observation of the session incarnation | none |
+| Unbound tools (incl. `manage_tasks`) | unknown scope | — | none |
+
+Producer seams added: `job` lifecycle facts on job reads/kills
+(`job_lifecycle_facts`), `timed_out` on containment timeouts, and
+`mutation_attempted` when `write_file`/`edit_file` fail after their truncating open.
+
+Trust boundary: result keys carry lifecycle meaning only from the producer the
+dispatcher actually bound. An unbound dynamic/registry tool contributes its exit
+status alone (`ProducerFacts(exit_code=...)`); the MCP bridge builds only
+stdout/stderr/exit_code, and `external`/`remote_acknowledged` come from the captured
+`ExternalResource`, not the result. RUNNING requires a bound process producer (and a
+launch reservation for `bg_job_id`); cleanup is attested only by a bound process
+producer; job settlement only by a bound `manage_bg_jobs` read/kill of exactly one
+Wave 3-validated job.
+
+## Completion integration
+
+No second policy. `completion._ledger()` builds the single `EvidenceLedger` used for
+the decision, `ask_user` filtering and prose filtering, then calls
+`record_effects(entries, action_order, partial_reads)`. Effects change the existing
+`evaluate()` as follows:
+
+- a fresh contradicting readback of a required artifact → FAILED;
+- a required artifact is **unsettled** (BLOCKED, "a later operation may have changed a
+ required artifact without settled evidence") when, after its last successful
+ mutation, an effect with unresolved impact may have touched it: explicit targets
+ with unknown/cancelled/timed-out outcomes or failures after `mutation_attempted`;
+ unknown-scope effects that were cancelled/interrupted, still RUNNING, or failed
+ teardown. Settled shell changes remain tracked by existing artifact version capture;
+- partial `read_file` validation events become non-authoritative;
+- `_supports_artifact_claim` applies the same rules, so prose cannot claim the write;
+- with or without declared artifacts, the **latest** effect on any changed file being
+ contradicted by a fresh readback → FAILED (a superseded earlier effect is history);
+- a passing verifier followed by an effect that may have changed state without
+ settled evidence → BLOCKED (the verifier is stale);
+- executed external effects that are not VERIFIED cap the decision at UNVERIFIED
+ (`EXTERNAL_EFFECT_UNVERIFIED`; the run may still end), and `completion_answer`
+ always appends server-authored facts for them ("reported success; any external
+ change it made was not independently verified", "reported failure", "unknown outcome"). This
+ disclosure is structural: it does not depend on recognizing the model's wording.
+ Prose filtering is additionally tightened (remote verbs are mutation claims; an
+ unnamed "I updated it" cannot borrow the single required artifact; bare "Done." is
+ a terminal claim) but is not relied on. A passing verifier still supports test
+ claims beside an unverified external effect; it never speaks for that effect.
+
+A RUNNING background launch alone does not block a run without declared obligations:
+it completes UNVERIFIED.
+
+Ordinary conversation and read-only synthesis are unchanged (no claims, no file).
+`effect_assessments` are added to terminal metrics metadata.
+
+## Browser, scheduler and background
+
+Browser page/document operations still fail closed before dispatch (verified through
+the real dispatcher with effects enabled: no claim, never dispatched). Only
+`session_info` produces session lifecycle observations; replacement stales them.
+
+The background monitor, after its existing `job_from_record` + `validate_job`, settles
+the exact launch claim from the server-owned record's typed lifecycle facts
+(idempotent across retries). The delivered report remains untrusted attributed
+content; it is never an observation. Scheduler triggers are unknown-scope claims
+whose replies verify nothing; scheduled runs use their own journals/logs.
+
+## Files
+
+Production: `effects.py`, `effect_log.py`, `effect_adapters.py` (new);
+`journal.py`, `completion.py`, `agent_evidence.py`, `bg_monitor.py`,
+`agent_tools/{filesystem_tools,subprocess_tools,bg_job_tools}.py` (seams);
+`resources.py` (effect store added to control-plane paths; strengthening only).
+Not changed: `authority.py`, containment, process ownership/reaper, browser
+authority, context resolution, runtime selection, agent loop.
+
+Tests: `test_effects_foundation.py` (recreated), `test_effect_journal_persistence.py`,
+`test_effect_resource_bindings.py` (real dispatcher), `test_effect_verification_adapters.py`;
+`tests/conftest.py` redirects the store to a session tmp directory.
+
+## Residual limitations (none weakens authority or manufactures success)
+
+- **P2 durable integrity:** records carry no MAC. A writer with access to `DATA_DIR`
+ outside the tool layer could forge records that a later `load()` accepts — the same
+ trust class as the existing job/containment stores.
+- **P2 concurrent recovery:** a process that opens a log not live in that process
+ recovers its unsettled claims as INTERRUPTED. If the owning run is live in another
+ process at that moment, its later settlement is rejected as a replacement and the
+ effect stays INTERRUPTED (unknown, never success).
+- **P2 unobserved writers:** freshness is relative to recorded history; an external
+ change after the last observation is detected only by a new observation.
+- **P2 scope of verification:** VERIFIED is reachable only for filesystem effects.
+ Owned/external effects have no independent readback contract and stay UNVERIFIED.
+- **P2 conservatism:** unbound tools are unknown scope, so cancelling/interrupting
+ even a read-only unbound tool, or a RUNNING background job, blocks later-unsettled
+ required artifacts until a new successful mutation.
+- **P2 replay is lazy:** interrupted claims are recovered when a log is opened (e.g.
+ background settlement); there is no startup scan. Unopened claims remain on disk
+ as unsettled (assessed PENDING/unknown, never success).
+- **P2 retention:** no pruning of effect logs or launch index files.
+
+## Corrective pass (adversarial review verdict B)
+
+| Finding | Disposition |
+| --- | --- |
+| P0-1 log creation lacked directory fsync | Fixed: created directories and the log's entry are fsynced under the lock before the first claim returns; a failed directory fsync rolls the record back and refuses dispatch. |
+| P0-2 `edit_file` verified from existence | Fixed: exact final-content digest from the producer's own pure transformation. A generic "content changed" predicate was rejected: an unrelated write satisfies it. |
+| P0-3 `apply_patch` update verified without the patch | Fixed as P0-2 (universal-newline pre-state, shared hunk application); an underivable target drops all postconditions. |
+| P0-4 unsupported external/MCP prose survived | Fixed structurally: decision cap + mandatory server disclosure; regex tightening is secondary. |
+| P0-5 empty `required_artifacts` bypassed effect obligations | Fixed: latest-effect contradiction, verifier staleness and the external cap apply regardless of declared artifacts. A blanket "any RUNNING effect blocks" rule was rejected (it blocks legitimate background launches and fails runs on superseded effects). |
+| P1-1 result dictionaries influenced RUNNING/cleanup | Fixed: facts scoped to the bound producer (see Adapters). |
+| P1-2 launch index lacked directory fsync | Fixed: fsync temp → replace → fsync directory. |
+| P1-3 `EffectLog.open` not thread-safe | Fixed: `_OPEN_LOCK` around the live check and load; correctness no longer depends on it (file lock + merge). |
+| P1-4 hardlink protection incomplete | Fixed without inventorying the store: `_aliases_effect_store`. |
+| P1-5 child unknown-scope invalidation | Rejected as intended: an unknown-scope child (e.g. a shell command) runs on the parent's host and can change any parent resource, so invalidation is required. Known-scope child effects invalidate only overlapping resources (regression test). |
+| P1-6 concurrent settlement could duplicate sequences | Fixed: lock → merge durable tail → allocate → validate → append → fsync. |
+
+## Wave 3 rebase compatibility checklist
+
+Overlap with the corrective range is `resources.py`, `bg_monitor.py` and
+`subprocess_tools.py`. Trial `git merge-tree` onto `bf697084`: the original candidate
+merges textually clean; the corrected series conflicts in `resources.py` only. After
+the rebase:
+
+1. `resources.py`: Wave 3 splits `_control_plane_path` into `_control_plane_snapshot()`
+ and `_control_plane_path(path, *, snapshot=None)`. **Semantic conflict even where
+ the text merges:** the Wave 4 effect-store prefix check
+ (`if any(Path(path).is_relative_to(d) for d in effect_dirs): return True`) lands
+ inside `_control_plane_snapshot()`, which has no `path` (NameError on first use).
+ This is true of the original candidate's "clean" merge as well. Resolve by putting
+ `_effect_store_dirs()` into the snapshot's prefix `directories` (not the rglob
+ inventory), and calling `_aliases_effect_store(candidate, effect_dirs)` after the
+ candidate `os.stat` in `_control_plane_path` (it needs `st_nlink`, which the identity
+ set does not carry). Keep the alias check per call, not snapshotted: it reads one
+ flat directory, only for multiply linked candidates.
+2. `bg_monitor._run_followup`: Wave 3 returns `FollowupResult`, makes linkage and
+ authority mismatches terminal, and revalidates after the drain. Keep
+ `_settle_launch_effect(resource, rec)` immediately after the first successful
+ `validate_job`, before the authority comparison: settlement is execution evidence
+ from the validated identity only. Confirm a TERMINAL_UNFOLLOWABLE job still settles
+ and that `mark_unfollowable` retirement does not block settlement on later retries.
+3. Launch publication retirement (`retire_launch(..., job=)`,
+ `prune_foreground_publications`): confirm `job_from_record`/`validate_job` still
+ validate a finished background job after its publication is retired, and that the
+ job record keeps the exact launch `generation` used as claim lineage. Otherwise a
+ launch claim stays RUNNING (conservative, but it blocks later artifacts).
+4. `subprocess_tools._run_owned_command`: Wave 3's `finally` retirement block sits
+ next to Wave 4's `"timed_out": True` hunk; keep both.
+5. Process launch validation cost/identity changes (`e23b9b39`, `7445ba70`): confirm
+ `ProcessLaunchResource`/`BackgroundJobResource` fields used by `resource_ref`
+ (`namespace, owner, request_id, thread_id, generation, job_id`) and `to_dict()` are
+ unchanged, and that native `#!bg` launches still bind `process.launch` (RUNNING
+ gating depends on it).
+6. Native local-control capability authorization and scheduled backend authority:
+ confirm newly authorized operations still reach the backend through
+ `dispatched()`/`mark_dispatch`, so each gets a durable claim before invocation, and
+ that no new path invokes a backend outside it.
+7. Diagnostics: Wave 3's preserved resource-denial diagnostics must stay pre-dispatch
+ refusals (no claim, no execution id).
+8. Rerun the four Wave 4 suites plus `test_runtime_resource_integration.py` and the
+ `test_wave3_*` suites on the rebased tree.
++
++## Integration with frozen lab `b1666951` (Wave 3 merged)
++
++Merged (not rebased) so the Wave 4 commit SHAs are preserved. Resolution:
++
++- `resources.py`: Wave 3's `_control_plane_snapshot()` / `_control_plane_path(path, *, snapshot=None)`
++ architecture is kept. The snapshot computes `_effect_store_dirs()` and adds them to
++ the returned prefix directories only after the recursive `job_dirs` inventory, and
++ never references `path`. `_control_plane_path` checks inventoried identities after
++ its `os.stat`, then calls `_aliases_effect_store` only for `st_nlink > 1`.
++- `bg_monitor.py`: settlement stays immediately after the first successful
++ `validate_job`, before the authority comparison; Wave 3's post-drain revalidation is
++ unchanged. The deleted-session branch (terminal before linkage validation) now also
++ settles a validated launch, because that job is later pruned and its publication
++ retired, which would otherwise leave its effect RUNNING.
++- Background publication is retired only by `bg_jobs._prune`, after a job is followed
++ up or terminal-unfollowable, so every path that reaches retirement has already had
++ its settlement attempt. A job with invalid linkage is never settled (no authority).
++- Scheduled builtin actions (e.g. `cookbook_serve`) run in the scheduler outside any
++ agent journal and never reached `mark_dispatch`; Wave 3 only added their backend
++ authority. Agent-dispatched local control (`download_model`, `serve_model`,
++ `serve_preset`) is claimed by `dispatched()` before its handler mints a capability.
diff --cc src/agent_runtime/resources.py
index df3c9100b,03006024c..701a381fd
--- a/src/agent_runtime/resources.py
+++ b/src/agent_runtime/resources.py
@@@ -28,46 -28,7 +28,46 @@@ def _absolute(value)
raise ValueError("Resource path must be canonical and absolute")
+def _effect_store_dirs():
+ from src import constants
+ directories = {canonical_root(os.path.join(constants.DATA_DIR, "effects"))}
+ effect_log = sys.modules.get("src.agent_runtime.effect_log")
+ if effect_log is not None:
+ directories.add(canonical_root(effect_log.EFFECTS_DIR))
+ return directories
+
+
+def _aliases_effect_store(candidate, directories):
+ """Whether ``candidate`` (an ``os.stat`` result) is a hardlink into the effect store.
+
+ The effect log and launch index refuse any file with more than one link,
+ and the store is flat. So only a multiply linked regular file on the
+ store's device can alias store state, and only then is the store listed,
+ one directory level, by inode. Ordinary single-link files cost nothing,
+ and the cost never depends on recursive store size. Uninspectable store
+ state fails closed.
+ """
+ if not stat.S_ISREG(candidate.st_mode) or candidate.st_nlink < 2:
+ return False
+ for directory in directories:
+ try:
+ if os.stat(directory).st_dev != candidate.st_dev:
+ continue
+ with os.scandir(directory) as entries:
+ for entry in entries:
+ if entry.inode() != candidate.st_ino:
+ continue
+ observed = entry.stat(follow_symlinks=False)
+ if (observed.st_dev, observed.st_ino) == (candidate.st_dev, candidate.st_ino):
+ return True
+ except FileNotFoundError:
+ continue
+ except OSError:
+ return True
+ return False
+
+
- def _control_plane_path(path):
+ def _control_plane_snapshot():
# Execution snapshots/receipts are server state, even if a workspace root
# contains the data directory. A writable user file cannot mint authority.
from src import constants
@@@ -84,12 -45,6 +84,10 @@@
processes = sys.modules.get("src.agent_runtime.process_resources")
if processes is not None:
job_dirs.add(canonical_root(processes._LAUNCH_DIR))
+ # Durable effect claims/outcomes/observations are server evidence state.
- # The store is not inventoried here: it grows with every run. Aliases are
- # caught below by ``_aliases_effect_store`` instead.
++ # They are prefix-protected below, but never inventoried: the store grows
++ # with every run. Hardlink aliases are caught by ``_aliases_effect_store``.
+ effect_dirs = _effect_store_dirs()
- if any(Path(path).is_relative_to(directory) for directory in effect_dirs):
- return True
# Producers may have configured paths different from the default constants.
# Inspect already-loaded server metadata without initializing a store here.
bg = sys.modules.get("src.bg_jobs")
@@@ -128,22 -81,28 +124,32 @@@
for suffix in ("-wal", "-shm", "-journal"))
protected.add(canonical_root(Path(constants.DATA_DIR) / ".app_key"))
protected.add(canonical_root(Path(constants.UPLOAD_DIR) / "uploads.json"))
- if path in protected:
+ identities = set()
+ for control in protected:
+ try:
+ observed = os.stat(control)
+ except FileNotFoundError:
+ continue
+ identities.add((observed.st_dev, observed.st_ino))
- return frozenset(job_dirs), frozenset(protected), frozenset(identities)
++ # Effect directories join the prefix set only after the recursive inventory.
++ return frozenset(job_dirs | effect_dirs), frozenset(protected), frozenset(identities)
+
+
+ def _control_plane_path(path, *, snapshot=None):
+ # A scan-local snapshot bounds repeated hardlink checks. Ordinary resource
+ # resolution always observes fresh state. Neither form is an atomic kernel
+ # access policy, and snapshots must never survive a workspace guard call.
+ directories, protected, identities = _control_plane_snapshot() if snapshot is None else snapshot
+ if any(Path(path).is_relative_to(directory) for directory in directories) or path in protected:
return True
try:
candidate = os.stat(path)
except FileNotFoundError:
return False
- if _aliases_effect_store(candidate, effect_dirs):
- return (candidate.st_dev, candidate.st_ino) in identities
++ if (candidate.st_dev, candidate.st_ino) in identities:
+ return True
- for control in protected:
- try:
- observed = os.stat(control)
- except FileNotFoundError:
- continue
- if (candidate.st_dev, candidate.st_ino) == (observed.st_dev, observed.st_ino):
- return True
- return False
++ # Only a multiply linked file can alias the (uninventoried) effect store.
++ return candidate.st_nlink > 1 and _aliases_effect_store(candidate, directories & _effect_store_dirs())
class FilesystemScope(str, Enum):
diff --cc src/bg_monitor.py
index 790783bc9,28f7f2225..9d0c7d2bb
--- a/src/bg_monitor.py
+++ b/src/bg_monitor.py
@@@ -135,7 -124,7 +140,17 @@@ async def _run_followup(rec: dict) -> F
# Session was deleted — nothing to continue. Consider it handled so we
# don't retry forever.
logger.info("bg-followup: session %s gone for job %s — skipping", rec.get("session_id"), rec.get("id"))
- return True
++ # The job is retired without a continuation, then pruned with its
++ # publication. Settle its launch effect first so it is not left RUNNING.
++ from src.agent_runtime.process_resources import job_from_record, validate_job
++ try:
++ resource = job_from_record(rec)
++ validate_job(resource)
++ except (ValueError, TypeError, OSError, RuntimeError):
++ pass # no validated linkage: nothing may be settled
++ else:
++ _settle_launch_effect(resource, rec)
+ return FollowupResult.TERMINAL_UNFOLLOWABLE
# Don't write into a session that's mid-stream. The followup appends to
# history + save_sessions(); a concurrent live turn does the same, and with
@@@ -162,14 -148,21 +174,22 @@@
try:
resource = job_from_record(rec)
validate_job(resource)
+ _settle_launch_effect(resource, rec)
if not authority.grants or (resource.owner, resource.thread_id, resource.request_id) != (
str(getattr(sess, "owner", None) or "").strip().casefold(), sess.id, authority.request_id):
- return False
+ return FollowupResult.TERMINAL_UNFOLLOWABLE
except (ValueError, TypeError, OSError, RuntimeError):
- return False
+ return FollowupResult.TERMINAL_UNFOLLOWABLE
+ context = sess.get_context_messages()
+ context.append(_background_result_message(rec))
authority = authority.restrict(disabled_tools=get_setting("disabled_tools", []) or ())
full, tool_events = await _drain_agent(sess, context, request_authority=authority)
+ # An awaited continuation must not deliver a result after its immutable
+ # linkage disappears or is replaced. This check grants no new authority.
+ try:
+ validate_job(resource)
+ except (ValueError, TypeError, OSError, RuntimeError):
+ return FollowupResult.TERMINAL_UNFOLLOWABLE
# Persist ONLY the assistant continuation so it renders as a normal agent
# turn — a standard chat bubble plus `tool_events` that the frontend
diff --cc tests/test_effect_journal_persistence.py
index c733deb85,000000000..56dac58d4
mode 100644,000000..100644
--- a/tests/test_effect_journal_persistence.py
+++ b/tests/test_effect_journal_persistence.py
@@@ -1,337 -1,0 +1,345 @@@
+"""Durable Wave 4 effect log: pre-invocation claims, append-only replay."""
+from __future__ import annotations
+
+import json
+import os
+
+import pytest
+
+from src.agent_runtime import effects as fx
+from src.agent_runtime.effect_log import EffectLog, EffectPersistenceError
+from src.agent_runtime.resources import FilesystemResource, FilesystemRoot, OwnedResource
+
+
+RUN = "a" * 32
+
+
+def target(tmp_path):
+ workspace = tmp_path / "ws"
+ workspace.mkdir()
+ root = FilesystemRoot.seal(str(workspace))
+ return fx.resource_ref(FilesystemResource.resolve(root, str(workspace / "a.txt"), allow_missing=True), "destination")
+
+
+def claim(log, target, effect_id="e1", action_id="act-1"):
+ return log.claim(effect_id=effect_id, action_id=action_id, operation=fx.OperationRef("write_file", "", "0" * 64),
+ impact_scope=(target,), obligations=(fx.Postcondition(target, fx.Predicate.EXISTS),))
+
+
+def records(path):
+ return [json.loads(line) for line in path.read_text().splitlines()]
+
+
+def test_claim_is_fsynced_to_disk_before_returning(tmp_path, target, monkeypatch):
+ synced = []
+ real_fsync = os.fsync
+ monkeypatch.setattr(os, "fsync", lambda fd: (synced.append(fd), real_fsync(fd)))
+ log = EffectLog(RUN, directory=tmp_path / "fx")
+ made = claim(log, target)
+ assert synced, "claim must be fsynced before the caller can invoke a backend"
+ on_disk = records(log.path)
+ assert [r["type"] for r in on_disk] == ["claim"]
+ assert fx.EffectClaim.from_dict(on_disk[0]["record"]) == made
+ assert oct(log.path.stat().st_mode & 0o777) == "0o600"
+
+
+def test_claim_persistence_failure_raises_and_records_nothing(tmp_path, target):
+ blocker = tmp_path / "not-a-directory"
+ blocker.write_text("x")
+ log = EffectLog(RUN, directory=blocker)
+ with pytest.raises(EffectPersistenceError):
+ claim(log, target)
+ assert log.history().claims == ()
+
+
+def test_non_claim_failure_degrades_without_losing_in_memory_truth(tmp_path, target, monkeypatch):
+ log = EffectLog(RUN, directory=tmp_path / "fx")
+ made = claim(log, target)
+ monkeypatch.setattr(log, "_write", lambda kind, record: (_ for _ in ()).throw(OSError("disk full")))
+ log.outcome(effect_id=made.effect_id, execution=fx.ExecutionOutcome.REPORTED_SUCCESS, impact=fx.Impact.POSSIBLE)
+ assert log.degraded
+ assert fx.assess(made, log.history()).execution is fx.ExecutionOutcome.REPORTED_SUCCESS
+ # Replay only sees the durable claim: it stays unknown, never success.
+ reloaded = EffectLog.load(RUN, directory=tmp_path / "fx")
+ assert fx.assess(made, reloaded.history()).verdict is fx.EffectVerdict.PENDING
+
+
+def test_replay_after_restart_marks_unsettled_claims_interrupted(tmp_path, target):
+ directory = tmp_path / "fx"
+ log = EffectLog(RUN, directory=directory)
+ settled = claim(log, target, "e1", "a1")
+ log.outcome(effect_id="e1", execution=fx.ExecutionOutcome.REPORTED_SUCCESS, impact=fx.Impact.POSSIBLE,
+ execution_id="a1:x")
+ log.observe(observation_id="o1", resource=target, mechanism=fx.ObservationMechanism.FILESYSTEM_READ,
+ coverage=fx.Coverage.COMPLETE, source_action_id="r1", exists=True)
+ pending = claim(log, target, "e2", "a2")
+ del log # process "crashes" before e2 settles
+
+ reloaded = EffectLog.load(RUN, directory=directory)
+ assert fx.assess(settled, reloaded.history()).verdict is fx.EffectVerdict.UNVERIFIED # e2 made o1 stale
+ appended = reloaded.recover_interrupted()
+ assert [(o.effect_id, o.execution, o.impact, o.replayed) for o in appended] == [
+ ("e2", fx.ExecutionOutcome.INTERRUPTED, fx.Impact.POSSIBLE, True)]
+ assessment = fx.assess(pending, reloaded.history())
+ assert assessment.verdict is fx.EffectVerdict.UNVERIFIED and assessment.unresolved_impact
+ # Recovery is append-only and idempotent across another restart.
+ again = EffectLog.load(RUN, directory=directory)
+ assert again.recover_interrupted() == ()
+ assert [r["type"] for r in records(again.path)] == ["claim", "outcome", "observation", "claim", "outcome"]
+
+
+def test_running_background_claim_is_not_converted_by_replay(tmp_path, target):
+ log = EffectLog(RUN, directory=tmp_path / "fx")
+ made = claim(log, target)
+ log.outcome(effect_id=made.effect_id, execution=fx.ExecutionOutcome.RUNNING, impact=fx.Impact.POSSIBLE)
+ reloaded = EffectLog.load(RUN, directory=tmp_path / "fx")
+ assert reloaded.recover_interrupted() == ()
+ assert fx.assess(made, reloaded.history()).verdict is fx.EffectVerdict.PENDING
+
+
+def test_torn_final_write_is_ignored_but_corruption_fails_closed(tmp_path, target):
+ directory = tmp_path / "fx"
+ log = EffectLog(RUN, directory=directory)
+ claim(log, target)
+ with open(log.path, "ab") as stream:
+ stream.write(b'{"v":1,"type":"outcome","rec') # crash mid-append
+ assert len(EffectLog.load(RUN, directory=directory).history().claims) == 1
+ with open(log.path, "ab") as stream:
+ stream.write(b'\n{"v":1,"type":"outcome","record":{"forged":true}}\n')
+ with pytest.raises(EffectPersistenceError):
+ EffectLog.load(RUN, directory=directory)
+
+
+def test_forged_success_record_cannot_be_replayed_into_verification(tmp_path, target):
+ directory = tmp_path / "fx"
+ log = EffectLog(RUN, directory=directory)
+ made = claim(log, target)
+ forged = {"v": 1, "type": "outcome", "record": {**fx.EffectOutcome(
+ made.effect_id, 2, fx.ExecutionOutcome.FAILED, fx.Impact.POSSIBLE).to_dict(), "execution": "verified"}}
+ with open(log.path, "a") as stream:
+ stream.write(json.dumps(forged) + "\n")
+ with pytest.raises(EffectPersistenceError):
+ EffectLog.load(RUN, directory=directory)
+
+
+def test_hardlinked_log_is_refused(tmp_path, target):
+ directory = tmp_path / "fx"
+ log = EffectLog(RUN, directory=directory)
+ claim(log, target)
+ os.link(log.path, tmp_path / "alias.jsonl")
+ with pytest.raises(EffectPersistenceError):
+ EffectLog.load(RUN, directory=directory)
+ with pytest.raises(EffectPersistenceError):
+ claim(log, target, "e2", "a2")
+
+
+def test_read_only_runs_write_no_file(tmp_path, target):
+ log = EffectLog(RUN, directory=tmp_path / "fx")
+ log.observe(observation_id="o1", resource=target, mechanism=fx.ObservationMechanism.FILESYSTEM_READ,
+ coverage=fx.Coverage.PARTIAL, source_action_id="r1", exists=True)
+ assert not log.path.exists() and len(log.history().observations) == 1
+
+
+def test_run_identifier_must_be_server_generated(tmp_path):
+ for forged in ("../escape", "", "A" * 32, "a" * 31):
+ with pytest.raises(ValueError):
+ EffectLog(forged, directory=tmp_path)
+
+
+def test_effect_store_is_server_control_state(tmp_path):
+ from src.agent_runtime import effect_log
+ store = effect_log.effects_dir()
+ store.mkdir(parents=True, exist_ok=True)
+ root = FilesystemRoot.seal(str(store.parent))
+ with pytest.raises(ValueError, match="sensitive"):
+ FilesystemResource.resolve(root, str(store / ("b" * 32 + ".jsonl")), allow_missing=True)
+
+
+def test_owned_revision_scope_round_trips(tmp_path):
+ record = fx.resource_ref(OwnedResource("notes", "u", "t", "notes", "n1", "rev-1"), "record")
+ log = EffectLog(RUN, directory=tmp_path / "fx")
+ log.claim(effect_id="e1", action_id="a1", operation=fx.OperationRef("manage_notes", "", "0" * 64),
+ impact_scope=(record,))
+ assert EffectLog.load(RUN, directory=tmp_path / "fx").history().claims[0].impact_scope == (record,)
+
+
+# -- crash durability ----------------------------------------------------------
+
+def synced(monkeypatch, events):
+ """Record the path each real fsync makes durable, in call order."""
+ real_fsync = os.fsync
+ monkeypatch.setattr(os, "fsync", lambda fd: (events.append(os.readlink(f"/proc/self/fd/{fd}")),
+ real_fsync(fd))[1])
+
+
[email protected](not os.path.isdir("/proc/self/fd"), reason="needs /proc fd paths")
+def test_created_directories_are_synced_before_the_claim_returns(tmp_path, target, monkeypatch):
+ events = []
+ synced(monkeypatch, events)
+ log = EffectLog(RUN, directory=tmp_path / "new" / "fx")
+ claim(log, target)
+ # Each newly created directory entry, then the record, then the log's entry.
+ assert events == [str(tmp_path), str(tmp_path / "new"), str(log.path), str(tmp_path / "new" / "fx")]
+ events.clear()
+ claim(log, target, "e2", "a2")
+ assert events == [str(log.path)], "later appends need only the record fsync"
+
+
[email protected](not os.path.isdir("/proc/self/fd"), reason="needs /proc fd paths")
+def test_launch_index_is_synced_written_replaced_then_directory_synced(tmp_path, target, monkeypatch):
+ log = EffectLog(RUN, directory=tmp_path / "fx")
+ claim(log, target)
+ events = []
+ synced(monkeypatch, events)
+ real_replace = os.replace
+ monkeypatch.setattr(os, "replace", lambda a, b: (events.append("replace"), real_replace(a, b))[1])
+ log.index_launch("d" * 32, "e1")
+ assert events == [str(tmp_path / "fx" / ("launch-" + "d" * 32 + ".tmp")), "replace", str(tmp_path / "fx")]
+ assert EffectLog.launch_owner("d" * 32, directory=tmp_path / "fx") == (RUN, "e1")
+
+
+def test_torn_tail_from_a_crashed_writer_is_repaired_before_the_next_append(tmp_path, target):
+ directory = tmp_path / "fx"
+ claim(EffectLog(RUN, directory=directory), target)
+ with open(directory / f"{RUN}.jsonl", "ab") as stream:
+ stream.write(b'{"v":1,"type":"claim","rec') # crash mid-append
+ survivor = EffectLog.load(RUN, directory=directory)
+ claim(survivor, target, "e2", "a2")
+ reloaded = EffectLog.load(RUN, directory=directory)
+ assert [c.effect_id for c in reloaded.history().claims] == ["e1", "e2"]
+ assert all(line.startswith("{") for line in (directory / f"{RUN}.jsonl").read_text().splitlines())
+
+
+# -- concurrent writers --------------------------------------------------------
+
+def test_independent_logs_allocate_from_the_durable_tail(tmp_path, target):
+ directory = tmp_path / "fx"
+ first, second = EffectLog(RUN, directory=directory), EffectLog(RUN, directory=directory)
+ claim(first, target, "e1", "a1")
+ claim(second, target, "e2", "a2") # second never saw e1 in memory
+ claim(first, target, "e3", "a3")
+ positions = [r.sequence for r in (*EffectLog.load(RUN, directory=directory).history().claims,)]
+ assert positions == [1, 2, 3]
+ assert [c.effect_id for c in first.history().claims] == ["e1", "e2", "e3"]
+
+
+def test_threads_with_separate_logs_never_duplicate_positions(tmp_path, target):
+ import threading
+ directory = tmp_path / "fx"
+ logs = [EffectLog(RUN, directory=directory) for _ in range(4)]
+ barrier = threading.Barrier(len(logs))
+
+ def append(index, log):
+ barrier.wait()
+ for n in range(25):
+ claim(log, target, f"e{index}-{n}", f"a{index}-{n}")
+
+ threads = [threading.Thread(target=append, args=(i, log)) for i, log in enumerate(logs)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+ history = EffectLog.load(RUN, directory=directory).history()
+ assert sorted(c.sequence for c in history.claims) == list(range(1, 101))
+
+
+_WRITER = """
+import sys
+from pathlib import Path
+from src.agent_runtime import effects as fx
+from src.agent_runtime.effect_log import EffectLog
+from src.agent_runtime.resources import FilesystemResource, FilesystemRoot
+directory, workspace, index = Path(sys.argv[1]), sys.argv[2], sys.argv[3]
+root = FilesystemRoot.seal(workspace)
+target = fx.resource_ref(FilesystemResource.resolve(root, workspace + "/a.txt", allow_missing=True), "destination")
+log = EffectLog(sys.argv[4], directory=directory)
+for n in range(40):
+ log.claim(effect_id=f"p{index}-{n}", action_id=f"a{index}-{n}",
+ operation=fx.OperationRef("write_file", "", "0" * 64), impact_scope=(target,))
+"""
+
+
+def test_independent_processes_never_duplicate_positions(tmp_path, target):
+ import subprocess
+ import sys
+ from pathlib import Path
+ directory = tmp_path / "fx"
+ root = Path(__file__).resolve().parents[1]
+ env = {**os.environ, "ODYSSEUS_DATA_DIR": str(tmp_path / "data"), "PYTHONPATH": str(root)}
+ writers = [subprocess.Popen([sys.executable, "-c", _WRITER, str(directory), str(tmp_path / "ws"), str(i), RUN],
+ cwd=root, env=env) for i in range(4)]
+ assert [writer.wait(timeout=120) for writer in writers] == [0, 0, 0, 0]
+ history = EffectLog.load(RUN, directory=directory).history()
+ assert sorted(c.sequence for c in history.claims) == list(range(1, 161))
+
+
+def test_a_settled_effect_is_never_settled_again_by_another_writer(tmp_path, target):
+ directory = tmp_path / "fx"
+ owner = EffectLog(RUN, directory=directory)
+ made = claim(owner, target)
+ owner.outcome(effect_id=made.effect_id, execution=fx.ExecutionOutcome.RUNNING, impact=fx.Impact.POSSIBLE)
+ other = EffectLog.load(RUN, directory=directory) # also sees RUNNING
+ assert owner.outcome(effect_id=made.effect_id, execution=fx.ExecutionOutcome.REPORTED_SUCCESS,
+ impact=fx.Impact.POSSIBLE) is not None
+ assert other.outcome(effect_id=made.effect_id, execution=fx.ExecutionOutcome.FAILED,
+ impact=fx.Impact.POSSIBLE) is None
+ reloaded = EffectLog.load(RUN, directory=directory)
+ assert reloaded.history().latest_outcome(made.effect_id).execution is fx.ExecutionOutcome.REPORTED_SUCCESS
+ assert other.history().latest_outcome(made.effect_id).execution is fx.ExecutionOutcome.REPORTED_SUCCESS
+
+
+def test_recovery_leaves_a_claim_another_writer_settled(tmp_path, target):
+ directory = tmp_path / "fx"
+ live = EffectLog(RUN, directory=directory)
+ made = claim(live, target)
+ stale = EffectLog.load(RUN, directory=directory) # sees the claim unsettled
+ live.outcome(effect_id=made.effect_id, execution=fx.ExecutionOutcome.REPORTED_SUCCESS, impact=fx.Impact.POSSIBLE)
+ assert stale.recover_interrupted() == ()
+ assert [r["type"] for r in records(live.path)] == ["claim", "outcome"]
+
+
+def test_concurrent_effect_log_open_returns_same_instance(tmp_path):
+ import concurrent.futures
+ with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
+ instances = list(pool.map(lambda _: EffectLog.open(RUN, directory=tmp_path / "fx"), range(16)))
+ assert all(instance is instances[0] for instance in instances)
+
+
+# -- control-plane protection ----------------------------------------------------
+
+def test_hardlinked_effect_state_is_control_plane_without_scanning_the_store(tmp_path, monkeypatch):
+ from pathlib import Path
+ from src.agent_runtime import effect_log, resources
+ store = tmp_path / "effects"
+ store.mkdir()
+ monkeypatch.setattr(effect_log, "EFFECTS_DIR", str(store))
+ for n in range(50):
+ (store / f"{n:032x}.jsonl").write_text("{}\n")
+ workspace = tmp_path / "ws"
+ workspace.mkdir()
+ ordinary = workspace / "notes.txt"
+ ordinary.write_text("x")
+ listed, globbed = [], []
+ real_scandir, real_rglob = os.scandir, Path.rglob
+ monkeypatch.setattr(resources.os, "scandir", lambda path: (listed.append(str(path)), real_scandir(path))[1])
+ monkeypatch.setattr(Path, "rglob", lambda self, pattern: (globbed.append(str(self)), real_rglob(self, pattern))[1])
+ assert resources._control_plane_path(str(ordinary)) is False
+ assert str(store) not in listed and str(store) not in globbed
+ alias = workspace / "sneaky.jsonl"
+ os.link(store / f"{7:032x}.jsonl", alias)
+ assert resources._control_plane_path(str(alias)) is True
++ # Wave 3's scan-local snapshot form: the store is a prefix, not inventory.
++ snapshot = resources._control_plane_snapshot()
++ assert str(store) in snapshot[0]
++ assert resources._control_plane_path(str(store / "new.jsonl"), snapshot=snapshot) is True
++ listed.clear()
++ assert resources._control_plane_path(str(ordinary), snapshot=snapshot) is False
++ assert str(store) not in listed
++ assert resources._control_plane_path(str(alias), snapshot=snapshot) is True
+ assert str(store) not in globbed, "the effect store is listed one level, never recursively inventoried"
+ # Multiply linked files elsewhere stay ordinary.
+ elsewhere = tmp_path / "other.txt"
+ elsewhere.write_text("y")
+ os.link(elsewhere, workspace / "pnpm-style.txt")
+ assert resources._control_plane_path(str(workspace / "pnpm-style.txt")) is False
diff --cc tests/test_wave3_background_followup.py
index 000000000,9c778fe96..7c826fb74
mode 000000,100644..100644
--- a/tests/test_wave3_background_followup.py
+++ b/tests/test_wave3_background_followup.py
@@@ -1,0 -1,100 +1,115 @@@
+ """Permanent linkage loss suppresses continuation without granting authority."""
+ from types import SimpleNamespace
+ import time
+
+ import pytest
+ from src import bg_jobs, bg_monitor
+ from src.agent_runtime import process_resources as resources
+ from tests.test_background_resource_identity import store, seed
+ from src.agent_runtime.resources import ResourceIdentityError
+
+
+ @pytest.fixture
+ def monitor_session(monkeypatch):
+ messages = []
+ sess = SimpleNamespace(id='thread', owner='alice', model='test-model', get_context_messages=lambda: [])
+ sm = SimpleNamespace(get_session=lambda sid: sess, add_message=lambda *args: messages.append(args), save_sessions=lambda: None)
+ import src.ai_interaction as ai
+ monkeypatch.setattr(ai, 'get_session_manager', lambda: sm)
+ import src.agent_runs
+ monkeypatch.setattr(src.agent_runs, 'is_active', lambda sid: False)
+ async def drain(*args, **kwargs):
+ messages.append('drained')
+ return 'continued', []
+ monkeypatch.setattr(bg_monitor, '_drain_agent', drain)
+ return messages
+
+
+ @pytest.mark.parametrize('damage', ['missing', 'corrupt', 'wrong_owner', 'wrong_pid'])
+ async def test_invalid_linkage_is_terminal_without_message(store, monkeypatch, monitor_session, damage):
+ resource, rec = seed(store, status='done')
+ sidecar = bg_jobs._JOBS_DIR / 'job.authority.json'
+ if damage == 'missing': sidecar.unlink()
+ elif damage == 'corrupt': sidecar.write_text('{}')
+ else:
+ jobs = bg_jobs._load()
+ if damage == 'wrong_owner': jobs['job']['resource_identity']['owner'] = 'bob'
+ else: jobs['job']['pid'] = 99999
+ bg_jobs._save(jobs)
+ rec = jobs['job']
+ # Invalid data must not even be rendered into a synthetic result message.
+ monkeypatch.setattr(bg_monitor, '_background_result_message', lambda rec: pytest.fail('Invalid result rendered'))
+ assert await bg_monitor._process_followup(rec) is bg_monitor.FollowupResult.TERMINAL_UNFOLLOWABLE
+ assert not monitor_session
+ assert not bg_jobs.pending_followups()
+ assert bg_jobs.peek('job')['followup_state'] == 'terminal_unfollowable'
+ assert not bg_jobs.peek('job').get('followed_up')
+ with pytest.raises(ResourceIdentityError):
+ resources.validate_job(resource)
+
+
+ async def test_busy_session_retries_then_continues(store, monkeypatch, monitor_session):
+ _, rec = seed(store, status='done')
+ import src.agent_runs
+ monkeypatch.setattr(src.agent_runs, 'is_active', lambda sid: True)
+ assert await bg_monitor._process_followup(rec) is bg_monitor.FollowupResult.RETRYABLE_LATER
+ assert bg_jobs.pending_followups() and not monitor_session
+ monkeypatch.setattr(src.agent_runs, 'is_active', lambda sid: False)
+ assert await bg_monitor._process_followup(rec) is bg_monitor.FollowupResult.COMPLETED
+ assert bg_jobs.peek('job')['followed_up']
+ assert monitor_session and not bg_jobs.pending_followups()
+
+
+ async def test_terminal_record_prunes_exact_generation(store, monitor_session):
+ resource, rec = seed(store, status='done')
+ rec['ended_at'] = time.time() - bg_jobs._RETENTION_S - 10
+ bg_jobs._save({'job': rec})
+ (bg_jobs._JOBS_DIR / 'job.authority.json').unlink()
+ assert await bg_monitor._process_followup(rec) is bg_monitor.FollowupResult.TERMINAL_UNFOLLOWABLE
+ assert not bg_jobs.pending_followups()
+ assert bg_jobs.peek('job') is None
+ assert not resources.launch_path(resource.generation).exists()
+ assert not monitor_session
+
+
+ def test_stale_terminal_snapshot_cannot_suppress_new_generation(store):
+ _, old = seed(store, status='done')
+ new, _ = seed(store, status='done')
+ assert not bg_jobs.mark_unfollowable('job', expected_record=old)
+ assert 'followup_state' not in bg_jobs.peek('job')
+ assert resources.launch_path(new.generation).exists()
+
+
+ async def test_linkage_lost_during_continuation_cannot_deliver(store, monkeypatch, monitor_session):
+ _, rec = seed(store, status='done')
+ async def interrupted(*args, **kwargs):
+ (bg_jobs._JOBS_DIR / 'job.authority.json').unlink()
+ return 'must not be delivered', []
+ monkeypatch.setattr(bg_monitor, '_drain_agent', interrupted)
+ assert await bg_monitor._process_followup(rec) is bg_monitor.FollowupResult.TERMINAL_UNFOLLOWABLE
+ assert not monitor_session
+ assert not bg_jobs.pending_followups()
+
+
+ async def test_stale_terminal_outcome_retries_current_record(store, monkeypatch, monitor_session):
+ _, old = seed(store, status='done')
+ seed(store, status='done')
+ async def terminal(rec): return bg_monitor.FollowupResult.TERMINAL_UNFOLLOWABLE
+ monkeypatch.setattr(bg_monitor, '_run_followup', terminal)
+ assert await bg_monitor._process_followup(old) is bg_monitor.FollowupResult.RETRYABLE_LATER
+ assert bg_jobs.pending_followups()
++
++
[email protected]('linkage', ['valid', 'damaged'])
++async def test_deleted_session_settles_only_a_validated_launch(store, monkeypatch, monitor_session, linkage):
++ """Wave 4: a job retired for a deleted session must not leave its launch effect RUNNING."""
++ resource, rec = seed(store, status='done')
++ if linkage == 'damaged':
++ (bg_jobs._JOBS_DIR / 'job.authority.json').write_text('{}')
++ import src.ai_interaction as ai
++ monkeypatch.setattr(ai, 'get_session_manager', lambda: SimpleNamespace(get_session=lambda sid: None))
++ settled = []
++ monkeypatch.setattr(bg_monitor, '_settle_launch_effect', lambda job, record: settled.append(job))
++ assert await bg_monitor._process_followup(rec) is bg_monitor.FollowupResult.TERMINAL_UNFOLLOWABLE
++ assert settled == ([resource] if linkage == 'valid' else [])
++ assert not monitor_session