diff --git a/README.md b/README.md index 8ed3138..7953032 100644 --- a/README.md +++ b/README.md @@ -98,8 +98,26 @@ state directory. Start authorizes one tools-off provider request. TORQ writes th returned UTF-8 contents to a separate candidate, then runs the fixed `structural-v1` check for Python syntax, strict JSON, and UTF-8 text. The policy accepts at most 32 files, 64 KiB per file, and 2 MiB total. It does not run unit -tests, execute generated code, or modify the configured project. Candidate -application remains a later governed step. +tests or execute generated code. Building a candidate leaves the configured +project unchanged. + +Open **Review candidate** to inspect its Plan, exact Changes, and signed Checks. +Request a correction to build a separate child candidate, or **Accept reviewed +candidate** to record approval without changing files. **Apply to project** is a +separate action that writes only those approved contents. After application, +**Continue after apply** opens a fresh task draft from the current source. +History remains readable after the project changes. + +Application supports UTF-8 file creation and replacement in existing directories. +It verifies source freshness and file identity, preserves supported permissions, +and rejects unsafe links or unsupported metadata. An interrupted application +blocks new work on that project until verified recovery completes; ambiguous or +externally changed files remain blocked rather than being overwritten. These +actions do not commit, push, merge, or run project tests. + +Pause other editors, autosave, formatters, and tools writing this project during +Apply or recovery. TORQ serializes its own installations and rejects observed +file changes, but cannot prevent an external write racing the final file rename. ## Safety model diff --git a/docs/plans/2026-09-16-dashboard-p3-builder-handoff.md b/docs/plans/2026-09-16-dashboard-p3-builder-handoff.md new file mode 100644 index 0000000..22511c9 --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-p3-builder-handoff.md @@ -0,0 +1,65 @@ +# Dashboard P3 builder handoff + +Status: **IMPLEMENTED — READY FOR FINAL PACKAGE AND G1D VERIFICATION** + +This implementation delivers the bounded P3 contract approved in +`2026-09-16-dashboard-p3-g1r-review.md`. It preserves P2 candidate creation and +adds artifact-backed review, readable exact-byte changes and check results, +immutable correction and continuation tasks, bounded searchable history, +separate signed acceptance, and an explicit evidence-backed Apply transaction. + +Apply remains candidate-only until the user accepts and applies a verified +candidate. It never invokes a provider. It uses anchored filesystem access, +per-user/host exclusion, signed staged identities, a shared pending marker, and +restart recovery. P3 does not claim a portable destination compare-and-swap: +external editors and other non-TORQ writers must pause writes and atomic saves +during Apply. All checks immediately before and after the rename remain in +place, and observed drift fails closed. + +## Main implementation + +- `src/torq_cli/domain/task_review.py`: sealed historical candidate resolver, + exact artifact and lineage validation, complete byte-aware diff projection. +- `src/torq_cli/domain/candidate_decision_evidence.py`: closed semantic review + and Apply lifecycles, including forward and rollback staged identities. +- `src/torq_cli/application/review_store.py`: durable versioned request/index + store with CAS and no-follow bounded reads. +- `src/torq_cli/application/candidate_review.py`: review, correction, immutable + child tasks, continuation, accept/apply replay, eligibility, and recovery. +- `src/torq_cli/safety/primary_transaction.py` and `primary_marker.py`: anchored + POSIX/Windows primary transactions, semantic metadata preservation, staging, + leases, markers, and recovery primitives. +- `src/torq_cli/interfaces/fleet_http.py`, `interfaces/cli.py`, and Fleet assets: + authenticated closed HTTP routes plus the full-height Plan/Changes/Checks, + correction, acceptance, Apply, recovery, and paginated history UI. +- Candidate task/store, receipt, and evidence modules carry the minimal P3 + lineage, stable chronology, semantic validation, and authenticated-prefix + support while preserving the P2 schemas and evidence. + +## Durable regressions + +Repository tests cover exact resolver and evidence schemas, authenticated HTTP +and replay, task history, platform-native transaction behavior, source +unchanged before Apply, signed acceptance/application, correction child tasks, +stale continuation plans, continuation process-death reconstruction, a CAS race +with an ordinary draft, and restart after a native rollback rename before its +restored receipt. The rollback test proves exact base restoration, marker +clearance, idempotent idle recovery, and no extra provider/check launches. + +Independent fixtures additionally exercised all ten forward crash boundaries, +unsigned and substituted staging files, third-byte conflicts, source-context +drift, legacy P2 evidence compatibility, replay-store substitution, and real +process death during rollback. Those results are recorded in +`2026-09-16-dashboard-p3-g1d-verification.md`. + +## Builder verification + +- `python -m pytest -q -p no:cacheprovider --basetemp E:\tmp\torq-p3-builder-final-focus tests/test_candidate_review.py tests/test_candidate_decision_evidence.py tests/test_primary_transaction.py tests/test_task_http.py tests/test_candidate_history.py tests/test_hermetic.py` — **56 passed**. +- `python -m ruff check src tests` — **passed**. +- `python -m mypy --platform win32 --cache-dir tmp/mypy-p3-final-win32 src/torq_cli` — **passed, 96 source files**. +- `python -m mypy --platform linux --cache-dir tmp/mypy-p3-final-linux src/torq_cli` — **passed, 96 source files**. +- `python -m mypy --platform darwin --cache-dir tmp/mypy-p3-final-darwin src/torq_cli` — **passed, 96 source files**. + +The independent G2A verdict is **APPROVE** in +`2026-09-16-dashboard-p3-g2a-review.md`. Packaging, installed-wheel browser +verification, and delivery remain with G1D/root. diff --git a/docs/plans/2026-09-16-dashboard-p3-contract.md b/docs/plans/2026-09-16-dashboard-p3-contract.md new file mode 100644 index 0000000..c5012f1 --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-p3-contract.md @@ -0,0 +1,176 @@ +# P3: verified review, refinement, and explicit project application + +Status: G1R approved, `READY_FOR_P3_BUILDER`; see `2026-09-16-dashboard-p3-g1r-review.md`. Baseline `e32ecdc` on `origin/main` (merged P2, PR #81). Working branch `feat/dashboard-p3-review-apply`. User authorizes implementation, testing, then commit/push and merge to main after required CI passes. This authorization does not turn dashboard Accept into an implicit Git action. + +```mermaid +flowchart LR + P2[Sealed candidate] --> Review[Exact Plan / Changes / Checks] + Review --> Revise[Saved correction and child plan] + Revise --> Child[New bounded candidate against original base] + Child --> Review + Review --> Accept[Signed acceptance decision] + Accept --> Apply[Explicit Apply to project] + Apply --> Lease[Primary lease and source recheck] + Lease --> Journal[Durable journal and backups] + Journal --> Write[Anchored per-file replacement] + Write --> Verify[Verify primary result and seal evidence] + Write --> Recover[Verified rollback or recovery required] +``` + +## Outcome, scope, and interpretation + +The user can inspect an actual candidate diff and its check evidence, request a correction, find earlier tasks, accept the exact reviewed candidate, and explicitly apply it to the configured project. The prior UX plan's acceptance-only description is expanded here because the delivered P2 explanation reserved project application for P3. Acceptance and application remain separate claims and separate buttons. A completed provider process, verified candidate, accepted decision, and applied source are never conflated. + +Keep P2's bounded UTF-8 create/replace policy: at most 32 files, 65,536 bytes per file, 2 MiB total, supported suffixes and secret/protected-path denial. No delete/rename operations, arbitrary shell, generated-code execution, project unit-test runner, credentials changes, autonomous Git operation, push/merge/deployment from the dashboard, or general IDE migration. The implementation is a separate candidate-review/application contract, not an implementation claim for the whole design-only schema-v3 governed-run orchestrator. Preserve existing run/chat transition behavior and never map an approval directly to completed. + +## Verified artifact projection + +Introduce a shared verified result resolver whose authoritative input is `(task_id, candidate_ready_sequence)`. Require a verified, sealed receipt store; the exact ready event and linked start/generated/check events; strict event semantics; cipher and plaintext hashes; matching task, plan, input, base, operation, candidate and check identities. Parse duplicate-free finite JSON with closed shapes. Resolve encrypted accepted-input, candidate-bundle, and check artifacts; reconstruct base from accepted-input and candidate from base plus the complete host-validated operations. Recompute the exact manifests, operation hashes and checked-file list. No GET creates keys, starts a provider, writes a receipt, or substitutes another task/sequence/artifact. + +Historical truth must not depend on current source, current isolated workdir, or upgraded helper bytes. These may differ after application/cleanup/upgrade. Existing P2 generated evidence remains valid if its signed artifacts remain valid. Preserve a separate live integrity/freshness signal for candidate-cache tampering rather than silently treating an altered existing cache as verified. Missing disposable cache alone may not erase historical review. Source freshness and platform/apply availability are separate from historical `verified` and are evaluated again on mutations. An unresolved artifact leaves an explicit error and disables acceptance/application; no latest-artifact fallback. + +Return one bounded immutable `torq-task-review-v1` envelope with task ID, exact ready sequence, plan/base/input/candidate/check hashes, verified Plan/Changes/Checks payloads and a canonical `review_hash`. Mutable eligibility/status must be outside that hash. Header displays task ID and evidence sequence. All tabs, filenames, counts and hunks come from this single response and identity; changing the selection invalidates pending responses. + +Changes are generated deterministically from accepted-input bytes to reconstructed result, never Git HEAD/origin or a live file. Include operation/path/base hash/result hash, exact text/newline metadata and a safe text diff representation. Preserve CRLF/LF and final-newline distinctions. Bound total rendered payload and hunks; if detail is truncated it must say so, retain file/hash identities, and provide a bounded full-file text view or disable acceptance until the complete supported review is available. Escape all provider/file content as text. Two tasks with disjoint files never mix views. + +Checks show signed check sequence, profile/version, actual exit code, output-complete and termination states, output, helper hash and argv hash. P2 only recorded argv hash: label the normalized fixed command `python -I -S ` as a command contract, not the exact historical argv. Never claim project tests ran. Missing/failed/incomplete checks prevent acceptance/application. + +## Refinement and continuation + +Persist a parent-scoped correction draft with revision CAS and bounded text, separate from signed evidence and ordinary project drafts. Review a child plan before dispatch. A new versioned child plan/input shape binds parent task ID, ready sequence, parent plan/candidate/review hashes, original root base hash, and correction revision/content hash. Never hide lineage in goal prose or silently reinterpret a v1 field. + +The child uses the SAME ORIGINAL source base for operation preconditions and application. Supply the verified prior candidate as explicit bounded context; the provider emits a complete desired create/replace operation set against the original base. Parent content is never read from an unverified mutable cache. Child gets its own task/run ID, immutable input, provider/check execution and sealed result. Parent remains sealed and unchanged. Re-resolve parent identity and check original source freshness before dispatch; stale source requires a new task/rebase, not automatic merge. Recheck lineage while independently verifying the child. + +Durable child request reservation precedes dispatch. Same request/body replays the same child; changed body conflicts; restart never redispatches. After verified Apply, Continue opens a new ordinary task draft with lineage context and a freshly reviewed live-source base; it cannot reuse the now-stale original-base child plan. Opening Continue alone performs no provider call. + +## Acceptance and application evidence + +New closed discriminators `torq-candidate-review-v1` and `torq-candidate-apply-v1` reuse existing certificate/encrypted-artifact/receipt authority only with explicit per-event and cross-receipt validators wired into BOTH append and portable verification. Generic signed audit prose does not grant eligibility. Existing sealed P2 chains are never appended to. + +Review decision is a separately sealed chain with exactly one terminal accepted or correction-requested decision. Bind request digest, task/ready/review identity, plan/base/input/candidate/check identities, decision, and actor assurance. Actor is a non-secret stable local session-instance ID with assurance `local_operator_session`; cookie bearer values and claims of durable human identity are forbidden. Preserve this subject across session rotation. + +Application references an independently verified accepted review chain and exact candidate. Its logical states/events are prepared, started, per-file progress, applied, rollback_started, rolled_back, and recovery_required. Exact field sets, order/link rules, terminal rules and bounded code enums must be implemented as schema validators before use. Applied requires final exact scoped source manifest matching the candidate, full operation completion and journal identity. Rolled back requires the exact original scoped manifest and original create absence. Recovery-required is NOT successful and stays unsealed until a verified terminal outcome is obtained. Signed applied history is distinct from a current source match; later edits do not erase the historical event. + +Accept rejects stale source in v1 and changes no source file. Apply is a second explicit POST, never triggered by Accept, GET, navigation or a provider. Its closed body includes stable request ID, exact candidate tuple/review hash and accepted-decision identity. Durable reservation plus canonical body digest precedes mutation. Same key/body replays the same result; changed body conflicts. Already-applied candidate/review cannot apply twice even with a new request ID. Replays after later source edits report historical outcome without writing. + +## Primary transaction and recovery + +Do not reuse `ApprovalBoundary.apply` or the broad legacy workspace copier. Implement a small audited native source transaction boundary. Every read/mutation uses validated relative paths, regular unlinked files, no reparse/symlink ancestors, physical root identity, case/NFC/device/ADS restrictions, and exact scope. Source, state, work and runtime boundaries stay disjoint. + +Acquire a kernel-held lease shared by TORQ installations running as the same OS user on the same host and targeting the same physical primary root (including aliases and separate login sessions). A state-local lock alone is insufficient. Use a physical-root keyed Windows named mutex or an anchored POSIX root-directory flock; retain the root handle throughout. This is local-host coordination, not a distributed lease across machines or separate user authorities. Windows Apply rejects UNC and mapped network volumes at preflight. Also persist a discoverable per-primary active/recovery marker in a fixed owner-only per-user authority location, so another installation cannot ignore a crashed transaction after the kernel lease is released. Test harnesses can inject an isolated common authority root. Unknown/corrupt marker means blocked, never idle. Clear the marker only after verified terminal evidence; another installation may report the owning recovery authority but must not mutate its journal. + +Under the lease, independently reverify accepted review/P2 artifacts, project mapping, ALL scoped context preimages and absence of all create paths. Bind root physical identity, parent directory identities, exact ordered operations, source base/result hashes, and permission/mode policy. Acquire mutation path handles before writes and retain anchors. This coordinates TORQ installations and rejects observable external drift; it is not an OS sandbox or a lock on other editors and tools. All non-TORQ writers, including editor autosave, formatters, and file watchers, must abstain during Apply and recovery. There is no portable destination-identity-conditional rename: an external write racing the final identity/content check and atomic rename may be overwritten. This limitation applies to both already-open handles and rename-based saves. Held root/parent anchors, no-follow/reparse checks, staged provenance, identity/content rechecks, and result verification remain mandatory. + +Write a closed, bounded, owner-only durable journal and exact backups/staging BEFORE the first primary mutation. Bind transaction/request/review/candidate identities, root identity, old/new file bytes or encrypted artifact references and hashes, originally absent paths, directory effects, and progress. Authenticate recovery against sealed input/review and signed prepared/journal digest; do not execute operations from an unauthenticated editable cache. fsync staged files/journal and relevant directories. Append started only after preparation is durable. Never dispatch provider/checker from application/recovery. + +Use same-directory exclusive temporary files, complete write loops, flush, then anchored atomic per-file rename. POSIX walks/open/create/replace/delete through held dirfds with nofollow; Windows holds no-reparse ancestor handles and uses handle-relative rename into the held parent. No Windows fallback to a pathname `os.replace` after a check. Preserve existing file permission semantics; creates inherit a documented safe mode/ACL. Track and safely undo any directories created by the transaction, only if still owned/empty; otherwise recovery-required. If a filesystem/platform cannot supply the required primitive, expose a precise unsupported Apply capability before mutation rather than weakening the boundary. + +This is recoverable PER-FILE atomic replacement, not atomic visibility of a multi-file transaction. Before each rename, durably sign the finalized staged file identity; after each mutation record progress durably. Rehash the full scoped result under the lease; only then append applied and seal. On exception, reverse only operations whose current target has both the expected desired bytes and the signed staged stable identity; unchanged authenticated preimages need no rewrite. Any third content, link/identity substitution, altered backup/journal, unavailable ownership or inconclusive flush remains recovery-required, with no blind overwrite of user edits. Recovery checks target bytes, signed stable identities and journal phase, not just a mutable progress counter. A file renamed before its progress receipt is recognized only by exact desired hash plus the durable signed staged identity. + +Startup discovers unfinished transactions before enabling Apply or new conflicting task operations. Recovery is bounded and idempotent: reconcile a wholly verified completed transaction, otherwise verify/restore the original snapshot where safe, otherwise block and show a recovery action/reason. Crash before writes can abort without mutation; crash at each subsequent boundary must either prove applied, prove restored, or remain explicitly uncertain. Do not release a success claim because an exception was swallowed. Keep evidence-write failure after primary writes distinct from a successfully sealed application. + +Native reference checked 2026-09-16: [Microsoft FILE_RENAME_INFO](https://learn.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_rename_info) documents relative names with a directory handle; [FILE_RENAME_INFORMATION](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_rename_information) describes replacement and same-volume constraints. Native integration tests, not documentation alone, determine capability. + +## HTTP, state, and user interface + +Add authenticated exact review GET, correction-draft/child-plan, Accept, Apply, recovery/status and bounded history-search routes to the existing Fleet seam. Retain exact-origin checks, strict bounded duplicate-free JSON, closed field sets and rotated single-owner mutations. Extend lost-response handling only to look up the exact existing accepted request for that mutation; an old token may never authorize a new decision/write or access general endpoints. Serialize all task/review writes through the same UI queue and capture immutable task/review/request identities before enqueue. + +Task search is navigation, not authority: bounded case-insensitive Unicode title/goal/project search, with stable chronological order and cursor/limit. Persist a monotonic ordinal for future tasks; explicitly define deterministic migration for older entries without pretending random task IDs are timestamps. Opening a result independently resolves its exact signed artifact identity. Parent/child navigation must not mix drafts or task content. + +## Closed-schema and crash-order addendum + +These concrete choices supersede any ambiguity in the narrative above. Shared references below are closed dictionaries; hashes are canonical SHA-256 strings, sequence/index/count values are bounded integers excluding booleans, IDs use fixed prefix plus generated hex, reasons use bounded machine-code enums, actor IDs are opaque non-secret IDs. Schemas reject extra keys, duplicate keys, non-finite numbers, malformed references, reordered/duplicate events and mixed discriminators. Limits derive from the existing 32-file/2-MiB policy, not unbounded user input. + +For bounded v1 Apply, all destination parent directories MUST already exist and be safely anchorable; no primary directories are created or removed. The immutable journal's `created_directories` is exactly an empty list. A missing parent yields `task_apply_parent_missing` before acceptance/application writes with the remedy to create the project directory and re-open review. This explicit restriction supersedes the optional directory-mutation discussion above; journaled directory creation is not claimed as delivered. Creating new files in existing safe directories remains supported. + +`review_hash` hashes the complete canonical immutable review core WITHOUT its own digest field. The returned envelope attaches this digest; the encrypted review artifact stores that same hashless core. This avoids self-referential hashes. CandidateRef's review hash must equal this computed digest; it is not copied into its own preimage. + +Metadata policy is fixed: POSIX replacements retain owner UID/GID and ordinary permission bits, rejecting special bits or additional ACL/xattr security metadata that the primitive cannot preserve; creates use the current user, normal group and mode 0600. Windows replacements retain the owner/group/DACL security descriptor and supported ordinary attributes, rejecting read-only, reparse, encrypted or other unsupported metadata and additional data streams before mutation; creates use the same explicit current-owner-only DACL policy as trusted task-state files. Metadata is captured through held handles, bound to the journal and verified after writes/restoration. Access-control preservation failure is a blocked/failed transaction, never a reason to silently broaden permissions. No timestamp-preservation or whole-repository-metadata claim is made. + +Windows descriptor policy comparison normalizes only `SE_DACL_AUTO_INHERITED` and `SE_SACL_AUTO_INHERITED`, which record inheritance processing. Owner, group, DACL/ACE bytes, protection semantics and supported file attributes remain preserved. This is defined metadata-policy equality, not raw descriptor byte equality. + +`CandidateRef` has exactly: `task_id`, `ready_sequence`, `ready_receipt_hash`, `terminal_manifest_hash`, `plan_hash`, `base_scope_manifest_hash`, `input_hash`, `candidate_scope_manifest_hash`, `check_sequence`, `check_receipt_hash`, `review_hash`. The receipt hashes come from the verified parent envelopes, and terminal-manifest hash is the hash of its exact verified bytes. `DecisionRef` has exactly: `decision_id`, `decision_sequence`, `decision_receipt_hash`, `terminal_manifest_hash`. An encrypted `ArtifactRef` has exactly `artifact`, `artifact_hash`, `content_hash`. All cross-chain projections independently verify the referenced stores and exact terminal events before comparing these fields; a matching opaque ID alone proves nothing. + +Every review event has exactly `review_contract`, `event`, `decision_id`, `request_digest`, `candidate`, `actor`, `detail`. `review_contract=torq-candidate-review-v1`; `actor` has exactly `subject_id`, `assurance` with assurance `local_operator_session`. `event=candidate_accepted` has `detail={review_artifact, source_scope_hash}`. `review_artifact` is an ArtifactRef for the exact canonical immutable review and the acceptance must record current scope matching CandidateRef base. `event=correction_requested` instead has `detail={correction_revision, correction_hash, child_plan_hash}`. Exactly one decision event per review chain, followed by seal; no later append. This does not mutate the source or dispatch a provider. + +Idempotent request digests bind the closed client operation body; the server-injected session actor is recorded separately and remains the actor of the original signed decision. A newly authenticated session after restart may replay the exact original request as a verified read without changing that actor or dispatching/applying again. Mutable request indexes must be checked against the signed request digest and all result references before returning a success. + +Correction is two explicit steps: review/save correction to obtain a child plan and a signed correction-requested decision, then Start revision to execute that reviewed plan. Child-plan creation is idempotent and CAS-bound before writing the decision; restart resumes or exposes its existing reservation and cannot dispatch. A child plan/input uses a new versioned shape and a closed `lineage` field with `mode=refinement`, `parent_candidate` (CandidateRef), `correction_revision`, `correction_hash`, and `root_base_scope_hash`. The correction DecisionRef is included in the signed accepted-input bundle and checked against the immutable child-plan hash; it is not inserted recursively into the plan whose hash the decision already binds. The full correction text and verified parent candidate context are part of that bounded accepted-input artifact. Continuation uses `mode=continuation` with the parent CandidateRef and verified applied-result reference but a fresh source base, not refinement semantics. + +`torq-candidate-plan-v2` has exactly `contract`, `project_id`, `goal`, `draft_revision`, `input_paths`, `output_paths`, `absent_output_paths`, `base_manifest_hash`, `provider`, `model`, `provider_binary_hash`, `check_profile_id`, `check_profile_version`, `helper_hash`, `limits`, `lineage`. All v1 field meanings/limits remain unchanged. Refinement lineage has the exact fields in the preceding paragraph; continuation lineage instead has exactly `mode`, `parent_candidate`, `application` (DecisionRef-shaped verified terminal apply reference). `torq-candidate-input-v2` has exactly `contract`, `plan`, `files`, `parent_context`, `correction`; files are the original-base bundle for refinement or freshly reviewed source for continuation. Parent context has exactly `candidate` (CandidateRef), `files` (the verified reconstructed parent candidate bundle). Correction is null for continuation; for refinement it has exactly `revision`, `text`, `content_hash`, `decision` (DecisionRef). A source-file bundle entry retains the existing exact `path`, `content`, `content_bytes`, `content_hash` schema. Source and parent bundles are each bounded by P2 limits; cap combined encoded provider input explicitly (and fail before dispatch if exceeded), rather than claiming both maxima always fit. Input hash covers all these bytes; child plan hash deliberately excludes the later decision reference to avoid a circular commitment. Verification resolves both the parent CandidateRef and correction DecisionRef, checks its child-plan hash, and requires original-base equality for refinement. The v1 shapes remain separately readable and cannot acquire v2 semantics through extra fields. + +The provider emits the COMPLETE child operation set against the original base. It may intentionally remove a parent change: omitted paths revert to original-base contents/absence, never implicitly inherit parent output. Show a clearly labelled parent-to-child comparison, including dropped parent-change paths, within the same verified review envelope. The authoritative Apply diff remains original base to child; the complete envelope is bound by `review_hash`. Only genuinely changed child operations are written; unchanged context files are never rewritten. + +Every apply event has exactly `apply_contract`, `event`, `application_id`, `request_digest`, `candidate`, `acceptance`, `actor`, `detail`. Discriminator is `torq-candidate-apply-v1`; candidate and acceptance are the exact references above. The common tuple cannot change between events. The allowed detail shapes are: + +| Event | Exact detail keys | Lifecycle rule | +| --- | --- | --- | +| `apply_authority_created` | `installation_id` | First and unique, nonterminal; before any shared marker or primary effects | +| `apply_rejected` | `reason_code` | Terminal after authority-created and before prepared, no writes; seal | +| `apply_prepared` | `journal_artifact`, `journal_hash`, `primary_identity_hash`, `operation_count` | After authority-created; authenticated immutable journal durable | +| `apply_started` | `prepared_sequence`, `prepared_receipt_hash` | Once after prepared; precedes any primary mutation | +| `apply_file_staged` | `started_sequence`, `operation_index`, `path`, `result_hash`, `staged_identity` | Increasing unique indices; finalized bytes/metadata flushed and signed prefix verified while exclusive temp handle remains held; precedes rename | +| `apply_file_written` | `started_sequence`, `operation_index`, `path`, `result_hash`, `staged_sequence`, `staged_receipt_hash` | Crosslinks its exact staged event and identity; increasing unique indices matching journal operations | +| `apply_rollback_started` | `caused_by_sequence`, `reason_code` | Once after preparation/start; subsequent mutation is rollback only | +| `apply_recovery_required` | `caused_by_sequence`, `reason_code` | Non-terminal, unsealed; unique per changed observation, bounded events | +| `candidate_applied` | `started_sequence`, `journal_hash`, `result_scope_manifest_hash`, `operation_count` | Terminal only after complete target-byte and scope verification, including safe restart reconciliation; seal | +| `apply_rolled_back` | `prepared_sequence`, `journal_hash`, `restored_scope_manifest_hash` | Terminal after authenticated restoration/unchanged-base verification; seal | + +Recovery may append the missing file-progress receipts in order only after proving those exact operation results; a mutable counter never authorizes them. A recovered complete transaction also verifies scope and all links before applied. Otherwise rollback must be explicitly entered. A terminal cannot be followed by any receipt, and portable validation enforces all sequence/hash/context/journal-bound transitions. A bounded prepared event with no start may only be safely abandoned/restored; it never becomes applied. + +The immutable journal plaintext has exactly `schema`, `application_id`, `request_digest`, `candidate`, `acceptance`, `primary_identity`, `base_scope_manifest_hash`, `result_scope_manifest_hash`, `operations`, `created_directories`. Schema is `torq-primary-journal-v1`. Primary identity is a closed native identity (platform plus volume/device and root file ID/inode) tied to the configured canonical root. Each ordered operation has exactly `index`, `operation`, `path`, `before_content`, `before_hash`, `after_content`, `after_hash`, `permission_policy`, `parent_identity`, `before_identity`; before content/hash/identity are null only for an originally absent create. Stable parent/before/staged identities have exactly `volume`, `file_id`, nonnegative integers excluding booleans; POSIX device/inode map to those fields. Size/mtime are not stable identity and remain separate read-stability/content/metadata checks. Changed operation bytes and original scoped context are authenticated against CandidateRef artifacts, not merely journal self-hashes. Permission policy is explicit regular-file mode/ACL preservation metadata and create policy, and cannot nominate paths or privileged flags. Created directories are empty in this version; never recursively delete any primary directory during recovery. + +The narrow native staging callback runs after complete bytes/metadata and file flush, while the exclusive temp handle remains held. It appends, flushes and verifies `apply_file_staged`; native commit then rechecks staged stable identity/hash and persisted parent identity before handle-relative rename. Recovery and rollback use this signed result identity, never a current pathname value substituted as the expected identity. An unsigned crashed temp before the staged receipt, or equal desired bytes under a different file identity, remains conservatively blocked. Written receipts inherit the staged identity through their exact sequence/hash crosslink. + +Mutable progress/temporary-path state is only an optimization: independently derive safe recovery from immutable authenticated journal, receipt prefix and current anchored filesystem. Prefer a separate versioned review/apply state store; do not add top-level keys to P2's closed v1 TaskStore without an explicit atomic migration. Search index order for legacy tasks derives earliest verified signed start timestamp, with task ID tie-breaker; entries without verified chronology are labelled legacy and ordered deterministically. New ordinal reservations are monotonic. + +Crash order is: durable request reservation -> create authority/certificate, append and flush `apply_authority_created`, and require ordinary store verification of that one-receipt unsealed prefix and exact manifest anchor -> physical primary lease -> exact evidence/source checks -> durable shared marker claiming this installation/application (no primary writes yet) -> encrypted immutable journal artifact plus flush -> signed `apply_prepared` receipt plus durable manifest prefix -> `apply_started` -> primary writes/progress -> result verification -> terminal receipt -> seal -> release shared marker. Authority creation is an original Apply preparation action, never a recovery action; no shared marker may exist before that authority is durable and verifiable. Zero-count initialization is never verified application evidence. A crash during authority creation/first append before the marker leaves a preparation-failed request and incomplete identity without a marker; a new explicit request receives a new application ID. Marker identifies application, owning state authority and primary identity, never supplies executable recovery operations. Inability to locate/authenticate its owner leaves the primary blocked. Before prepared/start, safe abort is allowed only if primary still equals authenticated base and no transaction-owned primary side effects occurred; otherwise preserve the block. Crashes between terminal and seal are reconciled by verifying the existing terminal, then sealing without rewriting source. Crashes after seal but before marker removal verify the sealed outcome and then remove the marker without reapplying. + +The marker is a closed `torq-primary-pending-v1` record with exactly `schema`, `primary_identity_hash`, `installation_id`, `application_id`, `authority_locator`, `journal_hash`, `phase`, `revision`. Phase is `reserved`, `prepared`, `started`, `recovering`, or `terminal`; journal hash is null only before prepared. Locator is a server-derived owning state-root reference, never an HTTP/model path; the installation ID binds it. Unknown phases, hash/owner/identity mismatch or ambiguous aliases block. Lease-held atomic update+fsync increments marker revision. Pre-journal recovery creates a sealed `apply_rejected` with reason `task_apply_preparation_aborted` only after verifying the linked sealed acceptance, recomputing source-base equality/create absence, and proving no started prefix or primary temp exists. Then it may clear its own marker. This is the explicit no-mutation abort; there is no generic marker deletion shortcut. + +Preparatory backups and encrypted journal live OUTSIDE primary. Same-directory temporary files are not created in primary until after `apply_started`; their leaf names are host-derived from application ID/index, never selected by request/model. Recovery validates their identity/content against the authenticated journal before cleanup, and unknown temp bytes keep recovery blocked. Thus a genuine pre-journal crash has no primary staging effects to infer. Apply mutates only the journal's verified changed-operation set; full context is rehashed but not rewritten. + +Recovery uses a NEW no-create verified-prefix artifact reader restricted to candidate-apply recovery. It authenticates the certificate, receipt prefix, current manifest anchor, strict apply state machine and exact signed prepared event; permits the existing verifier's authenticated `live_catching_up` state only with a fully verifiable covered prefix and matching artifact cipher/plain hashes. It never treats live data as a successful review or application and never exposes general unsealed artifacts through HTTP. Missing keys/certificates/prefix/artifacts are errors, not permission to create or repair identity. If the existing verifier cannot establish this invariant, use a separately sealed preparation chain rather than weaken verification. + +Post-marker reopening loads existing root/writer/artifact keys without calling key creation, trust-anchor pinning or certificate creation. Before advancing an authenticated uncovered tail, validate every signature and semantic link plus the nested prepared `detail.journal_artifact` cipher/plain hashes and closed journal schema. The legacy constructor's top-level-artifact tail recovery is insufficient for this nested reference and must not run before this validation. + +For a pre-marker restart, distinguish an incomplete first commit from a completed one by read-only verification. A fully verified begin receipt/manifest/anchor can be reopened without creation and sealed as `apply_rejected(task_apply_preparation_aborted)`; only an incomplete or unverifiable first commit is quarantined as preparation-failed. Neither outcome recreates missing identity or permits source writes. + +While a primary marker is active, unknown or recovery-required, ALL new plan/start/refinement/accept/apply operations touching that physical project are blocked across installation state roots. Read-only historical review/history and exact replay of previously accepted requests remain available. This gate is checked in server methods, not only capability/UI code. The kernel lease prevents concurrent application; the marker preserves exclusion after a process dies. + +Build a full-height review surface with accessible Plan, Changes, Checks tabs, file navigation, parent lineage, correction composer, Accept and Apply states and truthful current-source/recovery messages. Preserve draft text and focus across navigation; delayed GET/POST responses cannot overwrite a different selection or enable stale acceptance. Every blocked action explains a concrete remedy. Accept copy: records approval, does not modify project. Apply copy: lists the reviewed scope and confirms it changes this configured project. No extra secret/path implementation details in normal screens. Support keyboard, 320px widths, light/dark, zoom and reduced motion. Preserve existing Fleet and P2 flows. + +## Validation and delivery gates + +Sol G1R approves this contract before Builder implementation; Terra G2A independently reviews final changes. Root verifies browser/package and publication. Builder should first prove native anchored replacement and recovery in an isolated fixture; failure reshapes the implementation, never a hidden fallback. + +Required tests: exact-sequence and two-disjoint-run reviews; byte/newline-aware diff; missing/tampered/unsealed/cross-task artifacts; history after cache removal/source application/helper upgrade; stale/occupied/create/link/reparse/hardlink/protected/case paths; Accept no source writes and decision replay; correction CAS/parent verification/complete child context/idempotent dispatch; continuation with new source base; concurrent aliases/installations; injected crash before/after every write and every evidence/journal phase; exact rollback or persistent recovery block; observed/preexisting third-party states never overwritten by recovery; external writes racing the final check/rename are excluded by the writer-abstention precondition; current-source state separated from historical applied; no provider dispatch from review/apply/recovery; session/origin/unknown fields/lost-response replay boundaries; UI delayed selection/draft/accept/apply responses; searchable chronological history and keyboard/mobile review. + +Use actual fixture provider + checker + receipt authority + native primary writes against isolated temporary projects in integration, clearly labelled fixture generation. Test review -> correction -> child -> Accept (source unchanged) -> Apply (exact expected bytes) -> reload/history -> Continue, including installed-wheel browser flow. No live paid vendor call is necessary or claimed. Run focused tests, full repository suite, Ruff, mypy for win32/linux/darwin, Node UI tests, native Windows tests, wheel/build smoke and CI platform lanes. Only after local tests/reviews pass commit and push a scoped PR; merge to main after required checks pass without bypass. Preserve unrelated local artifacts. + +## Design stress test + +The Verdict: RESHAPE the acceptance-only original P3 into explicit review and a separately verified primary transaction, retaining P2's bounded policy. + +Why: the needed user outcome includes applying a reviewed candidate, while current approval/workspace helpers cannot provide crash or path-race safety. The artifact resolver also must separate historical evidence from live source eligibility. + +The Brutal Truth: A trustworthy diff that cannot be applied still leaves the build workflow unfinished. An Apply button without anchored writes and recovery is worse because it can lose the user's work. + +The Riskiest Assumption: native filesystem primitives and journal ordering can make interruption recoverable without overwriting unrelated changes. The 48-Hour Cheap Test: a real two-file Windows fixture interrupted before/after each replacement, then restarted, must show exact application, exact restoration, or an explicit persistent block. What would change the verdict: failure to provide a tested anchored primitive requires Apply to remain unsupported on that platform and must be reported as unfinished P3 application, not shipped as full completion. + +Council: Contrarian—fatal risk is partial writes plus false applied evidence; journal/fault tests address it. Expansionist—major upside is one immutable review identity reusable for later policies; no broad execution added now. First principles—major requirement is bytes reviewed equal bytes applied; one verified artifact value drives both. Researcher—major unknown is Windows native rename behavior; official API documentation plus real fixture tests are required. User—major risk is another opaque blocked state; preserve drafts, show freshness and give recovery remedies. For each lens, what would change my mind is failing its corresponding acceptance oracle, not a visual demo. + +## Rollback identity amendment + +G1R approved this bounded addition after the independent crash audit. Restoring a replacement creates a new file identity; `apply_rollback_started` alone never authorizes that identity. Two additional closed apply events use the existing common apply envelope: + +- `apply_rollback_file_staged`: detail exactly `{rollback_started_sequence, operation_index, path, base_hash, staged_identity}`. +- `apply_rollback_file_restored`: detail exactly `{rollback_started_sequence, operation_index, path, base_hash, staged_sequence, staged_receipt_hash}`. + +`base_hash` equals the authenticated journal's `before_hash` for replacement and is null for creation. The operation type is derived from that journal. For replacement, `staged_identity` is the new finalized rollback temporary file. For creation, the staged event is signed delete intent and its identity must equal the forward staged/result identity. The restored receipt crosslinks that exact staged receipt. Both events bind path/hash/index to their journal operation, and the unique rollback-start sequence. At most one pair per rolled-back operation is permitted, in strict reverse operation-index order; untouched operations need no pair. + +Rollback replacement uses a deterministic rollback-only temporary leaf distinct from forward staging. A retry reuses the authenticated stage and exact existing temporary file; it must not restage under another identity. If the target still has its forward identity and the exact signed rollback temp exists, recovery may commit that same held temp. If the target already has base bytes and the signed rollback-stage identity, recovery may append the missing restored receipt. An untouched preimage is accepted only under its original journal identity. Missing temp with a forward target, equal bytes under another identity, or an unknown temp keeps recovery blocked. + +For create rollback, signed intent plus the exact forward target permits retrying anchored deletion. A restored receipt plus absence completes the operation. A crash after deletion but before the restored receipt leaves ambiguous absence and remains `recovery_required`; absence is not a file identity and there is no inferred deletion-success shortcut. This explicitly permitted persistent block preserves the contract's exact restoration or honest recovery-block outcome. + +Tests must interrupt replacement around rollback staging, rename, and restored receipt, and creation around delete intent, unlink, and restored receipt. Terminal cleanup must reject both forward and rollback temporary leaves if unexpectedly present. Final G2A audit and native crash verification cover this amendment before delivery. diff --git a/docs/plans/2026-09-16-dashboard-p3-g1d-verification.md b/docs/plans/2026-09-16-dashboard-p3-g1d-verification.md new file mode 100644 index 0000000..baf7af2 --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-p3-g1d-verification.md @@ -0,0 +1,68 @@ +# P3 independent verification + +Status: **PASS for the bounded P3 local delivery gates**, verified 2026-09-17 America/Chicago. GitHub CI and merge are subsequent delivery gates; this receipt does not claim them in advance. + +Baseline: P2 main `e32ecdc3ed2ab3df1f6fa00e3d49994532c4474a`. G1D: GPT-6; G1R: GPT-5.6-Sol; backend and UI builders: GPT-Daybreak-Blue-Latest; G2A: GPT-5.6-Terra. G1R approved the contract and amendments; G2A approved the implementation in the separate review receipt. + +## Repository and package checks + +- Full repository suite: **1,055 passed, 13 skipped**, 1,068 collected, zero failures/errors. JUnit: `tmp/p3-release-tests.xml`; Windows runtime, network denied. +- Ruff `src tests`: passed. Mypy `src` for `win32`, `linux`, and `darwin`: passed, 96 source files on each target. These are static platform checks, not native Linux/macOS execution. +- Node task/review and resumed-task harnesses pass through the full Python suite. Delayed selection, project recovery, history pagination, draft preservation, rejected/rolled-back outcomes, and lost-response request identity are covered. +- Source distribution and wheel build passed. Clean-install `scripts/wheel_smoke.py tmp/p3-release-dist` passed. +- Verified every packaged `torq_cli/` file against its source counterpart: no mismatches. +- Wheel SHA-256: `0954d29f26cc9dc41eaddb23ae44c5c15607d6e91cc37cbaecc1d4eba15b1a79`. +- Named security mutants: 30/30 killed. These are the repository's existing security mutants, not a claim of mutation coverage for every new P3 branch. + +## Installed-wheel browser flow + +Served an isolated loopback dashboard from `tmp/p3-wheel-installed/torq_cli/__init__.py`, not the source checkout. Used an offline fixture provider through actual Windows `OwnedProcess`, followed by the packaged structural checker. No live paid-provider authentication or generation is claimed. + +1. Saved a goal/scope, reviewed the plan, and built an actual sealed candidate. +2. Opened Plan, Changes, and Checks. Requested a docstring correction, reviewed the child plan, and started a separate child candidate. The child showed parent lineage and the full original-base diff, including CRLF-to-LF facts. +3. Accepted the child; exact source bytes still contained the original subtraction. Applied it; source bytes exactly matched the reviewed addition/docstring candidate. +4. Continued after Apply; a fresh draft opened with focus on the goal. Edited that goal to multiplication and built another candidate. Its diff base was the newly applied docstring/addition bytes, and its lineage identified the applied child. This third build left primary source unchanged. +5. Reloaded and reopened history. All three candidate chains, the correction and acceptance decisions, and the application independently verified and were sealed. Exactly six process launches were recorded: three explicit provider starts and three structural checks. Review, Accept, Apply, and Continue added no provider launches. +6. Verified desktop and 320px layouts, light/dark presentation, keyboard arrow navigation between tabs, search, and 200% CSS zoom. Mobile document width remained 320px; zoomed layout did not overflow the viewport. CSS zoom is not browser-toolbar zoom. + +Evidence: `tmp/p3-wheel-browser/wheel-verification.json`, `tmp/p3-wheel-browser-*.json`, and `tmp/p3-wheel-*.png`. One automation attempt selected the previous candidate while the next Start response was pending; reopening after completion verified the correct continuation. It is not counted as a successful navigation attempt. + +Separately, the real browser recovery button restored an interrupted two-file source fixture and cleared its marker (`tmp/p3-cut-b9c96f26`). + +## Independent transaction and authority checks + +A fresh two-file process-death matrix ran against the final production code. Every case passed its expected outcome, with exact source inventories, verified evidence, and idempotent repeat recovery. `tmp/p3-final-matrix.json` records all fixture roots. + +| Process death boundary | Verified outcome | +|---|---| +| Reserved marker, before prepared, after prepared | Signed no-write rejection; original source preserved; marker cleared | +| After started | Verified rollback; original source preserved | +| Before signed stage receipt | Unknown temp preserved; recovery block retained | +| After signed stage, before rename | Exact signed temp reconciled; original source restored | +| After first file write | Partial application rolled back exactly | +| After both file writes | Full scope verified; application completed and sealed | +| Applied terminal before seal | Existing outcome sealed without rewriting source | +| Seal before marker cleanup | Sealed outcome projected; marker cleared without reapplication | + +Additional actual rollback process deaths passed before rollback rename (`tmp/p3-cut-51d8dc53`) and after rollback rename before restored receipt (`tmp/p3-cut-cc83685e`). Recovery reused signed rollback identities, restored exact bytes, sealed rollback, cleared the marker, and returned idle on repetition. A same-byte identity substitution after rollback rename was refused and preserved (`tmp/p3-cut-97a343df`). Durable repository tests also exercise native rollback restart and continuation crash/CAS recovery. + +Other independent checks passed: + +- Native replacement/restoration/create/remove, supported metadata, owner-only creates, missing parents, separate-process exclusion, hard-link/ADS refusal, and third-byte/same-byte-identity conflict refusal. +- A second TORQ installation sharing the authority refused new work while a crashed transaction's marker remained active. +- Unchanged scoped context modified after a crash was preserved and prevented false application success (`tmp/p3-cut-21584987`). +- Tampered encrypted journal and missing signer key blocked recovery without creating or changing any files or identity (`tmp/p3-cut-53c82388`, `tmp/p3-cut-45d56318`). +- Two disjoint signed applications resisted mutable-result swaps and cross-record locator substitution; exact retries under a new session caused no source writes (`tmp/p3-replay-8144a319`). +- Historical P2 evidence generated before the P3 implementation remained readable with exact CRLF/no-final-newline facts after cache removal and live-source drift. Wrong sequence and artifact tampering were refused; original P2 evidence hashes remained unchanged (`tmp/p3-legacy-a720f551`). + +## Practical limits + +P3 creates/replaces bounded UTF-8 files in existing directories. It does not execute generated code, run project unit tests, change credentials, or perform Git operations. Structural-check success is labelled accordingly. Generation retains the existing production platform containment restrictions. + +Application is recoverable per file, not a multi-file atomic transaction. The kernel lease coordinates TORQ installations for the same user/host. Pause non-TORQ editors, autosave, formatters, and other writers during Apply/recovery: a write racing the final check and native rename can be overwritten. Observed/preexisting third-party bytes or substituted identities are rejected. Unknown staging and a create-rollback crash after deletion but before its restored receipt remain explicitly recovery-blocked; absence alone is not identity evidence. + +## macOS CI follow-up + +The initial PR head `b46b448` passed Windows and Linux CI but failed the native macOS transaction test because Python on Darwin does not expose `os.listxattr`. This was a fail-closed platform defect, not a passing platform gate. The follow-up uses descriptor-bound Darwin `flistxattr` and ACL APIs, bounded parsing, strict errors, and before/after BSD-flag checks; it does not skip the test or substitute path-based reads. + +Root reran the native adapter, hermetic boundary, and candidate integration selection: **50 passed**; Ruff and Mypy for all three target platforms passed. G2A separately approved the adapter and distinguished mocked API tests from real Darwin execution. Native macOS CI must pass on the updated PR head before merge. The detailed browser/wheel evidence above describes the pre-follow-up package; dashboard assets and Windows execution behavior are unchanged by this Darwin-only fix. diff --git a/docs/plans/2026-09-16-dashboard-p3-g1r-review.md b/docs/plans/2026-09-16-dashboard-p3-g1r-review.md new file mode 100644 index 0000000..5219810 --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-p3-g1r-review.md @@ -0,0 +1,188 @@ +# Dashboard P3 G1R review + +Reviewed `2026-09-16-dashboard-p3-contract.md` and its closed-schema/crash-order +addendum against merged P2 baseline +`e32ecdc3ed2ab3df1f6fa00e3d49994532c4474a`, the sealed candidate evidence +contract, current task projection/store, Fleet session handling, and the existing +unsafe approval helper. This is a contract review; no native source mutation, +provider call, or recovery exercise was performed. + +## Judgment + +**APPROVE — `READY_FOR_P3_BUILDER`.** The amended contract is implementable as a +bounded task-specific review, refinement, acceptance, and explicit application +service. It pins the bytes reviewed to the bytes eligible for application, +separates historical evidence from current applicability, and defines a +recoverable per-file primary transaction without claiming the broader design-only +schema-v3 governed-run migration. + +## Findings + +1. **Historical review has one evidence authority.** Plan, Changes, and Checks + resolve from exact `(task_id, candidate_ready_sequence)` P2 receipts and + encrypted artifacts. The review hash covers a canonical immutable core, all + displayed diff components come from that core, and live source, disposable + candidate cache, or upgraded checker bytes cannot silently replace history. + Missing, substituted, cross-task, unsealed, or unresolved evidence fails + closed. The normalized structural command is labelled accurately because P2 + retained its argv hash rather than raw historical argv. + +2. **Review and application evidence are closed and independently linked.** + `CandidateRef`, `DecisionRef`, `ArtifactRef`, review decisions, application + events, journals, and the global marker have exact bounded shapes. Append and + portable verification enforce receipt hashes, manifest hashes, sequence/order, + common-context immutability, terminal/seal rules, and cross-chain verification. + Generic signed `audit` content, mutable task state, or an opaque matching ID + cannot authorize acceptance or application. + +3. **Acceptance and Apply are separate consequences.** `candidate_accepted` + records the exact reviewed candidate and a fresh scoped-source match but makes + no project write. Apply requires a second authenticated idempotent request and + independently verifies the accepted decision, P2 evidence, project mapping, + complete scoped preimages, and absent create targets. Replays return the + recorded result; a new request ID cannot apply an already-applied decision + twice. No provider or checker is dispatched by review, Apply, or recovery. + +4. **The primary transaction closes cross-process and crash windows.** A + physical-root kernel lease coordinates aliases, while a fixed per-user global + marker keeps other installations blocked after process death. The final order + durably reserves the request and creates, flushes, and verifies the signed + one-receipt apply authority before any shared marker. Therefore a + pre-journal recovery can authenticate the existing identity and seal the + no-mutation `apply_rejected` result without minting keys or certificates + during recovery. Unknown, corrupt, or foreign-owner markers remain blocked. + +5. **Writes and recovery are byte- and path-constrained.** Apply v1 requires + existing safely anchored parent directories and creates or removes no primary + directories. POSIX dirfd/nofollow and Windows no-reparse handle-relative + operations replace only evidence-derived changed files. The immutable journal + binds ordered preimages/results and fixed metadata policy before + `apply_started`. Recovery changes a target only when its bytes match an + authenticated preimage or intended result; any third state, unknown temp, + identity substitution, or unverifiable metadata stays recovery-required. + Applied and rolled-back terminals require exact full scoped verification. + +6. **Refinement is a new candidate, not a rewrite of sealed P2 history.** Closed + plan/input v2 shapes bind the parent candidate, original base, correction + revision/hash/decision, and verified parent context without a circular plan + commitment. A child emits a complete desired operation set against the + original base, including explicit visibility of dropped parent changes. + Durable reservation precedes dispatch and restart never redispatches. After a + verified Apply, continuation uses a freshly reviewed live-source base. + +7. **The user-facing scope remains truthful.** Search is navigation rather than + authority; opening a result re-verifies evidence. Delayed responses cannot + enable a stale selection. Accept copy says it records approval; Apply copy + identifies source modification. P3 performs no Git commit, push, merge, + deployment, arbitrary shell, generated-code execution, credential change, or + project test runner, and structural validation is not presented as tests. + +## Implementation-seam addendum + +The `apply_authority_created` amendment preserves the existing general receipt +verifier invariant: a zero-count anchor is initialization state, never verified +application evidence. Original Apply must append and flush the unique signed +begin event and require ordinary verification of its one-receipt unsealed +manifest/anchor before creating the shared primary marker. + +A restart before the marker distinguishes outcomes by read-only verification. A +fully committed begin prefix may be reopened without creation and terminalized as +the bounded no-mutation `apply_rejected`; a partial or unverifiable first commit +is quarantined as preparation-failed. Neither path recreates keys, certificates, +trust anchors, receipts, or artifacts, and neither permits a source write. + +Post-marker recovery likewise uses existing identity only. Before committing an +authenticated uncovered tail, it verifies the covered begin prefix, every tail +signature and semantic link, and the nested +`detail.journal_artifact` cipher/plain hashes plus closed journal schema. The +legacy automatic tail path checks only a top-level artifact reference and cannot +run first for this contract. `live_catching_up` remains a recovery input state; +it never projects accepted or applied success by itself. + +### Staged-identity recovery addendum + +**APPROVE.** The amended recovery seam closes the attribution gap between an +atomic rename and its durable written receipt. Every journal operation now binds +the exact stable `parent_identity` and nullable preimage `before_identity`, each +with only nonnegative integer `volume` and `file_id` fields; the preimage identity +is null only for a create. Content hashes and metadata checks remain separate +from these stable identities. + +Before rename, the narrow native callback runs with the finalized exclusive temp +handle still held and durably appends and verifies the exact +`apply_file_staged` event. Native commit then rechecks the staged identity/hash +and journal-bound parent identity. `apply_file_written` crosslinks the staged +receipt by sequence and receipt hash, so recovery inherits the signed result +identity without relying on process memory. Desired bytes are attributable to +TORQ only when their stable identity matches that signed staged identity. An +unsigned crashed temp or equal desired bytes under another identity remains +`recovery_required`; it is never deleted, overwritten, or promoted by content +alone. This amendment is builder-ready within the contract's cooperating-host, +non-hostile-writer boundary. + +### Rollback staged-identity addendum + +**APPROVE with the following closed protocol.** A replacement rollback creates a +temp in a deterministic rollback-only namespace, distinct from the forward-stage +leaf. Before rename it appends and verifies exactly one +`apply_rollback_file_staged` detail containing `rollback_started_sequence`, +`operation_index`, `path`, `base_hash`, and `staged_identity`. After rename it +appends exactly one `apply_rollback_file_restored` detail containing those first +four fields plus `staged_sequence` and `staged_receipt_hash`. The restored event +must crosslink the matching staged receipt. Events follow the unique rollback +start and process affected operations in strict reverse index order. + +For a replacement, `base_hash` equals the journal preimage hash and +`staged_identity` is the finalized rollback temp identity. Restart reuses that +single signed temp; it never creates a second stage identity. It may commit the +exact revalidated temp while the target still has the signed forward identity, +or append a missing restored receipt when the base bytes have the signed rollback +identity. A missing temp while the forward target remains, or base-equivalent +bytes under any other identity, stays `recovery_required`. An untouched preimage +is accepted only with the journal's original `before_identity`. + +For a create rollback, the staged event is the signed delete intent: +`base_hash` is null and `staged_identity` must equal the forward signed result +identity. Anchored deletion may proceed only while that exact target remains. The +restored crosslink is appended after verified absence. If the process crashes +after deletion but before that receipt, absence alone cannot prove the delete and +the transaction remains `recovery_required`; no equal-content or equal-state +identity waiver is allowed. Tests must inject crashes on both sides of rollback +stage, rename, restored receipt, delete intent, unlink, and delete-restored +receipt, including repeated recovery attempts. + +### Concurrent external-writer boundary + +**APPROVE with explicit disclosure.** The per-primary kernel lease serializes +cooperating TORQ installations, while the held root/parent handles, nofollow or +no-reparse traversal, content and identity checks, signed stage identities, and +post-result verification reject drift that the transaction observes. These +controls do not provide a portable atomic compare-and-replace of the destination +file identity. A non-TORQ process can replace a target after the final identity +check and before the anchored rename, causing that racing edit to be displaced. + +Apply and recovery therefore require other editors, formatters, watchers, and +tools that can write the project to remain paused for the operation. The contract, +README, UI, and tests must state this precondition and must not claim protection +against arbitrary concurrent external writers. `Third-party edits are never +overwritten` applies only to preexisting or otherwise observed third states that +fail the anchored content/identity checks. This limitation does not permit any +weakening of root or parent anchoring, staged provenance, revalidation, or +recovery refusal for an observed mismatch. + +## Builder and G2A release gate + +Builder may begin within this contract. Its first executable gate is the native +isolated fixture: prove anchored replacement, cross-installation exclusion, +injected crashes at every journal/evidence/write boundary, exact application, +exact restoration or persistent block, and sealed cross-chain projection before +enabling UI Apply. The complete integration must then exercise review -> +correction -> child -> Accept with unchanged source -> Apply exact bytes -> +reload/history -> Continue using the real fixture provider, checker, receipt +authority, and native primary writes. + +G2A must independently verify the contract's tamper, stale-source, link/reparse/ +hardlink/case, third-state recovery, idempotent replay, cross-installation, +session/origin, UI race/accessibility, package, platform, lint/type, full-suite, +and installed-wheel gates. Fixture execution is not live-vendor validation, and +no live paid-provider claim is authorized or needed for this P3 release. diff --git a/docs/plans/2026-09-16-dashboard-p3-g2a-review.md b/docs/plans/2026-09-16-dashboard-p3-g2a-review.md new file mode 100644 index 0000000..8e74b52 --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-p3-g2a-review.md @@ -0,0 +1,118 @@ +# Dashboard P3 G2A review + +## Verdict + +**APPROVE — bounded P3 review, refinement, acceptance, explicit Apply, and +recoverable per-file application scope.** + +I reviewed the final shared working-tree implementation against the approved P3 +contract. The source transaction remains constrained to evidence-derived UTF-8 +create/replace operations and does not add arbitrary command execution, +generated-code execution, project test execution, credential changes, or Git +operations. + +This approval covers the application authority boundaries reviewed below. Root +owns the separate final wheel, real-browser, and complete-repository gates; +this receipt does not claim those checks. + +## Independent review evidence + +- Read the P3 contract and G1R review. Reviewed the immutable task resolver, + review/application coordinator and mutable-store boundaries, task plan/start + validation, receipt lifecycle validator, anchored primary transaction and + marker paths, Fleet HTTP session/replay routing, and task UI request identity + and eligibility logic. +- Ran: + + ```text + python -m pytest tests/test_candidate_review.py \ + tests/test_candidate_decision_evidence.py \ + tests/test_fleet_ui_runtime.py tests/test_fleet_ui.py \ + -q -p no:cacheprovider + 16 passed + + node tests/js/task_runtime.test.cjs src/torq_cli/data/fleet/task.js + task runtime contract checks passed + + git diff --check + ``` + +## Findings resolved before approval + +- Continuation v2 plans now reject a stale draft server-side; disabling Start in + the browser is no longer the only protection. +- Continuation replay reconstructs the exact intended draft from the durable + request and independently verified applied candidate, so a process death + after the draft write is retryable without trusting cached result data. + The pre-save active-context write was removed: a concurrent ordinary draft + now wins its CAS conflict without acquiring continuation lineage. +- The immutable child resolver independently validates the sealed Apply terminal + *and* its sealed acceptance artifact, rather than relying on mutable review + state or a generic signed Apply record. +- Rejected and rolled-back applications remain historical outcomes but permit a + fresh explicit Apply after source freshness checks. Applied and + recovery-required outcomes still block it. The UI derives retry request + identity from the prior outcome and renders the corresponding remedy. +- Accepted request replay remains limited to exact request bodies and the + rotated-session replay routes; it does not widen chat or other mutations. +- The rollback-stage protocol uses distinct signed rollback temps and binds + stage/restored events to the original operation, preserving identity through + a crash before or after rollback rename. + +## Boundaries and limitations + +The primary lease coordinates TORQ installations for one OS user and host. It +anchors roots and parents, rejects observable source drift, and fails closed on +unknown marker, identity, journal, artifact, or staged-file state. It is not a +lock over other editors or tools. The contract and README now require external +writers, including autosave and formatters, to abstain during Apply/recovery; +a write racing the final content/identity check and atomic rename is outside the +portable guarantee. Observed or pre-existing third-party states remain +recovery-blocking and are not overwritten. + +No live provider, user-project mutation outside isolated fixtures, wheel smoke, +or browser run was performed by this reviewer. + +## Darwin native metadata follow-up — 2026-09-17 + +**APPROVE — bounded macOS metadata-adapter follow-up.** This supplements the +prior approval, which did not include a Darwin kernel run. + +The POSIX transaction now uses Darwin's descriptor-bound `flistxattr` ABI, +instead of Python's unavailable path/API surface. It rejects every xattr or ACL +enumeration failure, including unavailable-feature errors and a null ACL handle; +it therefore never treats unknown metadata as empty. A present ACL entry rejects +the target. The empty extended-ACL result is the Darwin `acl_get_entry` result +`-1` with `EINVAL`; this matches Apple's documented Darwin result convention +(`0` returns an entry, `-1` otherwise). Nonzero BSD `st_flags` also reject. + +The snapshot rechecks xattrs/ACLs and BSD flags after the held-descriptor read, +so the evidence snapshot does not accept a metadata transition during that read. +The existing anchored-root, no-follow, identity and permission-policy checks +remain unchanged. + +I ran `python -m pytest tests/test_primary_transaction.py -p +no:cacheprovider -ra` (**3 passed**), `python -m mypy +src/torq_cli/safety/primary_transaction.py` (clean), and `git diff --check`. +Those checks exercise the mocked Darwin ABI and static typing on this host; they +are not a Darwin kernel verification. macOS CI remains the required platform +gate before publishing this follow-up. + +### Correction: normal absence of a Darwin extended ACL + +The preceding null-ACL sentence was too strict. Apple Libc's +[`acl_file.c`](https://github.com/apple-oss-distributions/Libc/blob/main/posix1e/acl_file.c) +implements `acl_get_fd_np` by initializing `acl` to null and returning it after +calling `filesec_get_property(FILESEC_ACL, ...)`. It deliberately discards that +call's result. Apple's +[`filesec.c`](https://github.com/apple-oss-distributions/Libc/blob/main/gen/filesec.c) +defines an absent `FILESEC_ACL` property as `-1` with `errno = ENOENT`. +Consequently, a normal macOS plain file yields a null ACL pointer with `ENOENT`. + +The corrected, narrowly approved rule resets `errno` immediately before +`acl_get_fd_np` and treats **only** null plus `ENOENT` as no extended ACL. A +non-null ACL is enumerated and rejected if it has an entry; all other null/error +results remain `task_apply_metadata_unreadable`. This preserves the fail-closed +policy for unknown metadata while allowing ordinary files. The follow-up mock +must model null-plus-`ENOENT` for the plain-file case. Native macOS CI remains +the final platform gate for this correction. diff --git a/docs/plans/2026-09-16-dashboard-ux-plan.md b/docs/plans/2026-09-16-dashboard-ux-plan.md index 2ef837a..1b76ee6 100644 --- a/docs/plans/2026-09-16-dashboard-ux-plan.md +++ b/docs/plans/2026-09-16-dashboard-ux-plan.md @@ -1,6 +1,6 @@ # TORQ task workspace: dashboard review and implementation plan -Status: bounded P0/P1 and separately approved candidate-only P2 implemented on 2026-09-16; P3 remains unimplemented. See `2026-09-16-dashboard-p2-contract.md` and the P2 verification receipts. Scope: TORQ CLI in E:/Torq-CLI. +Status: bounded P0/P1 and candidate-only P2 implemented on 2026-09-16; bounded P3 review, refinement, explicit Apply, recovery, and continuation implemented and locally verified on 2026-09-17. See `2026-09-16-dashboard-p3-contract.md` and the P3 G1D/G1R/G2A receipts. GitHub CI and merge remain delivery gates. The original research and roadmap below are historical, broader product direction, not a claim of arbitrary execution or full competitor parity. Scope: TORQ CLI in E:/Torq-CLI. Historical P0/P1 correction: that increment delivered only the opt-in Workspace, truthful root/provider/session capability metadata, collection guidance, and diff --git a/src/torq_cli/application/candidate_review.py b/src/torq_cli/application/candidate_review.py new file mode 100644 index 0000000..ba38426 --- /dev/null +++ b/src/torq_cli/application/candidate_review.py @@ -0,0 +1,1881 @@ +"""Verified candidate review, signed acceptance, and explicit primary application.""" + +from __future__ import annotations + +import json +import re +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +from torq_cli.application.candidate_tasks import CandidateTaskService +from torq_cli.application.review_store import ReviewStore +from torq_cli.domain.candidate_decision_evidence import ( + APPLY_CONTRACT, + REVIEW_CONTRACT, + validate_decision_ref, +) +from torq_cli.domain.task_review import ResolvedTaskReview, resolve_task_review +from torq_cli.safety.evidence_broker import EvidenceBroker +from torq_cli.safety.primary_marker import PrimaryMarkerAuthority +from torq_cli.safety.primary_transaction import AnchoredFile, AnchoredPrimary +from torq_cli.safety.receipts import ( + FileRunKeyStore, + ReceiptChain, + read_verified_artifact, + read_verified_prefix_artifact, + verify_receipt_store, +) +from torq_cli.safety.task_workspace import canonical_json, digest_bytes, digest_json, validate_disjoint_roots + + +def _manifest(files: Mapping[str, bytes]) -> str: + return digest_json( + [ + {"path": path, "content_bytes": len(content), "content_hash": digest_bytes(content)} + for path, content in sorted(files.items(), key=lambda item: item[0].casefold()) + ] + ) + + +def _append(broker: EvidenceBroker, body: Mapping[str, Any]) -> dict[str, Any]: + capability = broker.issue("orchestrator") + return broker.append(capability.token, "audit", body) + + +def _artifact(broker: EvidenceBroker, name: str, content: str) -> dict[str, str]: + capability = broker.issue("orchestrator") + path = broker.write_artifact(capability.token, name, content) + if broker.read_artifact(path).encode("utf-8") != content.encode("utf-8"): + raise ValueError("candidate_artifact_content_changed") + return { + "artifact": path.relative_to(broker.run_root).as_posix(), + "artifact_hash": ReceiptChain.hash_file(path), + "content_hash": digest_bytes(content.encode("utf-8")), + } + + +class CandidateReviewService: + """Single service boundary used by Fleet HTTP and recovery startup.""" + + def __init__( + self, + *, + tasks: CandidateTaskService, + state_root: Path, + common_authority_root: Path, + ) -> None: + self.tasks = tasks + self.state_root = state_root.absolute() + if self.state_root != tasks.state_root: + raise ValueError("candidate_review_state_root_mismatch") + validate_disjoint_roots( + [ + *(project.root for project in tasks.projects.values()), + tasks.state_root, + tasks.work_root, + common_authority_root.absolute(), + ] + ) + self.store = ReviewStore(self.state_root) + self.review_evidence_root = self.state_root / "review-evidence" + self.apply_evidence_root = self.state_root / "apply-evidence" + self.review_evidence_root.mkdir(parents=True, exist_ok=True) + self.apply_evidence_root.mkdir(parents=True, exist_ok=True) + self.markers = PrimaryMarkerAuthority(common_authority_root) + self.tasks.project_gate = self.markers.assert_clear + self.tasks.input_bundle_provider = self._child_input_bundle + self.tasks.plan_transformer = self._transform_plan + self.tasks.draft_saved_observer = self._draft_saved + self.tasks.draft_deleted_observer = self._draft_deleted + + def review(self, task_id: str, ready_sequence: int) -> dict[str, Any]: + resolved = resolve_task_review(self.tasks.evidence_root, task_id, ready_sequence) + acceptance: dict[str, Any] | None = None + application: dict[str, Any] | None = None + snapshot = self.store.snapshot() + for record in sorted(snapshot["decisions"].values(), key=lambda item: item.get("ordinal", 0), reverse=True): + if not isinstance(record, Mapping): + continue + request = record.get("request") + if isinstance(request, Mapping) and ( + request.get("task_id"), request.get("ready_sequence"), request.get("review_hash") + ) == (task_id, ready_sequence, resolved.candidate_ref["review_hash"]): + try: + acceptance = self._replay_accept(record) + break + except (OSError, ValueError): + continue + if acceptance is not None: + for record in sorted(snapshot["applications"].values(), key=lambda item: item.get("ordinal", 0), reverse=True): + if not isinstance(record, Mapping): + continue + request = record.get("request") + if isinstance(request, Mapping) and request.get("candidate") == resolved.candidate_ref and request.get("acceptance") == acceptance.get("acceptance"): + try: + application = self._replay_application(record) + break + except (OSError, ValueError): + continue + reason: str | None = None + try: + self._assert_project_clear(resolved) + self._assert_source_base(resolved) + except (OSError, RuntimeError, ValueError) as exc: + reason = self._reason(exc, "candidate_source_unavailable") + application_state = None if application is None else application.get("state") + application_blocks_apply = application_state in {"applied", "recovery_required"} + envelope = dict(resolved.envelope) + envelope["eligibility"] = { + "can_accept": reason is None and acceptance is None, + "can_apply": reason is None and acceptance is not None and not application_blocks_apply, + "reason": reason or ( + "candidate_already_applied" if application_state == "applied" + else "candidate_apply_recovery_required" if application_state == "recovery_required" + else "candidate_already_accepted" if acceptance is not None and application is None + else None + ), + } + envelope["acceptance"] = acceptance + envelope["application"] = application + return envelope + + def correction(self, task_id: str, ready_sequence: int) -> dict[str, Any]: + resolve_task_review(self.tasks.evidence_root, task_id, ready_sequence) + return self.store.correction(task_id, ready_sequence) or { + "task_id": task_id, "ready_sequence": ready_sequence, "revision": 0, + "text": "", "content_hash": digest_bytes(b""), + } + + def save_correction( + self, + task_id: str, + ready_sequence: int, + *, + text: str, + expected_revision: int, + ) -> dict[str, Any]: + resolved = resolve_task_review(self.tasks.evidence_root, task_id, ready_sequence) + self._assert_project_clear(resolved) + return self.store.save_correction( + task_id, ready_sequence, text=text, expected_revision=expected_revision + ) + + def review_child_plan( + self, + task_id: str, + ready_sequence: int, + *, + request_id: str, + correction_revision: int, + correction_hash: str, + review_hash: str, + subject_id: str, + ) -> dict[str, Any]: + resolved = resolve_task_review(self.tasks.evidence_root, task_id, ready_sequence) + correction = self.store.correction(task_id, ready_sequence) + if correction is None or correction.get("revision") != correction_revision: + raise ValueError("candidate_correction_revision_stale") + if ( + correction.get("content_hash") != correction_hash + or resolved.candidate_ref["review_hash"] != review_hash + ): + raise ValueError("candidate_child_context_invalid") + body = { + "task_id": task_id, "ready_sequence": ready_sequence, + "review_hash": resolved.candidate_ref["review_hash"], + "correction_revision": correction_revision, + "correction_hash": correction["content_hash"], + } + record, created = self.store.reserve( + request_kind="child", request_id=request_id, body=body, id_prefix="decision-" + ) + if not created: + return self._replay_child_plan(record) + decision_id = str(record["record_id"]) + try: + self._assert_project_clear(resolved) + self._assert_source_base(resolved) + parent_plan = resolved.plan + plan = { + "contract": "torq-candidate-plan-v2", + "project_id": parent_plan["project_id"], "goal": correction["text"], + "draft_revision": correction_revision, + "input_paths": parent_plan["input_paths"], "output_paths": parent_plan["output_paths"], + "absent_output_paths": parent_plan["absent_output_paths"], + "base_manifest_hash": resolved.candidate_ref["base_scope_manifest_hash"], + "provider": parent_plan["provider"], "model": parent_plan["model"], + "provider_binary_hash": parent_plan["provider_binary_hash"], + "check_profile_id": parent_plan["check_profile_id"], + "check_profile_version": parent_plan["check_profile_version"], + "helper_hash": parent_plan["helper_hash"], "limits": parent_plan["limits"], + "lineage": { + "mode": "refinement", "parent_candidate": resolved.candidate_ref, + "correction_revision": correction_revision, + "correction_hash": correction["content_hash"], + "root_base_scope_hash": resolved.candidate_ref["base_scope_manifest_hash"], + }, + } + saved = self.tasks.store.save_plan(plan) + plan_hash = str(saved["plan_hash"]) + chain = ReceiptChain( + self.review_evidence_root, decision_id, FileRunKeyStore(self.review_evidence_root), + profile_version="candidate-review-v1", policy_version="candidate-review-v1", + ) + broker = EvidenceBroker(chain) + receipt = _append(broker, { + "review_contract": REVIEW_CONTRACT, "event": "correction_requested", + "decision_id": decision_id, "request_digest": record["request_digest"], + "candidate": resolved.candidate_ref, + "actor": {"subject_id": subject_id, "assurance": "local_operator_session"}, + "detail": { + "correction_revision": correction_revision, + "correction_hash": correction["content_hash"], "child_plan_hash": plan_hash, + }, + }) + manifest_path = broker.seal() + decision = { + "decision_id": decision_id, "decision_sequence": receipt["sequence"], + "decision_receipt_hash": receipt["receipt_hash"], + "terminal_manifest_hash": digest_bytes(manifest_path.read_bytes()), + } + context = { + "plan_hash": plan_hash, "parent_candidate": resolved.candidate_ref, + "correction_decision": decision, "correction_revision": correction_revision, + "correction_hash": correction["content_hash"], + } + self.store.save_child_plan(plan_hash, context) + result = { + "schema": "torq-candidate-child-plan-v1", "plan": saved, + "plan_hash": plan_hash, "correction_decision": decision, + } + self.store.update(decision_id, application=False, state="child_plan_ready", result=result) + return result + except BaseException as exc: + finding = self._reason(exc, "candidate_child_plan_failed") + self.store.update(decision_id, application=False, state="failed", finding=finding) + raise ValueError(finding) from exc + + def start_revision(self, *, request_id: str, plan_hash: str, replay_only: bool = False) -> dict[str, Any]: + self.store.child_plan(plan_hash) + method = self.tasks.replay_start if replay_only else self.tasks.start + return method(request_id=request_id, plan_hash=plan_hash) + + def continue_task(self, *, request_id: str, application_id: str) -> dict[str, Any]: + body = {"application_id": application_id} + record, created = self.store.reserve( + request_kind="continuation", request_id=request_id, body=body, + id_prefix="continuation-", + ) + if not created: + return self._replay_continuation(record) + try: + return self._complete_continuation(record) + except BaseException as exc: + finding = self._reason(exc, "candidate_continuation_failed") + self.store.update( + str(record["record_id"]), application=False, state="failed", finding=finding + ) + raise ValueError(finding) from exc + + def replay_continuation( + self, *, request_id: str, application_id: str + ) -> dict[str, Any]: + return self._replay_continuation( + self.store.replay( + request_kind="continuation", request_id=request_id, + body={"application_id": application_id}, + ) + ) + + def replay_child_plan( + self, + task_id: str, + ready_sequence: int, + *, + request_id: str, + correction_revision: int, + correction_hash: str, + review_hash: str, + ) -> dict[str, Any]: + body = { + "task_id": task_id, + "ready_sequence": ready_sequence, + "review_hash": review_hash, + "correction_revision": correction_revision, + "correction_hash": correction_hash, + } + return self._replay_child_plan( + self.store.replay(request_kind="child", request_id=request_id, body=body) + ) + + def _child_input_bundle(self, plan: Mapping[str, Any]) -> Mapping[str, Any]: + plan_hash = digest_json(plan) + context = self.store.child_plan(plan_hash) + parent = context.get("parent_candidate") + if not isinstance(parent, Mapping): + raise ValueError("candidate_child_context_invalid") + resolved = self._resolve_candidate_ref(parent) + mode = plan.get("lineage", {}).get("mode") if isinstance(plan.get("lineage"), Mapping) else None + if mode == "continuation": + application_id = context.get("application_id") + if not isinstance(application_id, str): + raise ValueError("candidate_continuation_context_invalid") + application = self.application(application_id) + application_ref = self._application_ref(application) + if ( + application.get("state") != "applied" + or context.get("application") != application_ref + or plan.get("lineage") != { + "mode": "continuation", "parent_candidate": resolved.candidate_ref, + "application": application_ref, + } + ): + raise ValueError("candidate_continuation_context_invalid") + project = self.tasks.projects[str(plan["project_id"])] + from torq_cli.safety.task_workspace import snapshot_source + + fresh = snapshot_source(project.root, [str(item) for item in plan["input_paths"]]) + if fresh.manifest_hash != plan.get("base_manifest_hash"): + raise ValueError("candidate_continuation_context_invalid") + value = { + "contract": "torq-candidate-input-v2", "plan": dict(plan), + "files": fresh.bundle(), + "parent_context": { + "candidate": resolved.candidate_ref, + "files": self._bundle(resolved.result_files), + }, + "correction": None, + } + if len(canonical_json(value).encode("utf-8")) > 4_194_304: + raise ValueError("candidate_child_input_too_large") + return value + correction = self.store.correction(str(parent["task_id"]), int(parent["ready_sequence"])) + if ( + correction is None + or correction.get("revision") != context.get("correction_revision") + or correction.get("content_hash") != context.get("correction_hash") + ): + raise ValueError("candidate_child_context_invalid") + decision = context.get("correction_decision") + self._verify_correction_decision(decision, resolved, plan_hash, correction) + value = { + "contract": "torq-candidate-input-v2", "plan": dict(plan), + "files": self._bundle(resolved.base_files), + "parent_context": { + "candidate": resolved.candidate_ref, "files": self._bundle(resolved.result_files), + }, + "correction": { + "revision": correction["revision"], "text": correction["text"], + "content_hash": correction["content_hash"], "decision": decision, + }, + } + if len(canonical_json(value).encode("utf-8")) > 4_194_304: + raise ValueError("candidate_child_input_too_large") + return value + + def _transform_plan(self, plan: Mapping[str, Any]) -> Mapping[str, Any]: + project_id = plan.get("project_id") + revision = plan.get("draft_revision") + if not isinstance(project_id, str) or not isinstance(revision, int) or isinstance(revision, bool): + return plan + context = self.store.continuation_context(project_id, revision) + if context is None: + context = self.store.active_continuation(project_id) + if context is None: + return plan + application_id = context.get("application_id") + if not isinstance(application_id, str): + raise ValueError("candidate_continuation_context_invalid") + application = self.application(application_id) + application_ref = self._application_ref(application) + if ( + application.get("state") != "applied" + or context.get("application") != application_ref + or context.get("parent_candidate") != application.get("candidate") + ): + raise ValueError("candidate_continuation_context_invalid") + transformed = dict(plan) + transformed["contract"] = "torq-candidate-plan-v2" + transformed["lineage"] = { + "mode": "continuation", "parent_candidate": application["candidate"], + "application": application_ref, + } + plan_hash = digest_json(transformed) + self.store.save_child_plan( + plan_hash, + { + "plan_hash": plan_hash, "mode": "continuation", + "parent_candidate": application["candidate"], + "application": application_ref, "application_id": application_id, + }, + ) + return transformed + + def _draft_saved(self, project_id: str, draft: Mapping[str, Any]) -> None: + context = self.store.active_continuation(project_id) + revision = draft.get("revision") + if context is not None and isinstance(revision, int) and not isinstance(revision, bool): + self.store.save_continuation_context(project_id, revision, context) + + def _draft_deleted(self, project_id: str) -> None: + self.store.set_active_continuation(project_id, None) + + def _replay_continuation(self, record: Mapping[str, Any]) -> dict[str, Any]: + request = record.get("request") + if ( + record.get("kind") != "continuation" + or not isinstance(request, Mapping) + or set(request) != {"application_id"} + or digest_json(request) != record.get("request_digest") + ): + raise ValueError("candidate_review_store_invalid") + if record.get("state") == "failed": + finding = record.get("finding") + raise ValueError(finding if isinstance(finding, str) else "candidate_continuation_failed") + return self._complete_continuation(record) + + def _complete_continuation(self, record: Mapping[str, Any]) -> dict[str, Any]: + """Finish or reconstruct one reserved continuation without trusting its cached result.""" + request = record.get("request") + record_id = record.get("record_id") + if ( + record.get("kind") != "continuation" + or not isinstance(record_id, str) + or not isinstance(request, Mapping) + or set(request) != {"application_id"} + or digest_json(request) != record.get("request_digest") + ): + raise ValueError("candidate_review_store_invalid") + application_id = request.get("application_id") + if not isinstance(application_id, str): + raise ValueError("candidate_continuation_application_invalid") + application = self.application(application_id) + if application.get("state") != "applied" or not isinstance(application.get("candidate"), Mapping): + raise ValueError("candidate_continuation_application_invalid") + resolved = self._resolve_candidate_ref(application["candidate"]) + project_id = str(resolved.plan["project_id"]) + self._assert_project_clear(resolved) + project = self.tasks.projects[project_id] + with AnchoredPrimary(project.root) as primary: + self._verify_primary(primary, resolved.result_files) + self._verify_scope_absence(primary, resolved) + + application_ref = self._application_ref(application) + context = { + "mode": "continuation", "parent_candidate": resolved.candidate_ref, + "application": application_ref, "application_id": application_id, + } + goal = f"Continue from: {str(resolved.plan['goal']).splitlines()[0][:240]}" + input_paths = sorted(resolved.result_files, key=str.casefold) + output_paths = [str(path) for path in resolved.plan["output_paths"]] + expected_fields = { + "project_id": project_id, + "goal": goal, + "input_paths": input_paths, + "output_paths": output_paths, + } + current = self.tasks.draft(project_id) + if current is not None and all(current.get(key) == value for key, value in expected_fields.items()): + draft = current + else: + revision = 0 if current is None else int(current["revision"]) + empty = ( + current is not None + and current.get("goal") == "" + and current.get("input_paths") == [] + and current.get("output_paths") == [] + ) + if current is not None and not empty: + ancestor = self._root_ancestor(resolved) + if current != { + "project_id": project_id, + "goal": ancestor.plan["goal"], + "input_paths": ancestor.plan["input_paths"], + "output_paths": ancestor.plan["output_paths"], + "revision": ancestor.plan["draft_revision"], + }: + raise ValueError("candidate_continuation_draft_occupied") + draft = self.tasks.save_draft( + project_id, goal=goal, + input_paths=input_paths, + output_paths=output_paths, + expected_revision=revision, + ) + self.store.set_active_continuation(project_id, context) + self.store.save_continuation_context(project_id, int(draft["revision"]), context) + result = {"schema": "torq-candidate-continuation-v1", "draft": dict(draft)} + self.store.update(record_id, application=False, state="continuation_ready", result=result) + return result + + @staticmethod + def _application_ref(application: Mapping[str, Any]) -> dict[str, Any]: + value = { + "decision_id": application.get("application_id"), + "decision_sequence": application.get("sequence"), + "decision_receipt_hash": application.get("receipt_hash"), + "terminal_manifest_hash": application.get("terminal_manifest_hash"), + } + if not validate_decision_ref(value): + raise ValueError("candidate_continuation_application_invalid") + return value + + def _root_ancestor(self, resolved: ResolvedTaskReview) -> ResolvedTaskReview: + current = resolved + seen: set[tuple[str, int]] = set() + while current.plan.get("contract") == "torq-candidate-plan-v2": + lineage = current.plan.get("lineage") + if not isinstance(lineage, Mapping): + raise ValueError("candidate_continuation_context_invalid") + parent = lineage.get("parent_candidate") + if not isinstance(parent, Mapping): + raise ValueError("candidate_continuation_context_invalid") + identity = (str(parent.get("task_id")), int(parent.get("ready_sequence", 0))) + if identity in seen: + raise ValueError("candidate_continuation_context_invalid") + seen.add(identity) + current = self._resolve_candidate_ref(parent) + return current + + @staticmethod + def _bundle(files: Mapping[str, bytes]) -> list[dict[str, Any]]: + return [ + { + "path": path, + "content": content.decode("utf-8"), + "content_bytes": len(content), + "content_hash": digest_bytes(content), + } + for path, content in sorted(files.items(), key=lambda item: item[0].casefold()) + ] + + def _verify_correction_decision( + self, + decision: object, + resolved: ResolvedTaskReview, + plan_hash: str, + correction: Mapping[str, Any], + ) -> None: + if not isinstance(decision, Mapping) or not validate_decision_ref(decision): + raise ValueError("candidate_correction_decision_invalid") + decision_id = str(decision["decision_id"]) + record = self.store.snapshot()["decisions"].get(decision_id) + if not isinstance(record, Mapping): + raise ValueError("candidate_review_store_invalid") + request = record.get("request") + expected_request = { + "task_id": resolved.candidate_ref["task_id"], + "ready_sequence": resolved.candidate_ref["ready_sequence"], + "review_hash": resolved.candidate_ref["review_hash"], + "correction_revision": correction["revision"], + "correction_hash": correction["content_hash"], + } + if ( + record.get("record_id") != decision_id + or record.get("kind") != "child" + or request != expected_request + or digest_json(expected_request) != record.get("request_digest") + ): + raise ValueError("candidate_correction_decision_mismatch") + root = self.review_evidence_root / decision_id + if verify_receipt_store(root).status != "verified": + raise ValueError("candidate_correction_decision_unverified") + rows = [ + json.loads(line) + for line in (root / "receipts.jsonl").read_text(encoding="utf-8").splitlines() + ] + if len(rows) != 1: + raise ValueError("candidate_correction_decision_invalid") + row = rows[0] + payload = row.get("payload", {}) + expected_ref = { + "decision_id": decision_id, + "decision_sequence": row.get("sequence"), + "decision_receipt_hash": row.get("receipt_hash"), + "terminal_manifest_hash": digest_bytes((root / "terminal-manifest.json").read_bytes()), + } + if ( + dict(decision) != expected_ref + or payload.get("review_contract") != REVIEW_CONTRACT + or payload.get("event") != "correction_requested" + or payload.get("decision_id") != decision_id + or payload.get("request_digest") != record.get("request_digest") + or payload.get("candidate") != resolved.candidate_ref + or payload.get("detail") + != { + "correction_revision": correction["revision"], + "correction_hash": correction["content_hash"], + "child_plan_hash": plan_hash, + } + ): + raise ValueError("candidate_correction_decision_mismatch") + + def _replay_child_plan(self, record: Mapping[str, Any]) -> dict[str, Any]: + request = record.get("request") + result = record.get("result") + if ( + record.get("kind") != "child" + or not isinstance(request, Mapping) + or set(request) + != { + "task_id", "ready_sequence", "review_hash", "correction_revision", + "correction_hash", + } + or digest_json(request) != record.get("request_digest") + or not isinstance(result, Mapping) + or set(result) != {"schema", "plan", "plan_hash", "correction_decision"} + or result.get("schema") != "torq-candidate-child-plan-v1" + or not isinstance(result.get("plan"), Mapping) + ): + raise ValueError("candidate_review_store_invalid") + resolved = resolve_task_review( + self.tasks.evidence_root, str(request["task_id"]), int(request["ready_sequence"]) + ) + correction = self.store.correction( + str(request["task_id"]), int(request["ready_sequence"]) + ) + if ( + resolved.candidate_ref["review_hash"] != request.get("review_hash") + or correction is None + or correction.get("revision") != request.get("correction_revision") + or correction.get("content_hash") != request.get("correction_hash") + ): + raise ValueError("candidate_child_context_invalid") + plan_hash = str(result["plan_hash"]) + projected_plan = dict(result["plan"]) + if projected_plan.pop("plan_hash", None) != plan_hash or digest_json(projected_plan) != plan_hash: + raise ValueError("candidate_review_store_invalid") + context = self.store.child_plan(plan_hash) + if context.get("parent_candidate") != resolved.candidate_ref: + raise ValueError("candidate_child_context_invalid") + self._verify_correction_decision( + result.get("correction_decision"), resolved, plan_hash, correction + ) + saved = self.tasks.store.snapshot()["plans"].get(plan_hash) + if saved != projected_plan: + raise ValueError("candidate_child_context_invalid") + return dict(result) + + def accept( + self, + *, + request_id: str, + task_id: str, + ready_sequence: int, + review_hash: str, + subject_id: str, + ) -> dict[str, Any]: + body = { + "task_id": task_id, "ready_sequence": ready_sequence, "review_hash": review_hash, + } + record, created = self.store.reserve( + request_kind="review", request_id=request_id, body=body, id_prefix="decision-" + ) + if not created: + return self._replay_accept(record) + decision_id = str(record["record_id"]) + try: + resolved = resolve_task_review(self.tasks.evidence_root, task_id, ready_sequence) + if resolved.candidate_ref["review_hash"] != review_hash: + raise ValueError("candidate_review_hash_mismatch") + self._assert_project_clear(resolved) + self._assert_source_base(resolved) + chain = ReceiptChain( + self.review_evidence_root, decision_id, FileRunKeyStore(self.review_evidence_root), + profile_version="candidate-review-v1", policy_version="candidate-review-v1", + ) + broker = EvidenceBroker(chain) + core = canonical_json(resolved.envelope["review"]) + review_artifact = _artifact(broker, "verified-review", core) + receipt = _append( + broker, + { + "review_contract": REVIEW_CONTRACT, + "event": "candidate_accepted", + "decision_id": decision_id, + "request_digest": record["request_digest"], + "candidate": resolved.candidate_ref, + "actor": {"subject_id": subject_id, "assurance": "local_operator_session"}, + "detail": { + "review_artifact": review_artifact, + "source_scope_hash": resolved.candidate_ref["base_scope_manifest_hash"], + }, + }, + ) + manifest_path = broker.seal() + if verify_receipt_store(chain.root).status != "verified": + raise ValueError("candidate_accept_evidence_unverified") + decision_ref = { + "decision_id": decision_id, + "decision_sequence": receipt["sequence"], + "decision_receipt_hash": receipt["receipt_hash"], + "terminal_manifest_hash": digest_bytes(manifest_path.read_bytes()), + } + result = { + "schema": "torq-candidate-acceptance-v1", "state": "accepted", + "candidate": resolved.candidate_ref, "acceptance": decision_ref, + "source_changed": False, + } + self.store.update(decision_id, application=False, state="accepted", result=result) + return result + except BaseException as exc: + finding = self._reason(exc, "candidate_accept_failed") + self.store.update(decision_id, application=False, state="failed", finding=finding) + raise ValueError(finding) from exc + + def apply( + self, + *, + request_id: str, + candidate: Mapping[str, Any], + acceptance: Mapping[str, Any], + subject_id: str, + ) -> dict[str, Any]: + body = {"candidate": dict(candidate), "acceptance": dict(acceptance)} + record, created = self.store.reserve( + request_kind="apply", request_id=request_id, body=body, id_prefix="application-" + ) + if not created: + return self._replay_application(record) + application_id = str(record["record_id"]) + broker: EvidenceBroker | None = None + primary: AnchoredPrimary | None = None + marker_written = False + started: dict[str, Any] | None = None + journal_hash: str | None = None + written: list[tuple[dict[str, Any], AnchoredFile, Mapping[str, Any]]] = [] + operations: list[dict[str, Any]] = [] + try: + resolved = self._resolve_candidate_ref(candidate) + accepted = self._resolve_acceptance(acceptance, resolved) + project = self.tasks.projects[str(resolved.plan["project_id"])] + chain = ReceiptChain( + self.apply_evidence_root, application_id, FileRunKeyStore(self.apply_evidence_root), + profile_version="candidate-apply-v1", policy_version="candidate-apply-v1", + ) + broker = EvidenceBroker(chain) + common = { + "apply_contract": APPLY_CONTRACT, "application_id": application_id, + "request_digest": record["request_digest"], "candidate": resolved.candidate_ref, + "acceptance": accepted, "actor": {"subject_id": subject_id, "assurance": "local_operator_session"}, + } + _append(broker, {**common, "event": "apply_authority_created", "detail": {"installation_id": self.store.installation_id}}) + if verify_receipt_store(chain.root).status != "verified": + raise ValueError("task_apply_authority_unverified") + primary = AnchoredPrimary(project.root) + if self.markers.read(primary) is not None: + raise ValueError("task_apply_recovery_pending") + operations, current = self._prepare_operations(primary, resolved) + marker = { + "schema": "torq-primary-pending-v1", "primary_identity_hash": primary.identity.digest(), + "installation_id": self.store.installation_id, "application_id": application_id, + "authority_locator": self.store.installation_id, "journal_hash": None, "phase": "reserved", + } + self.markers.write(primary, marker) + marker_written = True + journal = { + "schema": "torq-primary-journal-v1", "application_id": application_id, + "request_digest": record["request_digest"], "candidate": resolved.candidate_ref, + "acceptance": accepted, "primary_identity": primary.identity.value(), + "base_scope_manifest_hash": resolved.candidate_ref["base_scope_manifest_hash"], + "result_scope_manifest_hash": resolved.candidate_ref["candidate_scope_manifest_hash"], + "operations": operations, "created_directories": [], + } + journal_text = canonical_json(journal) + journal_hash = digest_bytes(journal_text.encode("utf-8")) + journal_artifact = _artifact(broker, "primary-journal", journal_text) + prepared = _append( + broker, + {**common, "event": "apply_prepared", "detail": { + "journal_artifact": journal_artifact, "journal_hash": journal_hash, + "primary_identity_hash": primary.identity.digest(), "operation_count": len(operations), + }}, + ) + self.markers.write(primary, {**marker, "journal_hash": journal_hash, "phase": "prepared"}) + started = _append( + broker, + {**common, "event": "apply_started", "detail": { + "prepared_sequence": prepared["sequence"], "prepared_receipt_hash": prepared["receipt_hash"], + }}, + ) + self.markers.write(primary, {**marker, "journal_hash": journal_hash, "phase": "started"}) + for operation, before in zip(operations, current, strict=True): + staged_receipt: dict[str, Any] | None = None + + def record_staged(identity: dict[str, int]) -> None: + nonlocal staged_receipt + staged_receipt = _append( + broker, + {**common, "event": "apply_file_staged", "detail": { + "started_sequence": started["sequence"], + "operation_index": operation["index"], "path": operation["path"], + "result_hash": operation["after_hash"], "staged_identity": identity, + }}, + ) + if verify_receipt_store(chain.root).status != "verified": + raise ValueError("task_apply_stage_unverified") + + applied_file = primary.replace( + str(operation["path"]), expected_before_hash=operation["before_hash"], + expected_parent_identity=before.parent_identity, + expected_target_identity=before.target_identity, + content=str(operation["after_content"]).encode("utf-8"), + permission_policy=dict(operation["permission_policy"]), + application_id=application_id, operation_index=int(operation["index"]), + staged_callback=record_staged, + ) + if staged_receipt is None: + raise ValueError("task_apply_stage_missing") + written.append((operation, applied_file, staged_receipt)) + _append( + broker, + {**common, "event": "apply_file_written", "detail": { + "started_sequence": started["sequence"], "operation_index": operation["index"], + "staged_sequence": staged_receipt["sequence"], + "staged_receipt_hash": staged_receipt["receipt_hash"], + "path": operation["path"], "result_hash": operation["after_hash"], + }}, + ) + self._verify_primary(primary, resolved.result_files) + terminal = _append( + broker, + {**common, "event": "candidate_applied", "detail": { + "started_sequence": started["sequence"], "journal_hash": journal_hash, + "result_scope_manifest_hash": resolved.candidate_ref["candidate_scope_manifest_hash"], + "operation_count": len(operations), + }}, + ) + manifest_path = broker.seal() + self.markers.write(primary, {**marker, "journal_hash": journal_hash, "phase": "terminal"}) + self.markers.clear(primary, installation_id=self.store.installation_id, application_id=application_id) + marker_written = False + result = { + "schema": "torq-candidate-application-v1", "state": "applied", + "application_id": application_id, "sequence": terminal["sequence"], + "receipt_hash": terminal["receipt_hash"], "terminal_manifest_hash": digest_bytes(manifest_path.read_bytes()), + "candidate": resolved.candidate_ref, "acceptance": accepted, + } + self.store.update(application_id, application=True, state="applied", result=result) + return result + except BaseException as exc: + finding = self._reason(exc, "task_apply_failed") + result = self._rollback_or_reject( + broker, primary, marker_written, started, written, journal_hash, record, application_id, + candidate, acceptance, subject_id, finding, operations, + ) + self.store.update(application_id, application=True, state=result["state"], finding=finding, result=result) + if result["state"] == "recovery_required": + return result + raise ValueError(finding) from exc + finally: + if primary is not None: + primary.close() + + def history(self, *, query: str = "", limit: int = 50, cursor: str | None = None) -> dict[str, Any]: + if len(query) > 256 or not isinstance(limit, int) or isinstance(limit, bool) or limit < 1 or limit > 100: + raise ValueError("candidate_history_query_invalid") + needle = query.casefold() + task_data = self.tasks.store.snapshot() + rows: list[dict[str, Any]] = [] + for task_id, task in task_data["tasks"].items(): + if not isinstance(task, Mapping) or re.fullmatch(r"run-task-[a-f0-9]{24}", task_id) is None: + continue + plan = task_data["plans"].get(task.get("plan_hash")) + goal = str(plan.get("goal", "")) if isinstance(plan, Mapping) else "" + project_id = str(plan.get("project_id", "")) if isinstance(plan, Mapping) else "" + label = self.tasks.projects.get(project_id) + root = self.tasks.evidence_root / task_id + ready_sequence: int | None = None + created_at: str | None = None + if verify_receipt_store(root).status == "verified": + try: + receipts = [json.loads(line) for line in (root / "receipts.jsonl").read_text(encoding="utf-8").splitlines()] + created_at = str(receipts[0].get("observed_at")) if receipts else None + ready_sequence = next( + int(row["sequence"]) + for row in receipts + if row.get("payload", {}).get("event") == "candidate_ready" + ) + except (OSError, ValueError, StopIteration, json.JSONDecodeError): + ready_sequence = None + row = { + "task_id": task_id, "ready_sequence": ready_sequence, + "title": goal.splitlines()[0][:120], "goal": goal, + "project_id": project_id, "project_label": label.label if label else "Configured project", + "state": "candidate_ready" if ready_sequence is not None else str(task.get("state", "unverified")), + "created_at": created_at, "legacy_order": created_at is None, + "history_ordinal": task.get("history_ordinal"), + } + if not needle or needle in " ".join( + str(row.get(key, "")) for key in ("task_id", "title", "goal", "project_id", "project_label") + ).casefold(): + rows.append(row) + def order(item: dict[str, Any]) -> tuple[int, int, str, str]: + ordinal = item.get("history_ordinal") + if isinstance(ordinal, int) and not isinstance(ordinal, bool) and ordinal > 0: + return (2, ordinal, "", str(item["task_id"])) + # Existing P2 entries use signed creation time when available. + # Undated entries have a labelled deterministic fallback, not a fake date. + return (1 if item.get("created_at") else 0, 0, + str(item.get("created_at") or ""), str(item["task_id"])) + + rows.sort(key=order, reverse=True) + if cursor is not None: + positions = [index for index, item in enumerate(rows) if item["task_id"] == cursor] + if not positions: + raise ValueError("candidate_history_cursor_invalid") + rows = rows[positions[0] + 1:] + filtered = rows[:limit] + return { + "schema": "torq-candidate-history-v1", "items": filtered, + "next_cursor": filtered[-1]["task_id"] if len(rows) > limit else None, + } + + def application(self, application_id: str) -> dict[str, Any]: + value = self.store.snapshot()["applications"].get(application_id) + if not isinstance(value, dict): + raise ValueError("task_application_unknown") + return self._replay_application(value) + + def recovery_status(self, project_id: str) -> dict[str, Any]: + project = self.tasks.projects.get(project_id) + if project is None: + raise ValueError("task_project_unknown") + try: + with AnchoredPrimary(project.root) as primary: + marker = self.markers.read(primary) + except RuntimeError: + return {"schema": "torq-candidate-recovery-v1", "state": "busy", "finding": "task_apply_primary_busy"} + if marker is None: + return {"schema": "torq-candidate-recovery-v1", "state": "idle", "finding": None} + return { + "schema": "torq-candidate-recovery-v1", "state": "recovery_required", + "application_id": marker["application_id"], + "owned": marker["installation_id"] == self.store.installation_id, + "finding": "task_apply_recovery_pending", + } + + def recover(self, project_id: str) -> dict[str, Any]: + project = self.tasks.projects.get(project_id) + if project is None: + raise ValueError("task_project_unknown") + with AnchoredPrimary(project.root) as primary: + marker = self.markers.read(primary) + if marker is None: + return {"schema": "torq-candidate-recovery-v1", "state": "idle", "finding": None} + if marker.get("installation_id") != self.store.installation_id: + raise ValueError("task_apply_marker_owned_elsewhere") + application_id = str(marker["application_id"]) + record = self.store.snapshot()["applications"].get(application_id) + if not isinstance(record, Mapping): + raise ValueError("candidate_review_store_invalid") + request = record.get("request") + if ( + record.get("kind") != "apply" + or record.get("record_id") != application_id + or not isinstance(request, Mapping) + or set(request) != {"candidate", "acceptance"} + or digest_json(request) != record.get("request_digest") + ): + raise ValueError("candidate_review_store_invalid") + candidate = request.get("candidate") + acceptance = request.get("acceptance") + if not isinstance(candidate, Mapping) or not isinstance(acceptance, Mapping): + raise ValueError("candidate_review_store_invalid") + resolved = self._resolve_candidate_ref(candidate) + accepted = self._resolve_acceptance(acceptance, resolved) + chain_root = self.apply_evidence_root / application_id + if verify_receipt_store(chain_root).status != "verified": + raise ValueError("task_apply_recovery_evidence_unverified") + rows = [json.loads(line) for line in (chain_root / "receipts.jsonl").read_text(encoding="utf-8").splitlines()] + if not rows: + raise ValueError("task_apply_recovery_state_invalid") + first = rows[0]["payload"] + common = { + "apply_contract": APPLY_CONTRACT, "application_id": application_id, + "request_digest": record["request_digest"], "candidate": resolved.candidate_ref, + "acceptance": accepted, "actor": first["actor"], + } + if any(first.get(key) != value for key, value in common.items()): + raise ValueError("task_apply_recovery_identity_mismatch") + terminal_events = {"candidate_applied", "apply_rolled_back", "apply_rejected"} + last_event = rows[-1].get("payload", {}).get("event") + manifest_path = chain_root / "terminal-manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if last_event in terminal_events: + for index, path in enumerate(resolved.changed_paths): + if primary.inspect_staged( + path, application_id=application_id, operation_index=index + ).content is not None: + raise ValueError("task_apply_recovery_conflict") + if last_event == "candidate_applied": + self._verify_primary(primary, resolved.result_files) + self._verify_scope_absence(primary, resolved) + else: + self._verify_base_scope(primary, resolved) + if manifest.get("sealed") is not True: + chain = ReceiptChain.open_existing( + self.apply_evidence_root, application_id, + FileRunKeyStore(self.apply_evidence_root), + profile_version="candidate-apply-v1", policy_version="candidate-apply-v1", + ) + EvidenceBroker(chain).seal() + replayed = self._replay_application(record) + self.store.update( + application_id, application=True, state=replayed["state"], result=replayed + ) + self.markers.clear( + primary, installation_id=self.store.installation_id, + application_id=application_id, + ) + return replayed + prepared_row = next((row for row in rows if row.get("payload", {}).get("event") == "apply_prepared"), None) + started_row = next((row for row in rows if row.get("payload", {}).get("event") == "apply_started"), None) + if prepared_row is None: + if len(rows) != 1: + raise ValueError("task_apply_recovery_state_invalid") + self._verify_base_scope(primary, resolved) + for index, path in enumerate(resolved.changed_paths): + if primary.inspect_staged( + path, application_id=application_id, operation_index=index + ).content is not None: + raise ValueError("task_apply_recovery_conflict") + chain = ReceiptChain.open_existing( + self.apply_evidence_root, application_id, + FileRunKeyStore(self.apply_evidence_root), + profile_version="candidate-apply-v1", policy_version="candidate-apply-v1", + ) + broker = EvidenceBroker(chain) + terminal = _append( + broker, + {**common, "event": "apply_rejected", "detail": { + "reason_code": "task_apply_recovery_aborted" + }}, + ) + sealed_path = broker.seal() + self.markers.clear( + primary, installation_id=self.store.installation_id, + application_id=application_id, + ) + result = { + "schema": "torq-candidate-application-v1", "state": "rejected", + "application_id": application_id, "sequence": terminal["sequence"], + "receipt_hash": terminal["receipt_hash"], + "terminal_manifest_hash": digest_bytes(sealed_path.read_bytes()), + "candidate": resolved.candidate_ref, "acceptance": accepted, + "finding": "task_apply_recovery_aborted", + } + self.store.update( + application_id, application=True, state="rejected", result=result + ) + return result + prepared = prepared_row["payload"] + artifact = prepared["detail"]["journal_artifact"] + journal_raw = read_verified_prefix_artifact( + self.apply_evidence_root, application_id, str(artifact["artifact"]) + ) + if ( + ReceiptChain.hash_file(chain_root / str(artifact["artifact"])) != artifact["artifact_hash"] + or digest_bytes(journal_raw) != artifact["content_hash"] + or digest_bytes(journal_raw) != prepared["detail"]["journal_hash"] + or marker.get("journal_hash") not in {None, digest_bytes(journal_raw)} + or marker.get("journal_hash") is None and marker.get("phase") != "reserved" + ): + raise ValueError("task_apply_journal_hash_mismatch") + journal = json.loads(journal_raw) + journal_keys = { + "schema", "application_id", "request_digest", "candidate", "acceptance", + "primary_identity", "base_scope_manifest_hash", "result_scope_manifest_hash", + "operations", "created_directories", + } + if ( + not isinstance(journal, Mapping) or set(journal) != journal_keys + or journal.get("schema") != "torq-primary-journal-v1" + or journal.get("application_id") != application_id + or journal.get("request_digest") != record["request_digest"] + or journal.get("candidate") != resolved.candidate_ref + or journal.get("acceptance") != accepted + or journal.get("primary_identity") != primary.identity.value() + or journal.get("base_scope_manifest_hash") != resolved.candidate_ref["base_scope_manifest_hash"] + or journal.get("result_scope_manifest_hash") != resolved.candidate_ref["candidate_scope_manifest_hash"] + or journal.get("created_directories") != [] + or not isinstance(journal.get("operations"), list) + ): + raise ValueError("task_apply_journal_invalid") + operations = self._validate_journal_operations( + primary, resolved, journal["operations"] + ) + if len(operations) != prepared["detail"]["operation_count"]: + raise ValueError("task_apply_journal_invalid") + staged_rows = { + row["payload"]["detail"]["operation_index"]: row + for row in rows if row.get("payload", {}).get("event") == "apply_file_staged" + } + written_rows = { + row["payload"]["detail"]["operation_index"]: row + for row in rows if row.get("payload", {}).get("event") == "apply_file_written" + } + rollback_started = any( + row.get("payload", {}).get("event") == "apply_rollback_started" + for row in rows + ) + rollback_started_row = next( + ( + row for row in rows + if row.get("payload", {}).get("event") == "apply_rollback_started" + ), + None, + ) + rollback_staged_rows = { + row["payload"]["detail"]["operation_index"]: row + for row in rows + if row.get("payload", {}).get("event") == "apply_rollback_file_staged" + } + rollback_restored_rows = { + row["payload"]["detail"]["operation_index"]: row + for row in rows + if row.get("payload", {}).get("event") == "apply_rollback_file_restored" + } + states: list[str] = [] + for index, operation in enumerate(operations): + current = primary.inspect(str(operation["path"])) + staged = staged_rows.get(index) + written_row = written_rows.get(index) + for progress in (staged, written_row): + if progress is not None and ( + progress["payload"]["detail"].get("path") != operation["path"] + or progress["payload"]["detail"].get("result_hash") + != operation["after_hash"] + ): + raise ValueError("task_apply_journal_invalid") + if current.parent_identity != operation.get("parent_identity"): + raise ValueError("task_apply_recovery_conflict") + rollback_stage = rollback_staged_rows.get(index) + rollback_restored = rollback_restored_rows.get(index) + rollback_temp = primary.inspect_rollback_staged( + str(operation["path"]), application_id=application_id, + operation_index=index, + ) + if rollback_temp.content is not None: + if rollback_stage is None or rollback_temp.target_identity is None: + raise ValueError("task_apply_recovery_conflict") + rollback_stable = { + "volume": rollback_temp.target_identity["volume"], + "file_id": rollback_temp.target_identity["file_id"], + } + if ( + rollback_temp.content_hash != operation["before_hash"] + or rollback_temp.parent_identity != operation["parent_identity"] + or rollback_stable + != rollback_stage["payload"]["detail"].get("staged_identity") + ): + raise ValueError("task_apply_recovery_conflict") + for progress in (rollback_stage, rollback_restored): + if progress is not None and ( + progress["payload"]["detail"].get("path") != operation["path"] + or progress["payload"]["detail"].get("base_hash") + != operation["before_hash"] + ): + raise ValueError("task_apply_journal_invalid") + before = None if operation.get("before_content") is None else str(operation["before_content"]).encode("utf-8") + after = str(operation.get("after_content", "")).encode("utf-8") + staged_file = primary.inspect_staged( + str(operation["path"]), application_id=application_id, + operation_index=index, + ) + if staged_file.content is not None: + if staged is None or staged_file.target_identity is None: + raise ValueError("task_apply_recovery_conflict") + staged_stable = { + "volume": staged_file.target_identity["volume"], + "file_id": staged_file.target_identity["file_id"], + } + if ( + staged_file.content_hash != operation["after_hash"] + or staged_file.parent_identity != operation["parent_identity"] + or staged_stable != staged["payload"]["detail"].get("staged_identity") + ): + raise ValueError("task_apply_recovery_conflict") + if current.content == before: + if before is not None: + stable = None if current.target_identity is None else {"volume": current.target_identity["volume"], "file_id": current.target_identity["file_id"]} + rollback_identity = ( + None if rollback_stage is None + else rollback_stage["payload"]["detail"].get("staged_identity") + ) + if ( + stable != operation.get("before_identity") + and stable != rollback_identity + ): + raise ValueError("task_apply_recovery_conflict") + if stable == rollback_identity and rollback_temp.content is not None: + raise ValueError("task_apply_recovery_conflict") + if stable == operation.get("before_identity"): + if rollback_stage is not None and rollback_restored is None: + raise ValueError("task_apply_recovery_conflict") + state = "before_original" + else: + state = "before_rollback" + elif rollback_stage is not None and rollback_restored is None: + # Absence after a signed delete intent but before its completion + # receipt is inherently ambiguous across a process death. + raise ValueError("task_apply_recovery_conflict") + else: + state = "before_rollback" if rollback_stage is not None else "before_original" + if staged is not None: + if staged_file.content is None: + if not rollback_started: + raise ValueError("task_apply_recovery_conflict") + elif staged_file.target_identity is None: + raise ValueError("task_apply_recovery_conflict") + else: + primary.remove_staged( + str(operation["path"]), application_id=application_id, + operation_index=index, expected_hash=str(operation["after_hash"]), + expected_parent_identity=dict(operation["parent_identity"]), + expected_target_identity=staged_file.target_identity, + ) + states.append(state) + elif current.content == after: + if staged_file.content is not None: + raise ValueError("task_apply_recovery_conflict") + stable = None if current.target_identity is None else {"volume": current.target_identity["volume"], "file_id": current.target_identity["file_id"]} + if staged is None or stable != staged["payload"]["detail"].get("staged_identity"): + raise ValueError("task_apply_recovery_conflict") + states.append("after") + else: + raise ValueError("task_apply_recovery_conflict") + chain = ReceiptChain.open_existing( + self.apply_evidence_root, application_id, FileRunKeyStore(self.apply_evidence_root), + profile_version="candidate-apply-v1", policy_version="candidate-apply-v1", + ) + broker = EvidenceBroker(chain) + if started_row is None: + if staged_rows or written_rows or any(not state.startswith("before_") for state in states): + raise ValueError("task_apply_recovery_conflict") + terminal = _append( + broker, + {**common, "event": "apply_rejected", "detail": { + "reason_code": "task_apply_recovery_aborted" + }}, + ) + sealed_path = broker.seal() + self.markers.clear( + primary, installation_id=self.store.installation_id, + application_id=application_id, + ) + result = { + "schema": "torq-candidate-application-v1", "state": "rejected", + "application_id": application_id, "sequence": terminal["sequence"], + "receipt_hash": terminal["receipt_hash"], + "terminal_manifest_hash": digest_bytes(sealed_path.read_bytes()), + "candidate": resolved.candidate_ref, "acceptance": accepted, + "finding": "task_apply_recovery_aborted", + } + self.store.update( + application_id, application=True, state="rejected", result=result + ) + return result + self.markers.write(primary, {**marker, "phase": "recovering"}) + if all(state == "after" for state in states): + for index, operation in enumerate(operations): + if index in written_rows: + continue + staged = staged_rows[index] + _append(broker, {**common, "event": "apply_file_written", "detail": { + "started_sequence": started_row["sequence"], "operation_index": index, + "staged_sequence": staged["sequence"], "staged_receipt_hash": staged["receipt_hash"], + "path": operation["path"], "result_hash": operation["after_hash"], + }}) + self._verify_primary(primary, resolved.result_files) + self._verify_scope_absence(primary, resolved) + terminal = _append(broker, {**common, "event": "candidate_applied", "detail": { + "started_sequence": started_row["sequence"], "journal_hash": marker["journal_hash"], + "result_scope_manifest_hash": resolved.candidate_ref["candidate_scope_manifest_hash"], + "operation_count": len(operations), + }}) + manifest_path = broker.seal() + self.markers.clear(primary, installation_id=self.store.installation_id, application_id=application_id) + result = { + "schema": "torq-candidate-application-v1", "state": "applied", "application_id": application_id, + "sequence": terminal["sequence"], "receipt_hash": terminal["receipt_hash"], + "terminal_manifest_hash": digest_bytes(manifest_path.read_bytes()), + "candidate": resolved.candidate_ref, "acceptance": accepted, + } + else: + if not rollback_started: + rollback_started_row = _append(broker, {**common, "event": "apply_rollback_started", "detail": { + "caused_by_sequence": broker.sequence, "reason_code": "task_apply_recovery_rollback", + }}) + if rollback_started_row is None: + raise ValueError("task_apply_recovery_state_invalid") + rollback_sequence = rollback_started_row["sequence"] + for index in reversed(range(len(operations))): + operation = operations[index] + existing_stage = rollback_staged_rows.get(index) + existing_restored = rollback_restored_rows.get(index) + if states[index] != "after": + if states[index] == "before_rollback" and existing_stage is not None and existing_restored is None: + if operation["before_content"] is None: + raise ValueError("task_apply_recovery_conflict") + _append(broker, {**common, "event": "apply_rollback_file_restored", "detail": { + "rollback_started_sequence": rollback_sequence, + "operation_index": index, "path": operation["path"], + "base_hash": operation["before_hash"], + "staged_sequence": existing_stage["sequence"], + "staged_receipt_hash": existing_stage["receipt_hash"], + }}) + continue + current = primary.inspect(str(operation["path"])) + staged_identity = staged_rows[index]["payload"]["detail"]["staged_identity"] + stable = None if current.target_identity is None else {"volume": current.target_identity["volume"], "file_id": current.target_identity["file_id"]} + if stable != staged_identity or current.target_identity is None: + raise ValueError("task_apply_recovery_conflict") + if operation["before_content"] is None: + rollback_stage = existing_stage + if rollback_stage is None: + rollback_stage = _append(broker, {**common, "event": "apply_rollback_file_staged", "detail": { + "rollback_started_sequence": rollback_sequence, + "operation_index": index, "path": operation["path"], + "base_hash": None, "staged_identity": stable, + }}) + elif rollback_stage["payload"]["detail"].get("staged_identity") != stable: + raise ValueError("task_apply_recovery_conflict") + primary.remove( + str(operation["path"]), expected_hash=str(operation["after_hash"]), + expected_parent_identity=current.parent_identity, + expected_target_identity=current.target_identity, + ) + else: + rollback_stage = existing_stage + if rollback_stage is None: + captured: dict[str, Any] | None = None + + def record_rollback_staged(identity: dict[str, int]) -> None: + nonlocal captured + captured = _append(broker, {**common, "event": "apply_rollback_file_staged", "detail": { + "rollback_started_sequence": rollback_sequence, + "operation_index": index, "path": operation["path"], + "base_hash": operation["before_hash"], + "staged_identity": identity, + }}) + + primary.replace( + str(operation["path"]), expected_before_hash=str(operation["after_hash"]), + expected_parent_identity=current.parent_identity, + expected_target_identity=current.target_identity, + content=str(operation["before_content"]).encode("utf-8"), + permission_policy=dict(operation["permission_policy"]), + application_id=application_id, operation_index=index, + staged_callback=record_rollback_staged, rollback=True, + ) + if captured is None: + raise ValueError("task_apply_rollback_stage_missing") + rollback_stage = captured + else: + rollback_temp = primary.inspect_rollback_staged( + str(operation["path"]), application_id=application_id, + operation_index=index, + ) + if rollback_temp.target_identity is None: + raise ValueError("task_apply_recovery_conflict") + primary.commit_rollback_staged( + str(operation["path"]), application_id=application_id, + operation_index=index, + expected_before_hash=str(operation["after_hash"]), + expected_before_identity=current.target_identity, + expected_parent_identity=current.parent_identity, + staged_hash=str(operation["before_hash"]), + staged_identity=dict(rollback_stage["payload"]["detail"]["staged_identity"]), + permission_policy=dict(operation["permission_policy"]), + ) + _append(broker, {**common, "event": "apply_rollback_file_restored", "detail": { + "rollback_started_sequence": rollback_sequence, + "operation_index": index, "path": operation["path"], + "base_hash": operation["before_hash"], + "staged_sequence": rollback_stage["sequence"], + "staged_receipt_hash": rollback_stage["receipt_hash"], + }}) + self._verify_primary(primary, resolved.base_files) + for path in resolved.changed_paths: + if path not in resolved.base_files and primary.inspect(path).content is not None: + raise ValueError("task_apply_recovery_conflict") + terminal = _append(broker, {**common, "event": "apply_rolled_back", "detail": { + "prepared_sequence": prepared_row["sequence"], "journal_hash": marker["journal_hash"], + "restored_scope_manifest_hash": resolved.candidate_ref["base_scope_manifest_hash"], + }}) + manifest_path = broker.seal() + self.markers.clear(primary, installation_id=self.store.installation_id, application_id=application_id) + result = { + "schema": "torq-candidate-application-v1", "state": "rolled_back", "application_id": application_id, + "sequence": terminal["sequence"], "receipt_hash": terminal["receipt_hash"], + "terminal_manifest_hash": digest_bytes(manifest_path.read_bytes()), + "candidate": resolved.candidate_ref, "acceptance": accepted, + } + self.store.update(application_id, application=True, state=result["state"], result=result) + return result + + def replay_accept( + self, *, request_id: str, task_id: str, ready_sequence: int, review_hash: str + ) -> dict[str, Any]: + body = {"task_id": task_id, "ready_sequence": ready_sequence, "review_hash": review_hash} + return self._replay_accept( + self.store.replay(request_kind="review", request_id=request_id, body=body) + ) + + def replay_apply( + self, *, request_id: str, candidate: Mapping[str, Any], acceptance: Mapping[str, Any] + ) -> dict[str, Any]: + body = {"candidate": dict(candidate), "acceptance": dict(acceptance)} + return self._replay_application( + self.store.replay(request_kind="apply", request_id=request_id, body=body) + ) + + def _resolve_candidate_ref(self, candidate: Mapping[str, Any]) -> ResolvedTaskReview: + task_id = candidate.get("task_id") + sequence = candidate.get("ready_sequence") + if not isinstance(task_id, str) or not isinstance(sequence, int) or isinstance(sequence, bool): + raise ValueError("candidate_reference_invalid") + resolved = resolve_task_review(self.tasks.evidence_root, task_id, sequence) + if resolved.candidate_ref != dict(candidate): + raise ValueError("candidate_reference_mismatch") + return resolved + + def _resolve_acceptance(self, acceptance: Mapping[str, Any], resolved: ResolvedTaskReview) -> dict[str, Any]: + decision_id = acceptance.get("decision_id") + if not isinstance(decision_id, str): + raise ValueError("candidate_acceptance_invalid") + root = self.review_evidence_root / decision_id + if verify_receipt_store(root).status != "verified": + raise ValueError("candidate_acceptance_unverified") + manifest_raw = (root / "terminal-manifest.json").read_bytes() + rows = [json.loads(line) for line in (root / "receipts.jsonl").read_text(encoding="utf-8").splitlines()] + if len(rows) != 1: + raise ValueError("candidate_acceptance_invalid") + payload = rows[0].get("payload", {}) + expected = { + "decision_id": decision_id, "decision_sequence": rows[0].get("sequence"), + "decision_receipt_hash": rows[0].get("receipt_hash"), + "terminal_manifest_hash": digest_bytes(manifest_raw), + } + if ( + dict(acceptance) != expected + or payload.get("review_contract") != REVIEW_CONTRACT + or payload.get("event") != "candidate_accepted" + or payload.get("decision_id") != decision_id + or payload.get("candidate") != resolved.candidate_ref + or payload.get("detail", {}).get("source_scope_hash") + != resolved.candidate_ref["base_scope_manifest_hash"] + ): + raise ValueError("candidate_acceptance_mismatch") + artifact = payload.get("detail", {}).get("review_artifact", {}) + plain = read_verified_artifact(self.review_evidence_root, decision_id, str(artifact.get("artifact"))) + artifact_path = root / str(artifact.get("artifact")) + if ( + ReceiptChain.hash_file(artifact_path) != artifact.get("artifact_hash") + or digest_bytes(plain) != artifact.get("content_hash") + or digest_json(json.loads(plain)) != resolved.candidate_ref["review_hash"] + ): + raise ValueError("candidate_acceptance_artifact_mismatch") + return expected + + def _replay_accept(self, record: Mapping[str, Any]) -> dict[str, Any]: + request = record.get("request") + if ( + record.get("kind") != "review" + or not isinstance(record.get("record_id"), str) + or not isinstance(request, Mapping) + or set(request) != {"task_id", "ready_sequence", "review_hash"} + or digest_json(request) != record.get("request_digest") + ): + raise ValueError("candidate_review_store_invalid") + task_id = request.get("task_id") + sequence = request.get("ready_sequence") + if not isinstance(task_id, str) or not isinstance(sequence, int) or isinstance(sequence, bool): + raise ValueError("candidate_review_store_invalid") + resolved = resolve_task_review(self.tasks.evidence_root, task_id, sequence) + if resolved.candidate_ref["review_hash"] != request.get("review_hash"): + raise ValueError("candidate_review_store_invalid") + root = self.review_evidence_root / str(record["record_id"]) + if verify_receipt_store(root).status != "verified": + raise ValueError("candidate_acceptance_unverified") + manifest_raw = (root / "terminal-manifest.json").read_bytes() + rows = [json.loads(line) for line in (root / "receipts.jsonl").read_text(encoding="utf-8").splitlines()] + if len(rows) != 1: + raise ValueError("candidate_acceptance_invalid") + payload = rows[0].get("payload", {}) + if ( + payload.get("event") != "candidate_accepted" + or payload.get("decision_id") != record["record_id"] + or payload.get("request_digest") != record.get("request_digest") + or payload.get("candidate") != resolved.candidate_ref + ): + raise ValueError("candidate_acceptance_mismatch") + verified_acceptance = { + "decision_id": record["record_id"], "decision_sequence": rows[0]["sequence"], + "decision_receipt_hash": rows[0]["receipt_hash"], + "terminal_manifest_hash": digest_bytes(manifest_raw), + } + self._resolve_acceptance(verified_acceptance, resolved) + return { + "schema": "torq-candidate-acceptance-v1", "state": "accepted", + "candidate": resolved.candidate_ref, "acceptance": verified_acceptance, + "source_changed": False, + } + + def _replay_application(self, record: Mapping[str, Any]) -> dict[str, Any]: + request = record.get("request") + application_id = record.get("record_id") + if ( + record.get("kind") != "apply" + or not isinstance(application_id, str) + or not isinstance(request, Mapping) + or set(request) != {"candidate", "acceptance"} + or digest_json(request) != record.get("request_digest") + ): + raise ValueError("candidate_review_store_invalid") + root = self.apply_evidence_root / application_id + verification = verify_receipt_store(root) + if verification.status != "verified": + raise ValueError("candidate_application_evidence_unverified") + candidate = request.get("candidate") + acceptance = request.get("acceptance") + if not isinstance(candidate, Mapping) or not isinstance(acceptance, Mapping): + raise ValueError("candidate_review_store_invalid") + resolved = self._resolve_candidate_ref(candidate) + verified_acceptance = self._resolve_acceptance(acceptance, resolved) + rows = [json.loads(line) for line in (root / "receipts.jsonl").read_text(encoding="utf-8").splitlines()] + terminal = rows[-1] + first_payload = rows[0].get("payload", {}) + terminal_payload = terminal.get("payload", {}) + if ( + first_payload.get("apply_contract") != APPLY_CONTRACT + or + first_payload.get("application_id") != application_id + or first_payload.get("request_digest") != record.get("request_digest") + or first_payload.get("candidate") != resolved.candidate_ref + or first_payload.get("acceptance") != verified_acceptance + ): + raise ValueError("candidate_application_evidence_mismatch") + event = terminal_payload.get("event") + state_by_event = { + "candidate_applied": "applied", "apply_rolled_back": "rolled_back", + "apply_recovery_required": "recovery_required", "apply_rejected": "rejected", + } + state = state_by_event.get(event) + if ( + state is None + or terminal.get("run_id") != application_id + or terminal_payload.get("application_id") != application_id + or terminal_payload.get("request_digest") != record.get("request_digest") + or terminal_payload.get("candidate") != resolved.candidate_ref + or terminal_payload.get("acceptance") != verified_acceptance + ): + raise ValueError("candidate_application_evidence_mismatch") + manifest_raw = (root / "terminal-manifest.json").read_bytes() + result = { + "schema": "torq-candidate-application-v1", "state": state, + "application_id": application_id, "sequence": terminal["sequence"], + "receipt_hash": terminal["receipt_hash"], "terminal_manifest_hash": digest_bytes(manifest_raw), + "candidate": resolved.candidate_ref, "acceptance": verified_acceptance, + } + if state in {"rejected", "recovery_required"}: + result["finding"] = terminal_payload.get("detail", {}).get("reason_code") + return result + + def _assert_project_clear(self, resolved: ResolvedTaskReview) -> None: + self.markers.assert_clear(self.tasks.projects[str(resolved.plan["project_id"])].root) + + def _assert_source_base(self, resolved: ResolvedTaskReview) -> None: + project = self.tasks.projects[str(resolved.plan["project_id"])] + with AnchoredPrimary(project.root) as primary: + try: + self._verify_base_scope(primary, resolved) + except ValueError as exc: + raise ValueError("candidate_source_stale") from exc + + def _prepare_operations( + self, primary: AnchoredPrimary, resolved: ResolvedTaskReview + ) -> tuple[list[dict[str, Any]], list[AnchoredFile]]: + try: + self._verify_base_scope(primary, resolved) + except ValueError as exc: + raise ValueError("candidate_source_stale") from exc + operations: list[dict[str, Any]] = [] + current: list[AnchoredFile] = [] + for index, path in enumerate(resolved.changed_paths): + before = primary.inspect(path) + original = resolved.base_files.get(path) + if before.content != original: + raise ValueError("candidate_source_stale") + policy = before.permission_policy if original is not None else primary.create_permission_policy() + if policy is None: + raise ValueError("task_apply_permission_invalid") + after = resolved.result_files[path] + operations.append( + { + "index": index, "operation": "replace" if original is not None else "create", "path": path, + "before_content": None if original is None else original.decode("utf-8"), + "before_hash": None if original is None else digest_bytes(original), + "after_content": after.decode("utf-8"), "after_hash": digest_bytes(after), + "permission_policy": policy, "parent_identity": before.parent_identity, + "before_identity": None if original is None else { + "volume": before.target_identity["volume"], + "file_id": before.target_identity["file_id"], + } if before.target_identity is not None else None, + } + ) + current.append(before) + return operations, current + + def _validate_journal_operations( + self, + primary: AnchoredPrimary, + resolved: ResolvedTaskReview, + value: object, + ) -> list[dict[str, Any]]: + if not isinstance(value, list) or len(value) != len(resolved.changed_paths): + raise ValueError("task_apply_journal_invalid") + operations: list[dict[str, Any]] = [] + keys = { + "index", "operation", "path", "before_content", "before_hash", + "after_content", "after_hash", "permission_policy", "parent_identity", + "before_identity", + } + for index, item in enumerate(value): + if not isinstance(item, Mapping) or set(item) != keys: + raise ValueError("task_apply_journal_invalid") + operation = dict(item) + path = resolved.changed_paths[index] + before = resolved.base_files.get(path) + after = resolved.result_files.get(path) + expected_kind = "create" if before is None else "replace" + expected_before_text = None if before is None else before.decode("utf-8") + if ( + operation.get("index") != index + or operation.get("operation") != expected_kind + or operation.get("path") != path + or operation.get("before_content") != expected_before_text + or operation.get("before_hash") + != (None if before is None else digest_bytes(before)) + or after is None + or operation.get("after_content") != after.decode("utf-8") + or operation.get("after_hash") != digest_bytes(after) + ): + raise ValueError("task_apply_journal_invalid") + parent_identity = operation.get("parent_identity") + before_identity = operation.get("before_identity") + if not self._stable_identity(parent_identity) or ( + before is None and before_identity is not None + ) or ( + before is not None and not self._stable_identity(before_identity) + ): + raise ValueError("task_apply_journal_invalid") + policy = operation.get("permission_policy") + if not isinstance(policy, Mapping): + raise ValueError("task_apply_journal_invalid") + current = primary.inspect(path) + if before is None and dict(policy) != primary.create_permission_policy(): + raise ValueError("task_apply_journal_invalid") + if before is not None and current.content in {before, after} and current.permission_policy != dict(policy): + raise ValueError("task_apply_journal_invalid") + operations.append(operation) + return operations + + @staticmethod + def _stable_identity(value: object) -> bool: + return ( + isinstance(value, Mapping) + and set(value) == {"volume", "file_id"} + and all( + isinstance(value.get(key), int) + and not isinstance(value.get(key), bool) + and value[key] >= 0 + for key in ("volume", "file_id") + ) + ) + + def _verify_primary(self, primary: AnchoredPrimary, files: Mapping[str, bytes]) -> None: + for path, content in files.items(): + if primary.inspect(path).content != content: + raise ValueError("task_apply_result_mismatch") + + def _verify_base_scope( + self, primary: AnchoredPrimary, resolved: ResolvedTaskReview + ) -> None: + for path, content in resolved.base_files.items(): + if primary.inspect(path).content != content: + raise ValueError("task_apply_result_mismatch") + for path in resolved.plan["absent_output_paths"]: + if primary.inspect(str(path)).content is not None: + raise ValueError("task_apply_result_mismatch") + + def _verify_scope_absence( + self, primary: AnchoredPrimary, resolved: ResolvedTaskReview + ) -> None: + for path in resolved.plan["absent_output_paths"]: + if path not in resolved.result_files and primary.inspect(str(path)).content is not None: + raise ValueError("task_apply_result_mismatch") + + def _rollback_or_reject( + self, broker: EvidenceBroker | None, primary: AnchoredPrimary | None, marker_written: bool, + started: Mapping[str, Any] | None, written: list[tuple[dict[str, Any], AnchoredFile, Mapping[str, Any]]], + journal_hash: str | None, record: Mapping[str, Any], application_id: str, + candidate: Mapping[str, Any], acceptance: Mapping[str, Any], subject_id: str, finding: str, + operations: list[dict[str, Any]], + ) -> dict[str, Any]: + if broker is None: + return {"schema": "torq-candidate-application-v1", "state": "failed", "finding": finding} + common = { + "apply_contract": APPLY_CONTRACT, "application_id": application_id, + "request_digest": record["request_digest"], "candidate": dict(candidate), + "acceptance": dict(acceptance), "actor": {"subject_id": subject_id, "assurance": "local_operator_session"}, + } + try: + if started is None: + _append(broker, {**common, "event": "apply_rejected", "detail": {"reason_code": finding}}) + broker.seal() + if marker_written and primary is not None: + self.markers.clear(primary, installation_id=self.store.installation_id, application_id=application_id) + return {"schema": "torq-candidate-application-v1", "state": "rejected", "application_id": application_id, "finding": finding} + caused = broker.sequence + rollback_started_receipt = _append( + broker, + {**common, "event": "apply_rollback_started", "detail": { + "caused_by_sequence": caused, "reason_code": finding, + }}, + ) + assert primary is not None and journal_hash is not None + del written + if verify_receipt_store(broker.run_root).status != "verified": + raise ValueError("task_apply_recovery_evidence_unverified") + signed_rows = [ + json.loads(line) + for line in (broker.run_root / "receipts.jsonl").read_text(encoding="utf-8").splitlines() + ] + staged_by_path = { + str(row["payload"]["detail"]["path"]): row + for row in signed_rows + if row.get("payload", {}).get("event") == "apply_file_staged" + } + for operation in reversed(operations): + path = str(operation["path"]) + current = primary.inspect(path) + before_raw = None if operation["before_content"] is None else str(operation["before_content"]).encode("utf-8") + after_raw = str(operation["after_content"]).encode("utf-8") + if current.content == before_raw: + continue + if current.content != after_raw: + raise ValueError("task_apply_recovery_conflict") + staged = staged_by_path.get(path) + staged_identity = None if staged is None else staged.get("payload", {}).get("detail", {}).get("staged_identity") + current_stable = None if current.target_identity is None else { + "volume": current.target_identity["volume"], "file_id": current.target_identity["file_id"] + } + if current_stable != staged_identity: + raise ValueError("task_apply_recovery_conflict") + if operation["before_content"] is None: + if current.target_identity is None: + raise ValueError("task_apply_recovery_conflict") + delete_stage = _append( + broker, + {**common, "event": "apply_rollback_file_staged", "detail": { + "rollback_started_sequence": rollback_started_receipt["sequence"], + "operation_index": operation["index"], "path": path, + "base_hash": None, "staged_identity": current_stable, + }}, + ) + primary.remove( + path, expected_hash=str(operation["after_hash"]), + expected_parent_identity=current.parent_identity, + expected_target_identity=current.target_identity, + ) + _append( + broker, + {**common, "event": "apply_rollback_file_restored", "detail": { + "rollback_started_sequence": rollback_started_receipt["sequence"], + "operation_index": operation["index"], "path": path, + "base_hash": None, "staged_sequence": delete_stage["sequence"], + "staged_receipt_hash": delete_stage["receipt_hash"], + }}, + ) + else: + rollback_stage: dict[str, Any] | None = None + + def record_rollback_staged(identity: dict[str, int]) -> None: + nonlocal rollback_stage + rollback_stage = _append( + broker, + {**common, "event": "apply_rollback_file_staged", "detail": { + "rollback_started_sequence": rollback_started_receipt["sequence"], + "operation_index": operation["index"], "path": path, + "base_hash": operation["before_hash"], + "staged_identity": identity, + }}, + ) + + primary.replace( + path, expected_before_hash=str(operation["after_hash"]), + expected_parent_identity=current.parent_identity, + expected_target_identity=current.target_identity, + content=str(operation["before_content"]).encode("utf-8"), + permission_policy=dict(operation["permission_policy"]), + application_id=application_id, operation_index=int(operation["index"]), + staged_callback=record_rollback_staged, rollback=True, + ) + if rollback_stage is None: + raise ValueError("task_apply_rollback_stage_missing") + _append( + broker, + {**common, "event": "apply_rollback_file_restored", "detail": { + "rollback_started_sequence": rollback_started_receipt["sequence"], + "operation_index": operation["index"], "path": path, + "base_hash": operation["before_hash"], + "staged_sequence": rollback_stage["sequence"], + "staged_receipt_hash": rollback_stage["receipt_hash"], + }}, + ) + resolved = self._resolve_candidate_ref(candidate) + self._verify_primary(primary, resolved.base_files) + for path in resolved.changed_paths: + if path not in resolved.base_files and primary.inspect(path).content is not None: + raise ValueError("task_apply_recovery_conflict") + terminal = _append( + broker, + {**common, "event": "apply_rolled_back", "detail": { + "prepared_sequence": 2, "journal_hash": journal_hash, + "restored_scope_manifest_hash": resolved.candidate_ref["base_scope_manifest_hash"], + }}, + ) + broker.seal() + self.markers.clear(primary, installation_id=self.store.installation_id, application_id=application_id) + return {"schema": "torq-candidate-application-v1", "state": "rolled_back", "application_id": application_id, "sequence": terminal["sequence"], "candidate": dict(candidate), "acceptance": dict(acceptance), "finding": finding} + except BaseException: + try: + _append( + broker, + {**common, "event": "apply_recovery_required", "detail": { + "caused_by_sequence": broker.sequence, "reason_code": "task_apply_recovery_required", + }}, + ) + except BaseException: + pass + return {"schema": "torq-candidate-application-v1", "state": "recovery_required", "application_id": application_id, "candidate": dict(candidate), "acceptance": dict(acceptance), "finding": "task_apply_recovery_required"} + + @staticmethod + def _record_result(record: Mapping[str, Any]) -> dict[str, Any]: + result = record.get("result") + if isinstance(result, dict): + return dict(result) + return {"schema": "torq-candidate-operation-v1", "state": record.get("state"), "finding": record.get("finding")} + + @staticmethod + def _reason(exc: BaseException, default: str) -> str: + if isinstance(exc, (OSError, RuntimeError, ValueError)) and exc.args and isinstance(exc.args[0], str): + value = exc.args[0].split(":", 1)[0] + if value.startswith(("task_", "candidate_")) and value.replace("_", "").isalnum() and len(value) <= 64: + return value + return default + + +__all__ = ["CandidateReviewService"] diff --git a/src/torq_cli/application/candidate_tasks.py b/src/torq_cli/application/candidate_tasks.py index 195d4d5..f3bfefd 100644 --- a/src/torq_cli/application/candidate_tasks.py +++ b/src/torq_cli/application/candidate_tasks.py @@ -46,6 +46,8 @@ CHECK_PROFILE_VERSION = "1.0.0" PLAN_CONTRACT = "torq-candidate-plan-v1" INPUT_CONTRACT = "torq-candidate-input-v1" +PLAN_CONTRACT_V2 = "torq-candidate-plan-v2" +INPUT_CONTRACT_V2 = "torq-candidate-input-v2" class ProcessOwner(Protocol): @@ -104,6 +106,11 @@ def __init__( owner_factory: Callable[..., ProcessOwner] | None = None, python_executable: Path | None = None, acquire_lock: bool = True, + project_gate: Callable[[Path], None] | None = None, + input_bundle_provider: Callable[[Mapping[str, Any]], Mapping[str, Any]] | None = None, + plan_transformer: Callable[[Mapping[str, Any]], Mapping[str, Any]] | None = None, + draft_saved_observer: Callable[[str, Mapping[str, Any]], None] | None = None, + draft_deleted_observer: Callable[[str], None] | None = None, ) -> None: if not projects or len(projects) > 32: raise ValueError("task_projects_invalid") @@ -133,6 +140,11 @@ def __init__( self.model = model self.owner_factory = owner_factory or cast(Callable[..., ProcessOwner], OwnedProcess) self.python_executable = (python_executable or Path(trusted_python_executable())).resolve() + self.project_gate = project_gate + self.input_bundle_provider = input_bundle_provider + self.plan_transformer = plan_transformer + self.draft_saved_observer = draft_saved_observer + self.draft_deleted_observer = draft_deleted_observer self._lock = threading.RLock() self._owner: ProcessOwner | None = None self._active_task: str | None = None @@ -232,6 +244,8 @@ def capabilities(self) -> dict[str, Any]: if isinstance(self.provider_factory, CandidateProviderCommandFactory): self.provider_factory.preflight() snapshot_source(next(iter(self.projects.values())).root, ()) + if self.project_gate is not None: + self.project_gate(next(iter(self.projects.values())).root) execution = True except (OSError, ValueError): execution = False @@ -280,17 +294,22 @@ def save_draft( self._project(project_id) safe_inputs = [validate_relative_path(item) for item in input_paths] safe_outputs = [validate_relative_path(item) for item in output_paths] - return self.store.put_draft( + saved = self.store.put_draft( project_id, goal=goal, input_paths=safe_inputs, output_paths=safe_outputs, expected_revision=expected_revision, ) + if self.draft_saved_observer is not None: + self.draft_saved_observer(project_id, saved) + return saved def delete_draft(self, project_id: str, *, expected_revision: int) -> None: self._project(project_id) self.store.delete_draft(project_id, expected_revision=expected_revision) + if self.draft_deleted_observer is not None: + self.draft_deleted_observer(project_id) def review_plan( self, @@ -301,6 +320,8 @@ def review_plan( output_paths: Sequence[str], ) -> dict[str, Any]: project = self._project(project_id) + if self.project_gate is not None: + self.project_gate(project.root) draft = self.draft(project_id) if draft is None or not draft["goal"] or draft["revision"] != draft_revision: raise ValueError("task_draft_revision_stale") @@ -334,6 +355,8 @@ def review_plan( "helper_hash": _hash_file(helper), "limits": {"files": 32, "file_bytes": 65536, "total_bytes": 2097152}, } + if self.plan_transformer is not None: + body = dict(self.plan_transformer(body)) return self.store.save_plan(body) def start(self, *, request_id: str, plan_hash: str) -> dict[str, Any]: @@ -350,9 +373,24 @@ def start(self, *, request_id: str, plan_hash: str) -> dict[str, Any]: plan = plans.get(plan_hash) if not isinstance(plan, dict) or digest_json(plan) != plan_hash: raise ValueError("task_plan_unknown") - draft = self.draft(str(plan["project_id"])) - if draft is None or draft["revision"] != plan["draft_revision"] or draft["goal"] != plan["goal"]: - raise ValueError("task_plan_stale") + if plan.get("contract") == PLAN_CONTRACT: + draft = self.draft(str(plan["project_id"])) + if draft is None or draft["revision"] != plan["draft_revision"] or draft["goal"] != plan["goal"]: + raise ValueError("task_plan_stale") + elif ( + plan.get("contract") == PLAN_CONTRACT_V2 + and isinstance(plan.get("lineage"), Mapping) + and plan["lineage"].get("mode") == "continuation" + ): + draft = self.draft(str(plan["project_id"])) + if draft != { + "project_id": plan["project_id"], + "goal": plan["goal"], + "input_paths": plan["input_paths"], + "output_paths": plan["output_paths"], + "revision": plan["draft_revision"], + }: + raise ValueError("task_plan_stale") self._revalidate_plan(plan) request = {"plan_hash": plan_hash, "project_id": plan["project_id"]} with self._lock: @@ -419,7 +457,7 @@ def _project(self, project_id: str) -> TaskProject: def _revalidate_plan(self, plan: Mapping[str, Any]) -> SourceSnapshot: if ( - plan.get("contract") != PLAN_CONTRACT + plan.get("contract") not in {PLAN_CONTRACT, PLAN_CONTRACT_V2} or plan.get("provider") != self.provider or plan.get("model") != self.model or plan.get("check_profile_id") != CHECK_PROFILE_ID @@ -427,6 +465,8 @@ def _revalidate_plan(self, plan: Mapping[str, Any]) -> SourceSnapshot: ): raise ValueError("task_plan_identity_invalid") project = self._project(str(plan["project_id"])) + if self.project_gate is not None: + self.project_gate(project.root) base = snapshot_source(project.root, [str(item) for item in plan["input_paths"]]) verify_output_scope( project.root, @@ -501,7 +541,14 @@ def _run(self, task_id: str, plan_hash: str, plan: Mapping[str, Any]) -> None: base = self._revalidate_plan(plan) chain = ReceiptChain(self.evidence_root, task_id, FileRunKeyStore(self.evidence_root), profile_version="candidate-v1", policy_version="candidate-v1") broker = EvidenceBroker(chain) - input_bundle = {"contract": INPUT_CONTRACT, "plan": dict(plan), "files": base.bundle()} + if plan.get("contract") == PLAN_CONTRACT_V2: + if self.input_bundle_provider is None: + raise ValueError("candidate_child_context_unavailable") + input_bundle = dict(self.input_bundle_provider(plan)) + if input_bundle.get("contract") != INPUT_CONTRACT_V2 or input_bundle.get("plan") != dict(plan): + raise ValueError("candidate_child_context_invalid") + else: + input_bundle = {"contract": INPUT_CONTRACT, "plan": dict(plan), "files": base.bundle()} input_text = canonical_json(input_bundle) input_hash = digest_bytes(input_text.encode("utf-8")) artifact, cipher_hash, content_hash = self._artifact(broker, "accepted-input", input_text) @@ -662,6 +709,11 @@ def _project_ready(self, task_id: str, task: Mapping[str, Any]) -> dict[str, Any generated = next(body for body in bodies if body["event"] == "candidate_generated") checked = next(body for body in bodies if body["event"] == "candidate_check_completed") ready = next(body for body in bodies if body["event"] == "candidate_ready") + ready_sequence = next( + row["sequence"] + for row in receipts + if row.get("payload", {}).get("event") == "candidate_ready" + ) input_plain = read_verified_artifact(self.evidence_root, task_id, str(started["artifact"])) candidate_plain = read_verified_artifact(self.evidence_root, task_id, str(generated["artifact"])) check_plain = read_verified_artifact(self.evidence_root, task_id, str(checked["artifact"])) @@ -674,6 +726,20 @@ def _project_ready(self, task_id: str, task: Mapping[str, Any]) -> dict[str, Any ): raise ValueError("task_artifact_content_hash_mismatch") input_bundle = json.loads(input_plain) + if input_bundle.get("contract") == INPUT_CONTRACT_V2: + from torq_cli.domain.task_review import resolve_task_review + + resolved = resolve_task_review(self.evidence_root, task_id, int(ready_sequence)) + review_check = resolved.envelope["review"]["checks"] + return { + "verified": True, + "ready_sequence": ready_sequence, + "candidate_files": sorted(resolved.result_files, key=str.casefold), + "check": { + "profile": review_check["profile_id"], + "exit_code": review_check["exit_code"], + }, + } if input_bundle.get("contract") != INPUT_CONTRACT or not isinstance(input_bundle.get("plan"), dict): raise ValueError("task_input_artifact_invalid") plan = input_bundle["plan"] @@ -752,7 +818,7 @@ def _project_ready(self, task_id: str, task: Mapping[str, Any]) -> dict[str, Any for operation in expected_ops ): raise ValueError("task_candidate_content_mismatch") - return {"verified": True, "candidate_files": [item.path for item in disk.entries], "check": {"profile": CHECK_PROFILE_ID, "exit_code": checked["exit_code"]}} + return {"verified": True, "ready_sequence": ready_sequence, "candidate_files": [item.path for item in disk.entries], "check": {"profile": CHECK_PROFILE_ID, "exit_code": checked["exit_code"]}} except (OSError, ValueError, KeyError, StopIteration, json.JSONDecodeError): return {"state": "untrusted", "finding": "task_result_verification_failed", "verified": False} diff --git a/src/torq_cli/application/review_store.py b/src/torq_cli/application/review_store.py new file mode 100644 index 0000000..17f8e74 --- /dev/null +++ b/src/torq_cli/application/review_store.py @@ -0,0 +1,283 @@ +"""Separate durable state for candidate review and application requests.""" + +from __future__ import annotations + +import json +import os +import secrets +import stat +import threading +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +from torq_cli.safety.receipts import ( + fsync_directory, + restrict_owner_only_directory, + restrict_owner_only_file, + signing_file_permissions_are_restricted, +) +from torq_cli.safety.task_workspace import canonical_json, digest_bytes, digest_json +from torq_cli.safety.task_workspace import validate_disjoint_roots + +_MAX_STORE = 8_388_608 + + +class ReviewStore: + """Closed v1 store; P2's TaskStore schema remains untouched.""" + + def __init__(self, state_root: Path) -> None: + self.root = state_root.absolute() + validate_disjoint_roots([self.root]) + self.root.mkdir(parents=True, exist_ok=True) + restrict_owner_only_directory(self.root) + validate_disjoint_roots([self.root]) + self.path = self.root / "candidate-review.json" + self._lock = threading.RLock() + if not os.path.lexists(self.path): + self._write( + { + "schema": "torq-candidate-review-store-v1", + "installation_id": "installation-" + secrets.token_hex(16), + "next_ordinal": 1, + "corrections": {}, + "child_plans": {}, + "review_requests": {}, + "decisions": {}, + "apply_requests": {}, + "applications": {}, + } + ) + + def _read(self) -> dict[str, Any]: + metadata = self.path.stat(follow_symlinks=False) + if ( + not self.path.is_file() + or self.path.is_symlink() + or metadata.st_nlink != 1 + or metadata.st_size > _MAX_STORE + or not signing_file_permissions_are_restricted(self.path) + ): + raise ValueError("candidate_review_store_unsafe") + flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(self.path, flags) + try: + before = os.fstat(descriptor) + if ( + not stat.S_ISREG(before.st_mode) + or before.st_nlink != 1 + or before.st_size > _MAX_STORE + or (before.st_dev, before.st_ino) != (metadata.st_dev, metadata.st_ino) + ): + raise ValueError("candidate_review_store_unsafe") + raw = bytearray() + while len(raw) <= _MAX_STORE: + chunk = os.read(descriptor, min(65_536, _MAX_STORE + 1 - len(raw))) + if not chunk: + break + raw.extend(chunk) + after = os.fstat(descriptor) + finally: + os.close(descriptor) + if len(raw) > _MAX_STORE or ( + before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns + ) != (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns): + raise ValueError("candidate_review_store_changed") + + def unique(pairs: list[tuple[str, object]]) -> dict[str, object]: + value: dict[str, object] = {} + for key, child in pairs: + if key in value: + raise ValueError("candidate_review_store_duplicate_key") + value[key] = child + return value + + def reject(_value: str) -> object: + raise ValueError("candidate_review_store_non_finite") + + value = json.loads(bytes(raw), object_pairs_hook=unique, parse_constant=reject) + keys = { + "schema", "installation_id", "next_ordinal", "corrections", "child_plans", + "review_requests", "decisions", "apply_requests", "applications", + } + if ( + not isinstance(value, dict) + or set(value) != keys + or value.get("schema") != "torq-candidate-review-store-v1" + or not isinstance(value.get("installation_id"), str) + or not isinstance(value.get("next_ordinal"), int) + or isinstance(value.get("next_ordinal"), bool) + or value["next_ordinal"] <= 0 + or not all(isinstance(value.get(key), dict) for key in keys - {"schema", "installation_id", "next_ordinal"}) + ): + raise ValueError("candidate_review_store_invalid") + return value + + def _write(self, value: Mapping[str, Any]) -> None: + temporary = self.path.with_name(self.path.name + "." + secrets.token_hex(8) + ".tmp") + temporary.write_text(canonical_json(value), encoding="utf-8", newline="\n") + restrict_owner_only_file(temporary) + with temporary.open("r+b") as stream: + os.fsync(stream.fileno()) + os.replace(temporary, self.path) + restrict_owner_only_file(self.path) + fsync_directory(self.root) + + def snapshot(self) -> dict[str, Any]: + with self._lock: + return self._read() + + @property + def installation_id(self) -> str: + return str(self.snapshot()["installation_id"]) + + def correction(self, task_id: str, ready_sequence: int) -> dict[str, Any] | None: + key = f"{task_id}:{ready_sequence}" + with self._lock: + value = self._read()["corrections"].get(key) + return None if value is None else dict(value) + + def save_correction( + self, task_id: str, ready_sequence: int, *, text: str, expected_revision: int + ) -> dict[str, Any]: + if not text.strip() or len(text) > 16_384 or "\x00" in text: + raise ValueError("candidate_correction_invalid") + key = f"{task_id}:{ready_sequence}" + with self._lock: + data = self._read() + current = data["corrections"].get(key) + revision = 0 if current is None else current["revision"] + if revision != expected_revision: + raise ValueError("candidate_correction_revision_conflict") + value = { + "task_id": task_id, "ready_sequence": ready_sequence, "revision": revision + 1, + "text": text, "content_hash": digest_bytes(text.encode("utf-8")), + } + data["corrections"][key] = value + self._write(data) + return dict(value) + + def reserve( + self, + *, + request_kind: str, + request_id: str, + body: Mapping[str, Any], + id_prefix: str, + ) -> tuple[dict[str, Any], bool]: + if request_kind not in {"review", "apply", "child", "continuation"} or not request_id or len(request_id) > 128: + raise ValueError("candidate_request_invalid") + digest = digest_json(body) + request_key = "apply_requests" if request_kind == "apply" else "review_requests" + record_key = "applications" if request_kind == "apply" else "decisions" + with self._lock: + data = self._read() + prior = data[request_key].get(request_id) + if prior is not None: + if prior.get("request_digest") != digest or prior.get("kind") != request_kind: + raise ValueError("candidate_request_replay_conflict") + return dict(data[record_key][prior["record_id"]]), False + record_id = id_prefix + secrets.token_hex(12) + record = { + "record_id": record_id, + "kind": request_kind, + "request_id": request_id, + "request_digest": digest, + "request": dict(body), + "ordinal": data["next_ordinal"], + "state": "reserved", + "finding": None, + "result": None, + } + data["next_ordinal"] += 1 + data[request_key][request_id] = {"kind": request_kind, "request_digest": digest, "record_id": record_id} + data[record_key][record_id] = record + self._write(data) + return dict(record), True + + def update(self, record_id: str, *, application: bool, **changes: object) -> dict[str, Any]: + with self._lock: + data = self._read() + records = data["applications" if application else "decisions"] + current = records.get(record_id) + if not isinstance(current, dict): + raise ValueError("candidate_record_unknown") + current.update(changes) + self._write(data) + return dict(current) + + def replay(self, *, request_kind: str, request_id: str, body: Mapping[str, Any]) -> dict[str, Any]: + request_key = "apply_requests" if request_kind == "apply" else "review_requests" + record_key = "applications" if request_kind == "apply" else "decisions" + expected = digest_json(body) + with self._lock: + data = self._read() + prior = data[request_key].get(request_id) + if ( + not isinstance(prior, dict) + or prior.get("kind") != request_kind + or prior.get("request_digest") != expected + or not isinstance(prior.get("record_id"), str) + ): + raise ValueError("candidate_request_replay_missing") + record = data[record_key].get(prior["record_id"]) + if not isinstance(record, dict): + raise ValueError("candidate_review_store_invalid") + return dict(record) + + def save_child_plan(self, plan_hash: str, value: Mapping[str, Any]) -> None: + with self._lock: + data = self._read() + existing = data["child_plans"].get(plan_hash) + if existing is not None and existing != dict(value): + raise ValueError("candidate_child_plan_hash_collision") + data["child_plans"][plan_hash] = dict(value) + self._write(data) + + def child_plan(self, plan_hash: str) -> dict[str, Any]: + with self._lock: + value = self._read()["child_plans"].get(plan_hash) + if not isinstance(value, dict): + raise ValueError("candidate_child_plan_unknown") + return dict(value) + + def save_continuation_context( + self, project_id: str, draft_revision: int, value: Mapping[str, Any] + ) -> None: + key = f"continuation:{project_id}:{draft_revision}" + with self._lock: + data = self._read() + existing = data["child_plans"].get(key) + if existing is not None and existing != dict(value): + raise ValueError("candidate_continuation_context_conflict") + data["child_plans"][key] = dict(value) + self._write(data) + + def continuation_context( + self, project_id: str, draft_revision: int + ) -> dict[str, Any] | None: + key = f"continuation:{project_id}:{draft_revision}" + with self._lock: + value = self._read()["child_plans"].get(key) + return dict(value) if isinstance(value, dict) else None + + def set_active_continuation( + self, project_id: str, value: Mapping[str, Any] | None + ) -> None: + key = f"continuation-active:{project_id}" + with self._lock: + data = self._read() + if value is None: + data["child_plans"].pop(key, None) + else: + data["child_plans"][key] = dict(value) + self._write(data) + + def active_continuation(self, project_id: str) -> dict[str, Any] | None: + key = f"continuation-active:{project_id}" + with self._lock: + value = self._read()["child_plans"].get(key) + return dict(value) if isinstance(value, dict) else None + + +__all__ = ["ReviewStore"] diff --git a/src/torq_cli/application/task_store.py b/src/torq_cli/application/task_store.py index 26130d6..6d609ed 100644 --- a/src/torq_cli/application/task_store.py +++ b/src/torq_cli/application/task_store.py @@ -181,6 +181,13 @@ def reserve(self, request_id: str, request_body: Mapping[str, Any]) -> tuple[dic raise ValueError("task_request_replay_conflict") return dict(data["tasks"][prior["task_id"]]), False task_id = "run-task-" + secrets.token_hex(12) + ordinals = [ + item["history_ordinal"] for item in data["tasks"].values() + if isinstance(item, dict) + and isinstance(item.get("history_ordinal"), int) + and not isinstance(item["history_ordinal"], bool) + and item["history_ordinal"] > 0 + ] task = { **dict(request_body), "task_id": task_id, @@ -188,6 +195,7 @@ def reserve(self, request_id: str, request_body: Mapping[str, Any]) -> tuple[dic "request_digest": request_digest, "state": "reserved", "provider_dispatch": False, + "history_ordinal": max(ordinals, default=0) + 1, "finding": None, } data["requests"][request_id] = {"request_digest": request_digest, "task_id": task_id} diff --git a/src/torq_cli/data/fleet/index.html b/src/torq_cli/data/fleet/index.html index f25eac9..abca20a 100644 --- a/src/torq_cli/data/fleet/index.html +++ b/src/torq_cli/data/fleet/index.html @@ -93,6 +93,70 @@

Choose an individual run

+ + +

Bounded execution

What would you like to build?

@@ -131,9 +195,16 @@

Build status

History

Recent candidates

+
No candidate history yet.
+
+
diff --git a/src/torq_cli/data/fleet/task.css b/src/torq_cli/data/fleet/task.css index b80a490..53838d2 100644 --- a/src/torq_cli/data/fleet/task.css +++ b/src/torq_cli/data/fleet/task.css @@ -1,4 +1,4 @@ -.task-view { max-width: 1180px; margin: 0 auto; padding: 42px 24px 140px; } +.task-view { width: 100%; max-width: 1180px; margin: 0 auto; padding: 42px 24px 140px; overflow-x: clip; } .task-hero { max-width: 720px; margin-bottom: 28px; } .task-hero h1 { margin: 5px 0 10px; font-size: clamp(2rem, 5vw, 4rem); letter-spacing: -.045em; } .task-hero > p:last-child { color: var(--muted); line-height: 1.55; font-size: 1.05rem; } @@ -23,12 +23,78 @@ .task-history { grid-column: 1 / -1; } .task-history-row { width: 100%; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; border: 0; border-top: 1px solid var(--line); padding: 12px 0; color: var(--text); background: transparent; text-align: left; cursor: pointer; } .task-history-row small { display: block; color: var(--muted); margin-top: 4px; } +.task-history-search { display: flex; gap: 8px; margin-bottom: 10px; } +.task-history-search input { flex: 1; min-width: 0; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--surface); color: var(--text); padding: 10px 12px; font: inherit; } +.task-history-more { margin-top: 12px; } +.task-recovery-panel { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 12px; padding: 12px 14px; border: 1px solid color-mix(in srgb, var(--warn) 70%, var(--line)); border-radius: 12px; background: color-mix(in srgb, var(--warn) 12%, var(--panel)); } +.task-recovery-panel[hidden] { display: none; } +.task-recovery-panel p { margin: 4px 0 0; color: var(--muted); line-height: 1.4; } +.task-view:has(.review-view:not([hidden])) { max-width: 1320px; padding-top: 16px; padding-bottom: 24px; } +.review-view { min-height: calc(100dvh - 100px); display: grid; grid-template-rows: auto auto auto minmax(0, 1fr); gap: 9px; } +.review-view[hidden] { display: none; } +.review-view [hidden] { display: none !important; } +.review-header { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: start; gap: 18px; } +.review-heading h1 { margin: 3px 0 0; font-size: clamp(1.5rem, 2.5vw, 2rem); letter-spacing: -.025em; line-height: 1.1; } +.review-alert { min-height: 1.35em; margin: 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); } +.review-alert[data-tone="success"] { border-color: color-mix(in srgb, var(--ok) 55%, var(--line)); } +.review-alert[data-tone="warning"] { border-color: color-mix(in srgb, var(--warn) 65%, var(--line)); } +.review-tabs { display: flex; gap: 5px; border-bottom: 1px solid var(--line); overflow-x: auto; } +.review-tabs button { min-height: 44px; padding: 9px 16px; border: 0; border-bottom: 3px solid transparent; background: transparent; color: var(--muted); font: 700 .85rem var(--mono); cursor: pointer; } +.review-tabs button[aria-selected="true"] { color: var(--text); border-bottom-color: var(--accent); } +.review-workspace { height: max(330px, calc(100dvh - 245px)); min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr) minmax(270px, 340px); gap: 16px; align-items: stretch; } +.review-evidence, .review-actions { min-width: 0; border: 1px solid var(--line); border-radius: 16px; background: var(--panel); box-shadow: var(--shadow); } +.review-evidence { min-height: 0; overflow: hidden; } +.review-evidence > [role="tabpanel"] { height: 100%; box-sizing: border-box; overflow: auto; padding: 22px; } +.review-actions { overflow: auto; padding: 20px; } +.review-actions h2, .review-actions h3 { margin: 0 0 8px; } +.review-actions section { display: grid; gap: 9px; margin: 12px 0; } +.review-primary-decision { padding: 12px; border: 1px solid color-mix(in srgb, var(--accent) 40%, var(--line)); border-radius: 12px; background: color-mix(in srgb, var(--accent) 6%, var(--surface)); } +.review-actions p { margin: 0; color: var(--muted); font-size: .86rem; line-height: 1.5; } +.review-actions hr { border: 0; border-top: 1px solid var(--line); margin: 18px 0; } +.review-actions label { display: grid; gap: 5px; } +.review-actions label span { color: var(--muted); font-size: .82rem; line-height: 1.4; } +.review-correction-details > summary { min-height: 44px; display: flex; align-items: center; font-weight: 750; cursor: pointer; } +.review-correction-details > summary::marker { color: var(--accent); } +.review-actions textarea { width: 100%; box-sizing: border-box; resize: vertical; border: 1px solid var(--line-strong); border-radius: 10px; padding: 10px; background: var(--surface); color: var(--text); font: inherit; } +.review-apply-button { min-height: 44px; border: 1px solid color-mix(in srgb, var(--warn) 70%, var(--line)); border-radius: 10px; padding: 10px 14px; background: color-mix(in srgb, var(--warn) 18%, var(--surface)); color: var(--text); font-weight: 800; cursor: pointer; } +.review-summary-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; } +.review-summary-grid div { padding: 14px; border-radius: 12px; background: var(--surface); } +.review-summary-grid span { display: block; margin-bottom: 5px; color: var(--muted); font-size: .75rem; } +.review-summary-grid strong { overflow-wrap: anywhere; } +.review-plan-goal { max-width: 72ch; font-size: 1.12rem; line-height: 1.6; } +#review-panel-changes { display: grid; grid-template-columns: minmax(150px, 230px) minmax(0, 1fr); gap: 18px; padding: 0; } +#review-panel-changes[hidden] { display: none; } +.review-files { padding: 14px 0; border-right: 1px solid var(--line); overflow: auto; } +.review-files button { width: 100%; min-height: 48px; border: 0; border-left: 3px solid transparent; padding: 9px 12px; background: transparent; color: var(--text); text-align: left; cursor: pointer; overflow-wrap: anywhere; } +.review-files button[aria-current="true"] { border-left-color: var(--accent); background: color-mix(in srgb, var(--accent) 9%, var(--surface)); } +.review-files small { display: block; margin-top: 4px; color: var(--muted); text-transform: uppercase; } +.review-diff { min-width: 0; padding: 20px 20px 30px 0; } +.review-diff header { display: flex; justify-content: space-between; gap: 14px; } +.review-diff h2 { margin: 5px 0 14px; overflow-wrap: anywhere; } +.review-diff dl, .review-check-facts, .review-details dl { margin: 0; } +.review-diff header dl { font-size: .75rem; color: var(--muted); text-align: right; } +.review-diff dt, .review-diff dd { display: inline; margin: 0; } +.review-diff dt::after { content: ": "; } +.review-diff dd::after { content: ""; display: block; } +.review-diff pre, #review-panel-checks pre { max-width: 100%; overflow: auto; padding: 15px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); color: var(--text); font: .76rem/1.55 var(--mono); white-space: pre; tab-size: 2; } +.review-details { margin-top: 18px; font-size: .75rem; } +.review-details dd { margin: 4px 0 10px; overflow-wrap: anywhere; } +.review-child-plan, .review-lineage, .check-verdict { padding: 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); } +.check-verdict[data-passed="true"] { border-color: color-mix(in srgb, var(--ok) 55%, var(--line)); } +.check-verdict[data-passed="false"] { border-color: color-mix(in srgb, var(--warn) 65%, var(--line)); } +.check-verdict p { margin-bottom: 0; } +.review-check-facts { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin: 16px 0; } +.review-check-facts div { padding: 10px; background: var(--surface); border-radius: 8px; } +.review-check-facts dt { color: var(--muted); font-size: .75rem; } +.review-check-facts dd { margin: 5px 0 0; overflow-wrap: anywhere; } +.review-view button:focus-visible, .review-view textarea:focus-visible, .task-history-search input:focus-visible { outline: 3px solid color-mix(in srgb, var(--accent) 35%, transparent); outline-offset: 2px; } body[data-dashboard-view="task"] .governance-rail, body[data-dashboard-view="task"] #fleet-board, body[data-dashboard-view="task"] #mini-monitor, body[data-dashboard-view="task"] .topbar-facts, body[data-dashboard-view="task"] #system-banner, body[data-dashboard-view="task"] #annotation-list { display: none !important; } +body[data-dashboard-view="task"] .topbar, body[data-dashboard-view="task"] .topbar-tools, body[data-dashboard-view="task"] .view-switch { max-width: 100%; } @media (max-width: 760px) { .task-view { padding: 26px 12px 80px; } .task-grid, .task-two-col { grid-template-columns: 1fr; } @@ -36,4 +102,31 @@ body[data-dashboard-view="task"] #annotation-list { display: none !important; } .task-history { grid-column: auto; } .task-card { padding: 16px; border-radius: 14px; } .task-actions { align-items: stretch; flex-direction: column-reverse; } + .review-header { grid-template-columns: 1fr auto; } + .review-heading { grid-column: 1 / -1; grid-row: 2; } + .review-workspace { grid-template-columns: 1fr; } + .review-workspace { height: auto; } + .review-evidence { min-height: 55dvh; } + .review-actions { max-height: none; } + .review-summary-grid, .review-check-facts { grid-template-columns: 1fr; } + #review-panel-changes { grid-template-columns: 1fr; } + .review-files { display: flex; border-right: 0; border-bottom: 1px solid var(--line); overflow-x: auto; padding: 0; } + .review-files button { min-width: 150px; border-left: 0; border-bottom: 3px solid transparent; } + .review-files button[aria-current="true"] { border-bottom-color: var(--accent); } + .review-diff { padding: 16px; } + .review-diff header { display: block; } + .review-diff header dl { text-align: left; } + .task-history-search { flex-direction: column; } + .task-recovery-panel { align-items: stretch; flex-direction: column; } + body[data-dashboard-view="task"] .topbar { flex-wrap: wrap; } + body[data-dashboard-view="task"] .topbar-tools { width: 100%; align-items: stretch; } + body[data-dashboard-view="task"] .view-switch { display: flex; flex-wrap: wrap; } +} +@media (max-width: 340px) { + .task-view { padding-inline: 8px; } + .review-evidence > [role="tabpanel"], .review-actions { padding: 14px; } + .review-tabs button { padding-inline: 11px; } +} +@media (prefers-reduced-motion: reduce) { + .review-view *, .review-view *::before, .review-view *::after { scroll-behavior: auto !important; transition-duration: .01ms !important; animation-duration: .01ms !important; } } diff --git a/src/torq_cli/data/fleet/task.js b/src/torq_cli/data/fleet/task.js index 066167a..6b5608d 100644 --- a/src/torq_cli/data/fleet/task.js +++ b/src/torq_cli/data/fleet/task.js @@ -1,268 +1,85 @@ (() => { "use strict"; - class MutationQueue { - constructor() { this.tail = Promise.resolve(); } - enqueue(work) { this.tail = this.tail.catch(() => {}).then(work); return this.tail; } - } - class EditGate { - constructor() { this.epoch = 0; } - edited() { this.epoch += 1; } - capture(project, snapshot) { return {epoch:this.epoch, project, snapshot}; } - accepts(ticket, project, snapshot) { return ticket.epoch === this.epoch && ticket.project === project && ticket.snapshot === snapshot; } - } - function requestIdForPlan(planHash, storage, cryptoSource) { - const key = `torq.task.request.${planHash}`; - try { - const value = storage.getItem(key) || cryptoSource.randomUUID(); - storage.setItem(key, value); - return value; - } catch (_) { return `request-${planHash.slice(7,31)}`; } - } - globalThis.TorqTask = { MutationQueue, EditGate, requestIdForPlan }; - const byId = (id) => document.getElementById(id); - const view = byId("task-view"); - const button = byId("task-view-button"); - if (!view || !button) return; - - const mutationQueue = new MutationQueue(); - const editGate = new EditGate(); - const state = { capabilities: null, project: "", revisions: {}, saved: {}, plan: null, active: null, loadToken: 0, saveTimer: null, initialized: false, draftReady: false }; - const lines = (value) => value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean); - const escape = (value) => String(value).replace(/[&<>"']/g, (char) => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[char])); - - async function request(path, options = {}) { - const response = await fetch(path, { credentials: "same-origin", headers: {"Content-Type":"application/json"}, ...options }); - const body = await response.json(); - if (!response.ok) throw new Error(body.finding || "task_request_failed"); - return body; - } - - function setStatus(message) { byId("task-draft-status").textContent = message; } - function setView() { - document.body.dataset.dashboardView = "task"; - view.hidden = false; - byId("workspace-view").hidden = true; - byId("fleet-board").hidden = true; - button.setAttribute("aria-pressed", "true"); - byId("workspace-view-button").setAttribute("aria-pressed", "false"); - byId("fleet-view-button").setAttribute("aria-pressed", "false"); - byId("skip-link").href = "#task-view"; - byId("skip-link").textContent = "Skip to new task"; - view.focus(); - if (!state.initialized) { - state.initialized = true; - refresh().catch(() => { state.initialized = false; setDraftReady(false); setStatus("Task setup is unavailable. Reload to try again."); }); - } else { - loadHistory().catch(() => setStatus("Could not refresh task history.")); - } - } - button.addEventListener("click", setView); - [byId("workspace-view-button"), byId("fleet-view-button")].forEach((item) => item.addEventListener("click", () => { - view.hidden = true; - button.setAttribute("aria-pressed", "false"); - delete document.body.dataset.dashboardView; - })); - - function setDraftReady(ready) { - state.draftReady = ready; - ["task-project", "task-goal", "task-input-paths", "task-output-paths", "task-clear", "task-review"].forEach((id) => { - const control = byId(id); - if (control) control.disabled = !ready; - }); - } - - async function loadDraft(project, expectedEpoch = editGate.epoch) { - const token = ++state.loadToken; - const epoch = expectedEpoch; - const body = await request(`/api/v1/tasks/drafts/${encodeURIComponent(project)}`, {headers:{}}); - if (token !== state.loadToken || project !== state.project) return; - const draft = body.draft; - state.revisions[project] = draft ? draft.revision : 0; - if (epoch !== editGate.epoch) return; - byId("task-goal").value = draft ? draft.goal : ""; - byId("task-input-paths").value = draft ? draft.input_paths.join("\n") : ""; - byId("task-output-paths").value = draft ? draft.output_paths.join("\n") : ""; - state.saved[project] = JSON.stringify({project, goal:draft ? draft.goal : "", inputPaths:draft ? draft.input_paths : [], outputPaths:draft ? draft.output_paths : []}); - setStatus(draft && draft.goal ? `Saved on this installation · revision ${state.revisions[project]}` : "Drafts are saved on this installation."); - } - - async function refresh() { - setDraftReady(false); - setStatus("Loading saved draft..."); - const initialEpoch = editGate.epoch; - const caps = await request("/api/v1/tasks/capabilities", {headers:{}}); - state.capabilities = caps; - const select = byId("task-project"); - const prior = state.project; - select.innerHTML = caps.projects.map((item) => ``).join(""); - state.project = caps.projects.some((item) => item.id === prior) ? prior : (caps.projects[0] || {}).id || ""; - select.value = state.project; + class MutationQueue { constructor(){this.tail=Promise.resolve();} enqueue(work){this.tail=this.tail.catch(()=>{}).then(work);return this.tail;} } + class EditGate { constructor(){this.epoch=0;} edited(){this.epoch+=1;} capture(project,snapshot){return{epoch:this.epoch,project,snapshot};} accepts(ticket,project,snapshot){return ticket.epoch===this.epoch&&ticket.project===project&&ticket.snapshot===snapshot;} } + class ReviewGate { constructor(){this.epoch=0;this.key="";} select(task,sequence){this.epoch+=1;this.key=`${task}:${sequence}`;return this.capture();} capture(){return{epoch:this.epoch,key:this.key};} accepts(ticket){return ticket.epoch===this.epoch&&ticket.key===this.key;} } + class RecoveryGate { constructor(){this.epoch=0;this.project="";} select(project){this.epoch+=1;this.project=project;return this.capture();} capture(){return{epoch:this.epoch,project:this.project};} accepts(ticket){return ticket.epoch===this.epoch&&ticket.project===this.project;} } + class HistoryGate { constructor(){this.epoch=0;this.query="";} select(query){this.epoch+=1;this.query=query;return this.capture();} capture(){return{epoch:this.epoch,query:this.query};} accepts(ticket){return ticket.epoch===this.epoch&&ticket.query===this.query;} } + function stableRequestId(kind,identity,storage,cryptoSource){const key=`torq.task.${kind}.${identity}`;try{const value=storage.getItem(key)||cryptoSource.randomUUID();storage.setItem(key,value);return value;}catch(_){return`request-${kind}-${String(identity).replace(/[^a-zA-Z0-9]/g,"").slice(0,24)}`;}} + function forgetAfterDefiniteRejection(error,kind,identity,storage){if(!error||!Number.isInteger(error.status)||error.status<400||error.status>499)return false;try{storage.removeItem(`torq.task.${kind}.${identity}`);return true;}catch(_){return false;}} + function requestIdForPlan(planHash,storage,cryptoSource){const key=`torq.task.request.${planHash}`;try{const value=storage.getItem(key)||cryptoSource.randomUUID();storage.setItem(key,value);return value;}catch(_){return`request-${String(planHash).slice(7,31)}`;}} + function unwrap(body,key){if(body&&typeof body.schema==="string")return body;if(body&&body.result!==undefined)return body.result;if(body&&body[key]!==undefined)return body[key];return body;} + function formatNewlineMetadata(meta,text){if(meta&&typeof meta==="object"){const style=String(meta.style||"newline style recorded").toUpperCase();const bytes=Number.isInteger(meta.bytes)?` · ${meta.bytes} bytes`:"";const ending=meta.final_newline===true?"final newline":meta.final_newline===false?"no final newline":(text&&text.endsWith("\n")?"final newline":"no final newline");return`${style}${bytes} · ${ending}`;}return`${String(meta||"newline style recorded").toUpperCase()} · ${text&&text.endsWith("\n")?"final newline":"no final newline"}`;} + function formatCheckOutput(output){if(!output||typeof output!=="object")return String(output||"No output recorded.");const checked=Array.isArray(output.checked)?output.checked:[];const status=output.status?`Status: ${readableValue(output.status)}`:"Structural output recorded.";const files=checked.map((item)=>item&&typeof item==="object"?`• ${String(item.path||"Unknown file")}${item.validator?` — ${readableValue(item.validator)}`:""}`:`• ${String(item)}`);return files.length?`${status}\nChecked files:\n${files.join("\n")}`:status;} + function readableValue(value){return String(value||"").replaceAll("_"," ");} + function canRecover(status){return !!status&&status.state==="recovery_required"&&status.owned===true;} + function applicationApplied(application){return !!application&&["applied","candidate_applied"].includes(application.state);} + function applicationBlocksApply(application){return applicationApplied(application)||!!application&&application.state==="recovery_required";} + function applicationRetryIdentity(candidate,acceptance,application){const prior=application&&["rejected","rolled_back"].includes(application.state)?`${application.application_id}.${application.state}`:"initial";return`${candidate.review_hash}.${acceptance.decision_id}.${prior}`;} + function applicationOutcomeMessage(application){if(applicationApplied(application))return"Candidate applied to the configured project. The signed review remains historical evidence.";if(application&&application.state==="recovery_required")return"Application did not complete. This project requires recovery before another Apply.";if(application&&application.state==="rolled_back")return"Application did not complete and the original project files were restored. Reopen eligibility before trying a fresh Apply.";if(application&&application.state==="rejected")return`Application was rejected${application.finding?`: ${readableValue(application.finding)}`:""}. Resolve the finding before trying a fresh Apply.`;return"Application did not complete. Reopen this review for the verified outcome and remedy.";} + globalThis.TorqTask={MutationQueue,EditGate,ReviewGate,RecoveryGate,HistoryGate,stableRequestId,forgetAfterDefiniteRejection,requestIdForPlan,unwrap,formatNewlineMetadata,formatCheckOutput,canRecover,applicationApplied,applicationBlocksApply,applicationRetryIdentity,applicationOutcomeMessage}; + const byId=(id)=>document.getElementById(id), view=byId("task-view"), button=byId("task-view-button"); + if(!view||!button)return; + const mutationQueue=new MutationQueue(), editGate=new EditGate(), reviewGate=new ReviewGate(), recoveryGate=new RecoveryGate(), historyGate=new HistoryGate(); + const terminal=["candidate_ready","failed","cancelled","interrupted","termination_unknown","untrusted"]; + const state={capabilities:null,project:"",revisions:{},saved:{},plan:null,active:null,loadToken:0,saveTimer:null,initialized:false,draftReady:false,review:null,selectedChange:0,correction:null,childPlan:null,acceptance:null,application:null,lastFocus:null,recoveryProject:"",historyQuery:"",historyCursor:null}; + const lines=(value)=>value.split(/\r?\n/).map((item)=>item.trim()).filter(Boolean); + const escape=(value)=>String(value==null?"":value).replace(/[&<>"']/g,(char)=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[char])); + const readable=readableValue; + async function request(path,options={}){const response=await fetch(path,{credentials:"same-origin",headers:{"Content-Type":"application/json"},...options});let body={};try{body=await response.json();}catch(_){}if(!response.ok){const error=new Error(body.finding||body.error||"task_request_failed");error.status=response.status;throw error;}return body;} + const enqueueMutation=(work)=>mutationQueue.enqueue(work); + function setStatus(message){byId("task-draft-status").textContent=message;} + function announce(message){if(byId("live-announcer"))byId("live-announcer").textContent=message;} + function setDraftReady(ready){state.draftReady=ready;["task-project","task-goal","task-input-paths","task-output-paths","task-clear","task-review"].forEach((id)=>{if(byId(id))byId(id).disabled=!ready;});} + function setView(){document.body.dataset.dashboardView="task";view.hidden=false;byId("workspace-view").hidden=true;byId("fleet-board").hidden=true;button.setAttribute("aria-pressed","true");byId("workspace-view-button").setAttribute("aria-pressed","false");byId("fleet-view-button").setAttribute("aria-pressed","false");byId("skip-link").href="#task-view";byId("skip-link").textContent="Skip to tasks";view.focus();if(!state.initialized){state.initialized=true;refresh().catch(()=>{state.initialized=false;setDraftReady(false);setStatus("Task setup is unavailable. Reload to try again.");});}else loadHistory().catch(()=>setStatus("Could not refresh task history."));} + button.addEventListener("click",setView); + [byId("workspace-view-button"),byId("fleet-view-button")].forEach((item)=>item.addEventListener("click",()=>{view.hidden=true;button.setAttribute("aria-pressed","false");delete document.body.dataset.dashboardView;})); + async function loadDraft(project,expectedEpoch=editGate.epoch){const token=++state.loadToken,body=await request(`/api/v1/tasks/drafts/${encodeURIComponent(project)}`,{headers:{}});if(token!==state.loadToken||project!==state.project)return;const draft=body.draft;state.revisions[project]=draft?draft.revision:0;if(expectedEpoch!==editGate.epoch)return;byId("task-goal").value=draft?draft.goal:"";byId("task-input-paths").value=draft?draft.input_paths.join("\n"):"";byId("task-output-paths").value=draft?draft.output_paths.join("\n"):"";state.saved[project]=JSON.stringify({project,goal:draft?draft.goal:"",inputPaths:draft?draft.input_paths:[],outputPaths:draft?draft.output_paths:[]});setStatus(draft&&draft.goal?`Saved on this installation · revision ${state.revisions[project]}`:"Drafts are saved on this installation.");} + async function refresh(){setDraftReady(false);setStatus("Loading saved draft...");const initialEpoch=editGate.epoch,caps=await request("/api/v1/tasks/capabilities",{headers:{}});state.capabilities=caps;const select=byId("task-project"),prior=state.project;select.innerHTML=caps.projects.map((item)=>``).join("");state.project=caps.projects.some((item)=>item.id===prior)?prior:(caps.projects[0]||{}).id||"";select.value=state.project; await loadDraft(state.project, initialEpoch); setDraftReady(true); - await loadHistory(); - if (caps.active_task_id) { - state.active = caps.active_task_id; - pollTask(); - } - } - - async function refreshTaskCapabilities() { - state.capabilities = await request("/api/v1/tasks/capabilities", {headers:{}}); - return state.capabilities; - } - - byId("task-project").addEventListener("change", async (event) => { - const newProject = event.target.value; - const pendingSave = byId("task-goal").value.trim() ? saveDraft().catch(() => {}) : Promise.resolve(); - setDraftReady(false); - state.plan = null; - byId("task-start").disabled = true; - await pendingSave; - state.project = newProject; - try { await loadDraft(state.project); setDraftReady(true); } - catch (error) { setStatus(error.message.replaceAll("_", " ")); } - }); - - const formSnapshot = () => ({ - project: state.project, - goal: byId("task-goal").value, - inputPaths: lines(byId("task-input-paths").value), - outputPaths: lines(byId("task-output-paths").value) - }); - const enqueueMutation = (work) => { - return mutationQueue.enqueue(work); - }; - - function saveDraft() { - if (!state.draftReady) return Promise.reject(new Error("task_draft_loading")); - const snapshot = formSnapshot(); - const work = async () => { - const {project, goal, inputPaths, outputPaths} = snapshot; - if (!goal.trim()) throw new Error("Enter a goal before reviewing."); - const encoded = JSON.stringify(snapshot); - if (state.saved[project] === encoded) { - return {project_id:project, goal, input_paths:inputPaths, output_paths:outputPaths, revision:state.revisions[project] || 0}; - } - const body = await request(`/api/v1/tasks/drafts/${encodeURIComponent(project)}`, { - method:"POST", body:JSON.stringify({goal, input_paths:inputPaths, output_paths:outputPaths, expected_revision:state.revisions[project] || 0}) - }); - state.revisions[project] = body.result.revision; - state.saved[project] = encoded; - if (project === state.project && JSON.stringify(formSnapshot()) === JSON.stringify(snapshot)) { - setStatus(`Saved on this installation · revision ${body.result.revision}`); - } - return body.result; - }; - return enqueueMutation(work); - } - - ["task-goal","task-input-paths","task-output-paths"].forEach((id) => byId(id).addEventListener("input", () => { - editGate.edited(); - state.plan = null; - byId("task-start").disabled = true; - byId("task-plan-summary").textContent = "Review the updated goal and scope before starting."; - setStatus("Saving changes…"); - clearTimeout(state.saveTimer); - if (byId("task-goal").value.trim()) state.saveTimer = setTimeout(() => saveDraft().catch((error) => setStatus(error.message.replaceAll("_", " "))), 650); - })); - - byId("task-form").addEventListener("submit", async (event) => { - event.preventDefault(); - try { - clearTimeout(state.saveTimer); - const reviewedSnapshot = JSON.stringify(formSnapshot()); - const reviewTicket = editGate.capture(state.project, reviewedSnapshot); - const draft = await saveDraft(); - const reviewedProject = state.project; - const body = await enqueueMutation(() => request("/api/v1/tasks/plans", {method:"POST", body:JSON.stringify({project_id:reviewedProject, draft_revision:draft.revision, input_paths:draft.input_paths, output_paths:draft.output_paths})})); - if (!editGate.accepts(reviewTicket, state.project, JSON.stringify(formSnapshot())) || draft.revision !== state.revisions[state.project]) return; - state.plan = body.result; - const projectLabel = (state.capabilities.projects.find((item) => item.id === state.project) || {}).label || state.project; - byId("task-plan-summary").innerHTML = `
Project
${escape(projectLabel)}
Provider
${escape(state.plan.provider)} · ${escape(state.plan.model)}
Check
Syntax and file format
Allowed files
    ${state.plan.output_paths.map((path) => `
  • ${escape(path)}
  • `).join("")}

The provider can return contents only for these paths. TORQ writes a separate candidate and runs Python syntax, strict JSON, or UTF-8 checks. It does not run unit tests or change your project.

Plan digest${escape(state.plan.plan_hash)}
`; - byId("task-start").disabled = !state.capabilities.can_start_task; - } catch (error) { setStatus(error.message.replaceAll("_", " ")); } - }); - - byId("task-clear").addEventListener("click", async () => { - try { - clearTimeout(state.saveTimer); - const project = state.project; - const deleteTicket = editGate.capture(project, JSON.stringify(formSnapshot())); - const body = await enqueueMutation(() => request(`/api/v1/tasks/drafts/${encodeURIComponent(project)}/delete`, {method:"POST", body:JSON.stringify({expected_revision:state.revisions[project] || 0})})); - state.revisions[project] = body.result.revision; - state.saved[project] = JSON.stringify({project, goal:"", inputPaths:[], outputPaths:[]}); - if (!editGate.accepts(deleteTicket, state.project, JSON.stringify(formSnapshot()))) return; - ["task-goal","task-input-paths","task-output-paths"].forEach((id) => { byId(id).value = ""; }); - state.plan = null; byId("task-start").disabled = true; byId("task-plan-summary").textContent = "Save a goal to review its exact execution plan."; - setStatus("Draft deleted from this installation."); - } catch (error) { setStatus(error.message.replaceAll("_", " ")); } - }); - - byId("task-start").addEventListener("click", async () => { - if (!state.plan) return; - const plan = state.plan; - const startTicket = editGate.capture(state.project, JSON.stringify(formSnapshot())); - byId("task-start").disabled = true; - try { - const requestId = requestIdForPlan(plan.plan_hash, localStorage, globalThis.crypto); - const body = await enqueueMutation(() => { - if (state.plan !== plan || !editGate.accepts(startTicket, state.project, JSON.stringify(formSnapshot()))) throw new Error("task_plan_changed"); - return request("/api/v1/tasks", {method:"POST", body:JSON.stringify({request_id:requestId, plan_hash:plan.plan_hash})}); - }); - if (state.plan !== plan || !editGate.accepts(startTicket, state.project, JSON.stringify(formSnapshot()))) return; - state.active = body.result.task_id; - renderTask(body.result); - pollTask(); - } catch (error) { if (state.plan === plan) byId("task-start").disabled = false; setStatus(`${error.message.replaceAll("_", " ")}. Select Start building to retry the same request.`); } - }); - - function renderTask(task) { - const terminal = ["candidate_ready","failed","cancelled","interrupted","termination_unknown","untrusted"].includes(task.state); - byId("task-current").innerHTML = `${escape(task.state.replaceAll("_"," "))}${task.finding ? `

${escape(task.finding.replaceAll("_"," "))}

` : ""}${task.verified ? `
Candidate verified
${escape((task.candidate_files || []).join(", "))}
Structural check exit ${escape(task.check.exit_code)}
` : ""}`; - byId("task-stop").disabled = terminal; - } - - async function pollTask() { - if (!state.active) return; - try { - const body = await request(`/api/v1/tasks/${encodeURIComponent(state.active)}`, {headers:{}}); - renderTask(body.task); - if (!["candidate_ready","failed","cancelled","interrupted","termination_unknown","untrusted"].includes(body.task.state)) setTimeout(pollTask, 600); - else { state.active = null; await loadHistory(); await refreshTaskCapabilities(); } - } catch (_) { setTimeout(pollTask, 1200); } - } - - byId("task-stop").addEventListener("click", async () => { - if (!state.active) return; - const activeTask = state.active; - byId("task-stop").disabled = true; - try { - const body = await enqueueMutation(() => request(`/api/v1/tasks/${encodeURIComponent(activeTask)}/stop`, {method:"POST", body:""})); - renderTask(body.result); - if (["candidate_ready","failed","cancelled","interrupted","termination_unknown","untrusted"].includes(body.result.state)) { - state.active = null; - await loadHistory(); - await refreshTaskCapabilities(); - } - } - catch (error) { setStatus(error.message.replaceAll("_", " ")); } - }); - - async function loadHistory() { - const body = await request("/api/v1/tasks", {headers:{}}); - byId("task-history-list").innerHTML = body.tasks.length ? body.tasks.map((task) => ``).join("") : "No candidate history yet."; - byId("task-history-list").querySelectorAll("[data-task-id]").forEach((row) => row.addEventListener("click", async () => { - const body = await request(`/api/v1/tasks/${encodeURIComponent(row.dataset.taskId)}`, {headers:{}}); - state.active = body.task.task_id; - renderTask(body.task); - if (!["candidate_ready","failed","cancelled","interrupted","termination_unknown","untrusted"].includes(body.task.state)) pollTask(); - else { state.active = null; await refreshTaskCapabilities(); } - })); - } - - request("/api/v1/tasks/capabilities", {headers:{}}).then((caps) => { - state.capabilities = caps; - button.hidden = false; - if (new URLSearchParams(location.search).get("view") === "task") setView(); - }).catch(() => { button.hidden = true; }); + await loadHistory();loadRecovery(state.project);if(caps.active_task_id){state.active=caps.active_task_id;pollTask();}} + async function refreshTaskCapabilities(){state.capabilities=await request("/api/v1/tasks/capabilities",{headers:{}});return state.capabilities;} + const formSnapshot=()=>({project:state.project,goal:byId("task-goal").value,inputPaths:lines(byId("task-input-paths").value),outputPaths:lines(byId("task-output-paths").value)}); + function saveDraft(){if (!state.draftReady) return Promise.reject(new Error("task_draft_loading"));const snapshot=formSnapshot();return enqueueMutation(async()=>{const{project,goal,inputPaths,outputPaths}=snapshot;if(!goal.trim())throw new Error("Enter a goal before reviewing.");const encoded=JSON.stringify(snapshot);if(state.saved[project]===encoded)return{project_id:project,goal,input_paths:inputPaths,output_paths:outputPaths,revision:state.revisions[project]||0};const body=await request(`/api/v1/tasks/drafts/${encodeURIComponent(project)}`,{method:"POST",body:JSON.stringify({goal,input_paths:inputPaths,output_paths:outputPaths,expected_revision:state.revisions[project]||0})});state.revisions[project]=body.result.revision;state.saved[project]=encoded;if(project===state.project&&JSON.stringify(formSnapshot())===JSON.stringify(snapshot))setStatus(`Saved on this installation · revision ${body.result.revision}`);return body.result;});} + byId("task-project").addEventListener("change",async(event)=>{const next=event.target.value,pending=byId("task-goal").value.trim()?saveDraft().catch(()=>{}):Promise.resolve();setDraftReady(false);state.plan=null;byId("task-start").disabled=true;await pending;state.project=next;loadRecovery(next);try{await loadDraft(next);setDraftReady(true);}catch(error){setStatus(readable(error.message));}}); + ["task-goal","task-input-paths","task-output-paths"].forEach((id)=>byId(id).addEventListener("input",()=>{editGate.edited();state.plan=null;byId("task-start").disabled=true;byId("task-plan-summary").textContent="Review the updated goal and scope before starting.";setStatus("Saving changes…");clearTimeout(state.saveTimer);if(byId("task-goal").value.trim())state.saveTimer=setTimeout(()=>saveDraft().catch((error)=>setStatus(readable(error.message))),650);})); + byId("task-form").addEventListener("submit",async(event)=>{event.preventDefault();try{clearTimeout(state.saveTimer);const snapshot=JSON.stringify(formSnapshot()),ticket=editGate.capture(state.project,snapshot),draft=await saveDraft(),project=state.project,body=await enqueueMutation(()=>request("/api/v1/tasks/plans",{method:"POST",body:JSON.stringify({project_id:project,draft_revision:draft.revision,input_paths:draft.input_paths,output_paths:draft.output_paths})}));if(!editGate.accepts(ticket,state.project,JSON.stringify(formSnapshot()))||draft.revision!==state.revisions[state.project])return;state.plan=body.result;const label=(state.capabilities.projects.find((item)=>item.id===state.project)||{}).label||state.project;byId("task-plan-summary").innerHTML=`
Project
${escape(label)}
Provider
${escape(state.plan.provider)} · ${escape(state.plan.model)}
Check
Syntax and file format
Allowed files
    ${state.plan.output_paths.map((path)=>`
  • ${escape(path)}
  • `).join("")}

The provider can return contents only for these paths. TORQ writes a separate candidate and runs Python syntax, strict JSON, or UTF-8 checks. It does not run unit tests or change your project.

Plan digest${escape(state.plan.plan_hash)}
`;byId("task-start").disabled=!state.capabilities.can_start_task;}catch(error){setStatus(readable(error.message));}}); + byId("task-clear").addEventListener("click",async()=>{try{clearTimeout(state.saveTimer);const project=state.project,ticket=editGate.capture(project,JSON.stringify(formSnapshot())),body=await enqueueMutation(()=>request(`/api/v1/tasks/drafts/${encodeURIComponent(project)}/delete`,{method:"POST",body:JSON.stringify({expected_revision:state.revisions[project]||0})}));state.revisions[project]=body.result.revision;state.saved[project]=JSON.stringify({project,goal:"",inputPaths:[],outputPaths:[]});if(!editGate.accepts(ticket,state.project,JSON.stringify(formSnapshot())))return;["task-goal","task-input-paths","task-output-paths"].forEach((id)=>{byId(id).value="";});state.plan=null;byId("task-start").disabled=true;byId("task-plan-summary").textContent="Save a goal to review its exact execution plan.";setStatus("Draft deleted from this installation.");}catch(error){setStatus(readable(error.message));}}); + byId("task-start").addEventListener("click",async()=>{if(!state.plan)return;const plan=state.plan,ticket=editGate.capture(state.project,JSON.stringify(formSnapshot()));byId("task-start").disabled=true;try{const requestId=requestIdForPlan(plan.plan_hash,localStorage,globalThis.crypto),body=await enqueueMutation(()=>{if(state.plan!==plan||!editGate.accepts(ticket,state.project,JSON.stringify(formSnapshot())))throw new Error("task_plan_changed");return request("/api/v1/tasks",{method:"POST",body:JSON.stringify({request_id:requestId,plan_hash:plan.plan_hash})});});if(state.plan!==plan||!editGate.accepts(ticket,state.project,JSON.stringify(formSnapshot())))return;state.active=body.result.task_id;renderTask(body.result);pollTask();}catch(error){if(state.plan===plan)byId("task-start").disabled=false;setStatus(`${readable(error.message)}. Select Start building to retry the same request.`);}}); + function renderTask(task){const done=terminal.includes(task.state);byId("task-current").innerHTML=`${escape(readable(task.state))}${task.finding?`

${escape(readable(task.finding))}

`:""}${task.verified?`
Candidate verified
${escape((task.candidate_files||[]).join(", "))}
Structural check exit ${escape(task.check.exit_code)}${task.ready_sequence!=null?`
`:""}
`:""}`;const open=byId("task-current").querySelector("[data-review-task]");if(open)open.addEventListener("click",()=>openReview(open.dataset.reviewTask,Number(open.dataset.reviewReady),task.goal_summary||task.goal||"Candidate review"));byId("task-stop").disabled=done;} + async function pollTask(){if(!state.active)return;try{const body=await request(`/api/v1/tasks/${encodeURIComponent(state.active)}`,{headers:{}});renderTask(body.task);if(!terminal.includes(body.task.state))setTimeout(pollTask,600);else{state.active=null;await loadHistory();await refreshTaskCapabilities();}}catch(_){setTimeout(pollTask,1200);}} + byId("task-stop").addEventListener("click",async()=>{if(!state.active)return;const active=state.active;byId("task-stop").disabled=true;try{const body=await enqueueMutation(()=>request(`/api/v1/tasks/${encodeURIComponent(active)}/stop`,{method:"POST",body:""}));renderTask(body.result);if(terminal.includes(body.result.state)){state.active=null;await loadHistory();await refreshTaskCapabilities();}}catch(error){setStatus(readable(error.message));}}); + + const reviewPath=(task,sequence,suffix="")=>`/api/v1/task-reviews/${encodeURIComponent(task)}/${encodeURIComponent(sequence)}${suffix}`; + const remedies={task_review_source_stale:"The project changed after this candidate was built. Start a new task from the current source.",task_apply_recovery_required:"This project has an interrupted application. Use the recovery action, then reopen this review.",task_apply_primary_busy:"Another application is using this project. Wait for it to finish, then try again.",task_apply_parent_missing:"Create the missing project folder, then reopen this review.",task_review_unverified:"The signed candidate evidence could not be verified. Rebuild the candidate before accepting it.",task_correction_revision_conflict:"The correction changed in another session. Reopen this review to load the saved draft.",candidate_continuation_draft_occupied:"This project already has a saved task draft. Return to tasks and finish or delete that draft before continuing."}; + const remedyFor=(code)=>remedies[code]||`${readable(code)}. Reopen the review and try again.`; + function setReviewAlert(message,tone=""){byId("review-alert").textContent=message;byId("review-alert").dataset.tone=tone;announce(message);} + function renderRecovery(status){const panel=byId("task-recovery-panel"),button=byId("task-recover");if(!status||status.state==="idle"){panel.hidden=true;button.hidden=true;return;}panel.hidden=false;byId("task-recovery-title").textContent="Project recovery required";byId("task-recovery-message").textContent=status.owned===true?"An interrupted application must be resolved before this project can accept new work.":"Another TORQ installation owns this interrupted application. Open that installation to recover it; this dashboard will not modify its journal.";button.hidden=!canRecover(status);button.disabled=false;} + async function loadRecovery(project){if(!project){renderRecovery(null);return;}state.recoveryProject=project;const ticket=recoveryGate.select(project);try{const status=await request(`/api/v1/task-recovery/${encodeURIComponent(project)}`,{headers:{}});if(recoveryGate.accepts(ticket)&&state.recoveryProject===project)renderRecovery(status);}catch(error){if(recoveryGate.accepts(ticket)&&state.recoveryProject===project){renderRecovery({state:"recovery_required",owned:false});byId("task-recovery-message").textContent=`Recovery status is unavailable: ${readable(error.message)}. Reload before starting or applying work.`;}}} + byId("task-recover").addEventListener("click",async()=>{const project=state.recoveryProject,ticket=recoveryGate.capture(),reviewTicket=reviewGate.capture(),control=byId("task-recover");if(!project)return;control.disabled=true;try{await enqueueMutation(()=>request(`/api/v1/task-recovery/${encodeURIComponent(project)}/recover`,{method:"POST",body:"{}"}));if(!recoveryGate.accepts(ticket)||state.recoveryProject!==project)return;await loadRecovery(project);await refreshTaskCapabilities();if(reviewGate.accepts(reviewTicket)&&state.review){const identity=state.review.review;await openReview(identity.task_id,identity.ready_sequence,byId("review-title").textContent);}else setStatus("Project recovery completed. You can review or start work again.");}catch(error){if(recoveryGate.accepts(ticket)&&state.recoveryProject===project){control.disabled=false;renderRecovery({state:"recovery_required",owned:true});byId("task-recovery-message").textContent=`Recovery remains blocked: ${readable(error.message)}. Resolve the reported project conflict, then retry.`;}}}); + function showCompose(focus=true){reviewGate.select("",0);state.review=null;state.childPlan=null;state.acceptance=null;state.application=null;byId("task-review-view").hidden=true;byId("task-compose-view").hidden=false;loadRecovery(state.project);if(focus)(state.lastFocus&&document.contains(state.lastFocus)?state.lastFocus:byId("task-history-query")).focus();} + byId("review-back").addEventListener("click",()=>showCompose()); + function renderPlan(review){const plan=review.plan||{},lineage=review.lineage||plan.lineage;byId("review-panel-plan").innerHTML=`
Project${escape(plan.project_label||plan.project_id||"Configured project")}
Provider${escape([plan.provider,plan.model].filter(Boolean).join(" · "))}
Files in scope${escape((plan.output_paths||[]).length)}

Goal

${escape(plan.goal||"No goal recorded")}

Reviewed scope

    ${(plan.output_paths||[]).map((path)=>`
  • ${escape(path)}
  • `).join("")}
${lineage?`

Lineage

This candidate is a ${escape(lineage.mode||"revision")} of task ${escape((lineage.parent_candidate||{}).task_id||lineage.parent_task_id||"")}.

`:""}`;} + function renderDiff(){const changes=(state.review&&state.review.review.changes)||[],change=changes[state.selectedChange];if(!change){byId("review-diff").textContent="No file changes.";return;}byId("review-files").querySelectorAll("button").forEach((item,index)=>{item.setAttribute("aria-current",index===state.selectedChange?"true":"false");item.tabIndex=index===state.selectedChange?0:-1;});const diff=change.diff_complete===false?`${change.diff||""}\n\nDiff detail was truncated. Inspect the bounded reviewed result text below.`:change.diff||"No textual diff.";byId("review-diff").innerHTML=`
${escape(readable(change.operation))}

${escape(change.path)}

Before
${escape(formatNewlineMetadata(change.base_newlines,change.base_text))}
After
${escape(formatNewlineMetadata(change.result_newlines,change.result_text))}
${escape(diff)}
${change.diff_complete===false?`
Reviewed result text
${escape(change.result_text||"")}
`:""}
File hashes
Base
${escape(change.base_hash||"Absent")}
Result
${escape(change.result_hash)}
`;} + function renderChanges(review){const changes=review.changes||[];byId("review-change-count").textContent=`(${changes.length})`;byId("review-files").innerHTML=changes.map((change,index)=>``).join("");const controls=Array.from(byId("review-files").querySelectorAll("button"));controls.forEach((item,index)=>{item.addEventListener("click",()=>{state.selectedChange=Number(item.dataset.changeIndex);renderDiff();});item.addEventListener("keydown",(event)=>{let next;if(event.key==="ArrowDown"||event.key==="ArrowRight")next=(index+1)%controls.length;if(event.key==="ArrowUp"||event.key==="ArrowLeft")next=(index-1+controls.length)%controls.length;if(event.key==="Home")next=0;if(event.key==="End")next=controls.length-1;if(next!==undefined){event.preventDefault();state.selectedChange=next;renderDiff();controls[next].focus();}});});state.selectedChange=0;renderDiff();} + function renderChecks(review){const check=review.checks||{},passed=Number(check.exit_code)===0&&check.output_complete===true&&check.termination==="confirmed_empty";byId("review-panel-checks").innerHTML=`
${passed?"Structural checks passed":"Structural checks did not pass"}

${passed?"The signed bounded file-format check completed successfully.":"Acceptance is unavailable until a complete successful check is recorded."}

Profile
${escape([check.profile_id,check.profile_version].filter(Boolean).join(" · "))}
Exit code
${escape(check.exit_code)}
Output
${check.output_complete?"Complete":"Incomplete"}
Termination
${escape(readable(check.termination))}

Check output

${escape(formatCheckOutput(check.output))}

Command contract: ${escape(check.command_contract||"python -I -S ")}. This is a structural file check; project tests were not run.

Check identifiers
Helper
${escape(check.helper_hash)}
Arguments
${escape(check.argv_hash)}
`;return passed;} + function renderHashes(envelope){const review=envelope.review,plan=review.plan||{};byId("review-hashes").innerHTML=`
Task
${escape(review.task_id)}
Evidence sequence
${escape(review.ready_sequence)}
Review
${escape(envelope.review_hash)}
Plan
${escape(plan.plan_hash)}
Base scope
${escape(plan.base_scope_manifest_hash)}
Candidate scope
${escape(plan.candidate_scope_manifest_hash)}
`;} + function renderReview(envelope,title){const review=envelope.review;state.review=envelope;byId("review-title").textContent=title||review.plan.goal||"Candidate review";byId("review-identity").textContent=`Task ${review.task_id} · evidence sequence ${review.ready_sequence}`;byId("review-state").textContent=envelope.verified?"Verified":"Unavailable";renderPlan(review);renderChanges(review);const checksPassed=renderChecks(review),live=envelope.eligibility||envelope.live||{},accepted=envelope.acceptance||live.acceptance||null,application=envelope.application||live.application||null,applied=applicationApplied(application);renderHashes(envelope);state.acceptance=accepted;state.application=application;byId("review-accept").disabled=!(envelope.verified&&checksPassed&&live.can_accept===true&&!accepted);byId("review-apply-section").hidden=!(accepted&&live.can_apply===true&&!applicationBlocksApply(application));byId("review-continue-section").hidden=!applied;if(live.reason||live.finding)setReviewAlert(remedyFor(live.reason||live.finding),"warning");else if(applied)setReviewAlert("This candidate was applied. The historical review remains available.","success");else if(application)setReviewAlert(applicationOutcomeMessage(application),"warning");else if(accepted)setReviewAlert("Candidate accepted. Your project is unchanged until you select Apply to project.","success");else if(live.can_accept!==true)setReviewAlert("This verified review is historical. Current acceptance eligibility is unavailable; reopen after the server finishes checking the project.","warning");else setReviewAlert("Verified candidate loaded.","success");} + async function loadCorrection(ticket){try{const body=await request(reviewPath(state.review.review.task_id,state.review.review.ready_sequence,"/correction"),{headers:{}});if(!reviewGate.accepts(ticket))return;state.correction=unwrap(body,"correction")||{revision:0,text:""};byId("review-correction").value=state.correction.text||"";byId("review-correction-status").textContent=state.correction.text?`Saved correction · revision ${state.correction.revision}`:"Correction draft is separate from project drafts.";}catch(_){if(reviewGate.accepts(ticket))byId("review-correction-status").textContent="Correction draft is unavailable.";}} + async function openReview(task,sequence,title){state.lastFocus=document.activeElement;const ticket=reviewGate.select(task,sequence);state.review=null;state.childPlan=null;state.acceptance=null;state.application=null;byId("task-compose-view").hidden=true;byId("task-review-view").hidden=false;byId("review-title").textContent=title||"Candidate review";byId("review-goal").textContent="Loading the selected candidate…";byId("review-identity").textContent=`Task ${task} · evidence sequence ${sequence}`;byId("review-state").textContent="Loading";byId("review-accept").disabled=true;byId("review-apply-section").hidden=true;byId("review-continue-section").hidden=true;byId("review-child-plan").hidden=true;byId("review-start-revision").hidden=true;setReviewAlert("Verifying the selected candidate…");byId("review-back").focus();try{const body=await request(reviewPath(task,sequence),{headers:{}});if(!reviewGate.accepts(ticket))return;const envelope=unwrap(body,"review");if(!envelope||envelope.schema!=="torq-task-review-v1")throw new Error("task_review_schema_invalid");renderReview(envelope,title);loadRecovery(envelope.review.plan.project_id);loadCorrection(ticket);}catch(error){if(reviewGate.accepts(ticket)){byId("review-state").textContent="Unavailable";setReviewAlert(remedyFor(error.message),"warning");}}} + function selectTab(name,focus=true){document.querySelectorAll("[data-review-tab]").forEach((tab)=>{const selected=tab.dataset.reviewTab===name;tab.setAttribute("aria-selected",String(selected));tab.tabIndex=selected?0:-1;byId(`review-panel-${tab.dataset.reviewTab}`).hidden=!selected;if(selected&&focus)tab.focus();});} + const tabs=Array.from(document.querySelectorAll("[data-review-tab]"));tabs.forEach((tab,index)=>{tab.addEventListener("click",()=>selectTab(tab.dataset.reviewTab,false));tab.addEventListener("keydown",(event)=>{let next;if(event.key==="ArrowRight")next=(index+1)%tabs.length;if(event.key==="ArrowLeft")next=(index-1+tabs.length)%tabs.length;if(event.key==="Home")next=0;if(event.key==="End")next=tabs.length-1;if(next!==undefined){event.preventDefault();selectTab(tabs[next].dataset.reviewTab);}});}); + byId("review-correction").addEventListener("input",()=>{state.childPlan=null;byId("review-child-plan").hidden=true;byId("review-start-revision").hidden=true;byId("review-correction-status").textContent="Correction has unsaved changes.";}); + async function saveCorrection(ticket){const text=byId("review-correction").value.trim();if(!text)throw new Error("Enter a correction before reviewing it.");const identity=state.review.review,expected=state.correction?state.correction.revision:0,body=await request(reviewPath(identity.task_id,identity.ready_sequence,"/correction"),{method:"POST",body:JSON.stringify({text,expected_revision:expected})});if(!reviewGate.accepts(ticket))return null;state.correction=unwrap(body,"correction");byId("review-correction-status").textContent=`Saved correction · revision ${state.correction.revision}`;return state.correction;} + byId("review-correction-plan").addEventListener("click",async()=>{if(!state.review)return;const ticket=reviewGate.capture(),control=byId("review-correction-plan");control.disabled=true;try{const correction=await enqueueMutation(()=>saveCorrection(ticket));if(!correction||!reviewGate.accepts(ticket))return;const identity=state.review.review,requestId=stableRequestId("correction-plan",`${identity.task_id}.${identity.ready_sequence}.${correction.content_hash}`,localStorage,globalThis.crypto),body=await enqueueMutation(()=>request(reviewPath(identity.task_id,identity.ready_sequence,"/child-plans"),{method:"POST",body:JSON.stringify({request_id:requestId,correction_revision:correction.revision,correction_hash:correction.content_hash,review_hash:state.review.review_hash})}));if(!reviewGate.accepts(ticket))return;const childEnvelope=unwrap(body,"plan");state.childPlan=childEnvelope.plan||childEnvelope;byId("review-child-plan").innerHTML=`Revision plan ready

${escape(state.childPlan.goal||"Build a corrected candidate from the same original base.")}

${escape((state.childPlan.output_paths||[]).length)} files in scope. Starting creates a new candidate; this one remains unchanged.

`;byId("review-child-plan").hidden=false;byId("review-start-revision").hidden=false;setReviewAlert("Correction plan reviewed. Start revision when ready.","success");}catch(error){if(reviewGate.accepts(ticket))setReviewAlert(remedyFor(error.message),"warning");}finally{if(reviewGate.accepts(ticket))control.disabled=false;}}); + byId("review-start-revision").addEventListener("click",async()=>{if(!state.review||!state.childPlan)return;const ticket=reviewGate.capture(),plan=state.childPlan,control=byId("review-start-revision");control.disabled=true;try{const requestId=stableRequestId("revision",plan.plan_hash||`${state.review.review_hash}.${state.correction.revision}`,localStorage,globalThis.crypto),body=await enqueueMutation(()=>request("/api/v1/task-revisions",{method:"POST",body:JSON.stringify({request_id:requestId,plan_hash:plan.plan_hash})}));if(!reviewGate.accepts(ticket))return;const task=unwrap(body,"task");showCompose(false);state.active=task.task_id;renderTask(task);pollTask();}catch(error){if(reviewGate.accepts(ticket)){control.disabled=false;setReviewAlert(remedyFor(error.message),"warning");}}}); + byId("review-accept").addEventListener("click",async()=>{if(!state.review)return;const ticket=reviewGate.capture(),envelope=state.review,control=byId("review-accept");control.disabled=true;try{const identity=envelope.review,requestId=stableRequestId("accept",envelope.review_hash,localStorage,globalThis.crypto),body=await enqueueMutation(()=>request("/api/v1/task-reviews/accept",{method:"POST",body:JSON.stringify({request_id:requestId,task_id:identity.task_id,ready_sequence:identity.ready_sequence,review_hash:envelope.review_hash})}));if(!reviewGate.accepts(ticket))return;state.acceptance=unwrap(body,"acceptance");byId("review-apply-section").hidden=false;setReviewAlert("Candidate accepted. Your project is unchanged until you select Apply to project.","success");}catch(error){if(reviewGate.accepts(ticket)){control.disabled=false;setReviewAlert(remedyFor(error.message),"warning");}}}); + byId("review-apply").addEventListener("click",async()=>{if(!state.review||!state.acceptance)return;const ticket=reviewGate.capture(),control=byId("review-apply"),priorApplication=state.application;control.disabled=true;try{const candidate=state.acceptance.candidate,acceptance=state.acceptance.acceptance||state.acceptance.decision,requestId=stableRequestId("apply",applicationRetryIdentity(candidate,acceptance,priorApplication),localStorage,globalThis.crypto),body=await enqueueMutation(()=>request("/api/v1/task-applications",{method:"POST",body:JSON.stringify({request_id:requestId,candidate,acceptance})}));if(!reviewGate.accepts(ticket))return;state.application=unwrap(body,"application");const applied=applicationApplied(state.application);byId("review-continue-section").hidden=!applied;byId("review-apply-section").hidden=true;setReviewAlert(applicationOutcomeMessage(state.application),applied?"success":"warning");if(["rejected","rolled_back"].includes(state.application.state)){const identity=state.review.review,title=byId("review-title").textContent,fresh=await request(reviewPath(identity.task_id,identity.ready_sequence),{headers:{}});if(reviewGate.accepts(ticket))renderReview(unwrap(fresh,"review"),title);}}catch(error){if(reviewGate.accepts(ticket)){control.disabled=false;setReviewAlert(remedyFor(error.message),"warning");}}}); + byId("review-continue").addEventListener("click",async()=>{if(!state.review||!state.application)return;const ticket=reviewGate.capture(),control=byId("review-continue"),applicationId=state.application.application_id;control.disabled=true;try{const requestId=stableRequestId("continue",applicationId,localStorage,globalThis.crypto),body=await enqueueMutation(()=>request("/api/v1/task-continuations",{method:"POST",body:JSON.stringify({request_id:requestId,application_id:applicationId})}));if(!reviewGate.accepts(ticket))return;const envelope=unwrap(body,"draft"),draft=envelope.draft||envelope;showCompose(false);if(draft&&draft.project_id===state.project){await loadDraft(state.project);byId("task-goal").focus();}setStatus("Continuation draft opened from the project’s current source.");}catch(error){forgetAfterDefiniteRejection(error,"continue",applicationId,localStorage);if(reviewGate.accepts(ticket)){control.disabled=false;setReviewAlert(remedyFor(error.message),"warning");}}}); + function bindHistoryRows(){byId("task-history-list").querySelectorAll("[data-task-id]").forEach((row)=>row.addEventListener("click",async()=>{if(row.dataset.readySequence!==undefined){openReview(row.dataset.taskId,Number(row.dataset.readySequence),row.querySelector("strong").textContent);return;}const result=await request(`/api/v1/tasks/${encodeURIComponent(row.dataset.taskId)}`,{headers:{}}),task=result.task;if(task.state==="candidate_ready"&&task.ready_sequence!=null){openReview(task.task_id,task.ready_sequence,task.goal_summary||task.goal);return;}state.active=task.task_id;renderTask(task);if(!terminal.includes(task.state))pollTask();else{state.active=null;await refreshTaskCapabilities();}}));} + async function loadHistory(query="",append=false){const normalized=String(query).trim();let ticket,cursor;if(append){ticket=historyGate.capture();cursor=state.historyCursor;if(!cursor)return;}else{ticket=historyGate.select(normalized);state.historyQuery=normalized;state.historyCursor=null;cursor=null;}const cursorPart=cursor?`&cursor=${encodeURIComponent(cursor)}`:"";let body;try{body=await request(`/api/v1/task-history?q=${encodeURIComponent(normalized)}&limit=50${cursorPart}`,{headers:{}});}catch(error){if(!historyGate.accepts(ticket)||state.historyQuery!==normalized)return;if(error.status!==404||append)throw error;body=await request("/api/v1/tasks",{headers:{}});}if(!historyGate.accepts(ticket)||state.historyQuery!==normalized)return;const items=body.items||body.tasks||[],markup=items.map((task)=>``).join("");const list=byId("task-history-list");list.innerHTML=append?list.innerHTML+markup:(markup||"No matching candidate history.");state.historyCursor=body.next_cursor||null;byId("task-history-more").hidden=!state.historyCursor;bindHistoryRows();} + byId("task-history-search").addEventListener("submit",(event)=>{event.preventDefault();loadHistory(byId("task-history-query").value,false).catch(()=>setStatus("History search is unavailable. Try again."));}); + byId("task-history-more").addEventListener("click",()=>{const control=byId("task-history-more");control.disabled=true;loadHistory(state.historyQuery,true).catch(()=>setStatus("More history is unavailable. Try again.")).finally(()=>{control.disabled=false;});}); + request("/api/v1/tasks/capabilities",{headers:{}}).then((caps)=>{state.capabilities=caps;button.hidden=false;if(new URLSearchParams(location.search).get("view")==="task")setView();}).catch(()=>{button.hidden=true;}); })(); diff --git a/src/torq_cli/domain/candidate_decision_evidence.py b/src/torq_cli/domain/candidate_decision_evidence.py new file mode 100644 index 0000000..148afc3 --- /dev/null +++ b/src/torq_cli/domain/candidate_decision_evidence.py @@ -0,0 +1,432 @@ +"""Closed review and application audit contracts for candidate decisions.""" + +from __future__ import annotations + +import re +import hashlib +import json +from collections.abc import Mapping, Sequence +from typing import Any + +REVIEW_CONTRACT = "torq-candidate-review-v1" +APPLY_CONTRACT = "torq-candidate-apply-v1" +_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") +_CODE = re.compile(r"[a-z][a-z0-9_]{0,63}") +_HASH = re.compile(r"sha256:[a-f0-9]{64}") +_ARTIFACT = re.compile(r"[A-Za-z0-9][A-Za-z0-9/._-]{0,255}") + +CANDIDATE_KEYS = { + "task_id", "ready_sequence", "ready_receipt_hash", "terminal_manifest_hash", + "plan_hash", "base_scope_manifest_hash", "input_hash", "candidate_scope_manifest_hash", + "check_sequence", "check_receipt_hash", "review_hash", +} +DECISION_KEYS = {"decision_id", "decision_sequence", "decision_receipt_hash", "terminal_manifest_hash"} +ACTOR_KEYS = {"subject_id", "assurance"} +COMMON_REVIEW = {"review_contract", "event", "decision_id", "request_digest", "candidate", "actor", "detail"} +COMMON_APPLY = {"apply_contract", "event", "application_id", "request_digest", "candidate", "acceptance", "actor", "detail"} + + +def _identifier(value: object) -> bool: + return isinstance(value, str) and _ID.fullmatch(value) is not None + + +def _digest(value: object) -> bool: + return isinstance(value, str) and _HASH.fullmatch(value) is not None + + +def _positive(value: object) -> bool: + return isinstance(value, int) and not isinstance(value, bool) and value > 0 + + +def _artifact(value: object) -> bool: + return isinstance(value, str) and _ARTIFACT.fullmatch(value) is not None and ".." not in value.split("/") + + +def validate_candidate_ref(value: object) -> bool: + return ( + isinstance(value, Mapping) + and set(value) == CANDIDATE_KEYS + and _identifier(value.get("task_id")) + and _positive(value.get("ready_sequence")) + and _positive(value.get("check_sequence")) + and all(_digest(value.get(key)) for key in CANDIDATE_KEYS - {"task_id", "ready_sequence", "check_sequence"}) + ) + + +def _receipt_hash(row: Mapping[str, Any]) -> str: + existing = row.get("receipt_hash") + if isinstance(existing, str): + return existing + raw = json.dumps(row, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8") + return "sha256:" + hashlib.sha256(raw).hexdigest() + + +def validate_decision_ref(value: object) -> bool: + return ( + isinstance(value, Mapping) + and set(value) == DECISION_KEYS + and _identifier(value.get("decision_id")) + and _positive(value.get("decision_sequence")) + and _digest(value.get("decision_receipt_hash")) + and _digest(value.get("terminal_manifest_hash")) + ) + + +def _actor(value: object) -> bool: + return ( + isinstance(value, Mapping) + and set(value) == ACTOR_KEYS + and _identifier(value.get("subject_id")) + and value.get("assurance") == "local_operator_session" + ) + + +def _artifact_ref(value: object) -> bool: + return ( + isinstance(value, Mapping) + and set(value) == {"artifact", "artifact_hash", "content_hash"} + and _artifact(value.get("artifact")) + and _digest(value.get("artifact_hash")) + and _digest(value.get("content_hash")) + ) + + +def validate_review_payload(payload: Mapping[str, Any]) -> str | None: + if payload.get("review_contract") != REVIEW_CONTRACT: + return None + if set(payload) != COMMON_REVIEW or not _identifier(payload.get("decision_id")): + return "candidate_review_payload_invalid" + if not _digest(payload.get("request_digest")) or not validate_candidate_ref(payload.get("candidate")) or not _actor(payload.get("actor")): + return "candidate_review_identity_invalid" + detail = payload.get("detail") + if not isinstance(detail, Mapping): + return "candidate_review_detail_invalid" + event = payload.get("event") + if event == "candidate_accepted": + if set(detail) != {"review_artifact", "source_scope_hash"} or not _artifact_ref(detail.get("review_artifact")) or not _digest(detail.get("source_scope_hash")): + return "candidate_accept_detail_invalid" + elif event == "correction_requested": + if ( + set(detail) != {"correction_revision", "correction_hash", "child_plan_hash"} + or not _positive(detail.get("correction_revision")) + or not _digest(detail.get("correction_hash")) + or not _digest(detail.get("child_plan_hash")) + ): + return "candidate_correction_detail_invalid" + else: + return "candidate_review_event_invalid" + return None + + +_APPLY_DETAILS = { + "apply_authority_created": {"installation_id"}, + "apply_rejected": {"reason_code"}, + "apply_prepared": {"journal_artifact", "journal_hash", "primary_identity_hash", "operation_count"}, + "apply_started": {"prepared_sequence", "prepared_receipt_hash"}, + "apply_file_staged": {"started_sequence", "operation_index", "path", "result_hash", "staged_identity"}, + "apply_file_written": {"started_sequence", "staged_sequence", "staged_receipt_hash", "operation_index", "path", "result_hash"}, + "apply_rollback_started": {"caused_by_sequence", "reason_code"}, + "apply_rollback_file_staged": { + "rollback_started_sequence", "operation_index", "path", "base_hash", + "staged_identity", + }, + "apply_rollback_file_restored": { + "rollback_started_sequence", "operation_index", "path", "base_hash", + "staged_sequence", "staged_receipt_hash", + }, + "apply_recovery_required": {"caused_by_sequence", "reason_code"}, + "candidate_applied": {"started_sequence", "journal_hash", "result_scope_manifest_hash", "operation_count"}, + "apply_rolled_back": {"prepared_sequence", "journal_hash", "restored_scope_manifest_hash"}, +} + + +def validate_apply_payload(payload: Mapping[str, Any]) -> str | None: + if payload.get("apply_contract") != APPLY_CONTRACT: + return None + if set(payload) != COMMON_APPLY or not _identifier(payload.get("application_id")): + return "candidate_apply_payload_invalid" + if ( + not _digest(payload.get("request_digest")) + or not validate_candidate_ref(payload.get("candidate")) + or not validate_decision_ref(payload.get("acceptance")) + or not _actor(payload.get("actor")) + ): + return "candidate_apply_identity_invalid" + event = payload.get("event") + detail = payload.get("detail") + if not isinstance(event, str) or event not in _APPLY_DETAILS or not isinstance(detail, Mapping) or set(detail) != _APPLY_DETAILS[event]: + return "candidate_apply_detail_invalid" + if event == "apply_authority_created" and not _identifier(detail.get("installation_id")): + return "candidate_apply_detail_invalid" + if event in {"apply_rejected", "apply_rollback_started", "apply_recovery_required"} and not ( + isinstance(detail.get("reason_code"), str) and _CODE.fullmatch(str(detail["reason_code"])) + ): + return "candidate_apply_detail_invalid" + if event == "apply_prepared" and not ( + _artifact_ref(detail.get("journal_artifact")) + and _digest(detail.get("journal_hash")) + and _digest(detail.get("primary_identity_hash")) + and _positive(detail.get("operation_count")) + ): + return "candidate_apply_detail_invalid" + for key in ("prepared_sequence", "started_sequence", "caused_by_sequence"): + if key in detail and not _positive(detail.get(key)): + return "candidate_apply_detail_invalid" + if "prepared_receipt_hash" in detail and not _digest(detail.get("prepared_receipt_hash")): + return "candidate_apply_detail_invalid" + if "journal_hash" in detail and not _digest(detail.get("journal_hash")): + return "candidate_apply_detail_invalid" + if "result_scope_manifest_hash" in detail and not _digest(detail.get("result_scope_manifest_hash")): + return "candidate_apply_detail_invalid" + if "restored_scope_manifest_hash" in detail and not _digest(detail.get("restored_scope_manifest_hash")): + return "candidate_apply_detail_invalid" + if event in { + "apply_file_staged", "apply_file_written", "apply_rollback_file_staged", + "apply_rollback_file_restored", + } and not ( + isinstance(detail.get("operation_index"), int) + and not isinstance(detail.get("operation_index"), bool) + and detail["operation_index"] >= 0 + and isinstance(detail.get("path"), str) + ): + return "candidate_apply_detail_invalid" + if event in {"apply_file_staged", "apply_file_written"} and not _digest( + detail.get("result_hash") + ): + return "candidate_apply_detail_invalid" + if event in {"apply_rollback_file_staged", "apply_rollback_file_restored"} and not ( + _positive(detail.get("rollback_started_sequence")) + and (detail.get("base_hash") is None or _digest(detail.get("base_hash"))) + ): + return "candidate_apply_detail_invalid" + for identity_key in ("staged_identity",): + if identity_key in detail: + identity = detail.get(identity_key) + if ( + not isinstance(identity, Mapping) + or set(identity) != {"volume", "file_id"} + or not all(isinstance(identity.get(key), int) and not isinstance(identity.get(key), bool) and identity[key] >= 0 for key in ("volume", "file_id")) + ): + return "candidate_apply_detail_invalid" + if event in {"apply_file_written", "apply_rollback_file_restored"} and not ( + _positive(detail.get("staged_sequence")) and _digest(detail.get("staged_receipt_hash")) + ): + return "candidate_apply_detail_invalid" + if "operation_count" in detail and not _positive(detail.get("operation_count")): + return "candidate_apply_detail_invalid" + return None + + +def validate_decision_receipt_contract(receipts: Sequence[Mapping[str, Any]], *, sealed: bool) -> str | None: + review: list[tuple[int, Mapping[str, Any]]] = [] + apply: list[tuple[int, Mapping[str, Any]]] = [] + for row in receipts: + payload = row.get("payload") + sequence = row.get("sequence") + if not isinstance(payload, Mapping): + continue + if payload.get("review_contract") == REVIEW_CONTRACT: + if row.get("transition") != "audit" or not _positive(sequence): + return "candidate_review_receipt_invalid" + finding = validate_review_payload(payload) + if finding: + return finding + assert isinstance(sequence, int) and not isinstance(sequence, bool) + review.append((int(sequence), payload)) + if payload.get("apply_contract") == APPLY_CONTRACT: + if row.get("transition") != "audit" or not _positive(sequence): + return "candidate_apply_receipt_invalid" + finding = validate_apply_payload(payload) + if finding: + return finding + assert isinstance(sequence, int) and not isinstance(sequence, bool) + apply.append((int(sequence), payload)) + if review: + if len(review) != 1: + return "candidate_review_lifecycle_invalid" + payload = review[0][1] + if row_run_id(receipts, review[0][0]) != payload.get("decision_id"): + return "candidate_review_run_id_mismatch" + if apply: + common = {key: apply[0][1][key] for key in COMMON_APPLY - {"event", "detail"}} + if any({key: payload[key] for key in common} != common for _, payload in apply): + return "candidate_apply_context_changed" + events = [str(payload["event"]) for _, payload in apply] + if events[0] != "apply_authority_created" or events.count("apply_authority_created") != 1: + return "candidate_apply_begin_invalid" + terminal = {"apply_rejected", "candidate_applied", "apply_rolled_back"} + if any(event in terminal for event in events[:-1]): + return "candidate_apply_after_terminal" + if sealed and events[-1] not in terminal: + return "candidate_apply_terminal_invalid" + if row_run_id(receipts, apply[0][0]) != apply[0][1].get("application_id"): + return "candidate_apply_run_id_mismatch" + if any(row_run_id(receipts, sequence) != apply[0][1].get("application_id") for sequence, _ in apply): + return "candidate_apply_run_id_mismatch" + if events == ["apply_authority_created"]: + return "candidate_apply_terminal_invalid" if sealed else None + if events[1] == "apply_rejected": + return None if len(events) == 2 else "candidate_apply_after_terminal" + if events[1] != "apply_prepared" or events.count("apply_prepared") != 1: + return "candidate_apply_prepared_order_invalid" + prepared_sequence, prepared = apply[1] + prepared_hash = next( + (_receipt_hash(row) for row in receipts if row.get("sequence") == prepared_sequence), + None, + ) + operation_count = prepared["detail"]["operation_count"] + journal_hash = prepared["detail"]["journal_hash"] + started_rows = [(sequence, body) for sequence, body in apply if body["event"] == "apply_started"] + if events[-1] == "apply_rejected": + return None if len(events) == 3 else "candidate_apply_after_terminal" + if len(started_rows) > 1: + return "candidate_apply_started_order_invalid" + started_sequence: int | None = None + if started_rows: + started_sequence, started_body = started_rows[0] + if ( + events.index("apply_started") != 2 + or started_body["detail"].get("prepared_sequence") != prepared_sequence + or started_body["detail"].get("prepared_receipt_hash") != prepared_hash + ): + return "candidate_apply_started_order_invalid" + staged_rows = [(sequence, body) for sequence, body in apply if body["event"] == "apply_file_staged"] + written_rows = [(sequence, body) for sequence, body in apply if body["event"] == "apply_file_written"] + if ( + [body["detail"]["operation_index"] for _, body in staged_rows] + != list(range(len(staged_rows))) + or len(staged_rows) > operation_count + or staged_rows and started_sequence is None + or started_sequence is not None + and any(body["detail"].get("started_sequence") != started_sequence for _, body in staged_rows) + or len({body["detail"].get("path") for _, body in staged_rows}) != len(staged_rows) + ): + return "candidate_apply_progress_order_invalid" + if written_rows: + if started_sequence is None: + return "candidate_apply_progress_order_invalid" + if [body["detail"]["operation_index"] for _, body in written_rows] != list(range(len(written_rows))): + return "candidate_apply_progress_order_invalid" + if any(body["detail"].get("started_sequence") != started_sequence for _, body in written_rows): + return "candidate_apply_progress_order_invalid" + paths = [body["detail"].get("path") for _, body in written_rows] + if len(paths) != len(set(paths)) or len(written_rows) > operation_count: + return "candidate_apply_progress_order_invalid" + staged_by_index = {body["detail"]["operation_index"]: (sequence, body) for sequence, body in staged_rows} + for _, body in written_rows: + staged = staged_by_index.get(body["detail"]["operation_index"]) + if ( + staged is None + or body["detail"].get("staged_sequence") != staged[0] + or body["detail"].get("staged_receipt_hash") + != next((_receipt_hash(row) for row in receipts if row.get("sequence") == staged[0]), None) + or body["detail"].get("result_hash") != staged[1]["detail"].get("result_hash") + ): + return "candidate_apply_progress_link_invalid" + rollback_rows = [(sequence, body) for sequence, body in apply if body["event"] == "apply_rollback_started"] + rollback_staged: list[tuple[int, Mapping[str, Any]]] = [] + rollback_restored: list[tuple[int, Mapping[str, Any]]] = [] + if len(rollback_rows) > 1: + return "candidate_apply_rollback_order_invalid" + if rollback_rows: + rollback_index = events.index("apply_rollback_started") + if rollback_rows[0][1]["detail"].get("caused_by_sequence") != apply[rollback_index - 1][0]: + return "candidate_apply_rollback_order_invalid" + allowed_rollback_tail = { + "apply_rollback_file_staged", "apply_rollback_file_restored", + "apply_recovery_required", "apply_rolled_back", + } + if any(event not in allowed_rollback_tail for event in events[rollback_index + 1 :]): + return "candidate_apply_rollback_order_invalid" + rollback_started_sequence = rollback_rows[0][0] + rollback_staged = [ + (sequence, body) for sequence, body in apply + if body["event"] == "apply_rollback_file_staged" + ] + rollback_restored = [ + (sequence, body) for sequence, body in apply + if body["event"] == "apply_rollback_file_restored" + ] + indices = [body["detail"]["operation_index"] for _, body in rollback_staged] + if ( + len(indices) != len(set(indices)) + or any( + body["detail"].get("rollback_started_sequence") + != rollback_started_sequence + for _, body in rollback_staged + rollback_restored + ) + or indices != sorted(indices, reverse=True) + ): + return "candidate_apply_rollback_progress_invalid" + staged_by_index = { + body["detail"]["operation_index"]: (sequence, body) + for sequence, body in rollback_staged + } + restored_indices: list[int] = [] + for _, body in rollback_restored: + detail = body["detail"] + index = detail["operation_index"] + staged = staged_by_index.get(index) + if ( + staged is None + or index in restored_indices + or detail.get("staged_sequence") != staged[0] + or detail.get("staged_receipt_hash") + != next( + (_receipt_hash(row) for row in receipts if row.get("sequence") == staged[0]), + None, + ) + or detail.get("path") != staged[1]["detail"].get("path") + or detail.get("base_hash") != staged[1]["detail"].get("base_hash") + ): + return "candidate_apply_rollback_progress_invalid" + restored_indices.append(index) + if restored_indices != indices[: len(restored_indices)]: + return "candidate_apply_rollback_progress_invalid" + for index, (sequence, body) in enumerate(apply): + del sequence + if body["event"] == "apply_recovery_required" and ( + index == 0 or body["detail"].get("caused_by_sequence") != apply[index - 1][0] + ): + return "candidate_apply_recovery_link_invalid" + if events[-1] == "candidate_applied": + detail = apply[-1][1]["detail"] + if ( + started_sequence is None + or detail.get("started_sequence") != started_sequence + or detail.get("journal_hash") != journal_hash + or detail.get("operation_count") != operation_count + or len(written_rows) != operation_count + or detail.get("result_scope_manifest_hash") + != apply[0][1]["candidate"].get("candidate_scope_manifest_hash") + ): + return "candidate_apply_terminal_link_invalid" + elif events[-1] == "apply_rolled_back": + detail = apply[-1][1]["detail"] + if ( + not rollback_rows + or detail.get("prepared_sequence") != prepared_sequence + or detail.get("journal_hash") != journal_hash + or len(rollback_restored) != len(rollback_staged) + or detail.get("restored_scope_manifest_hash") + != apply[0][1]["candidate"].get("base_scope_manifest_hash") + ): + return "candidate_apply_terminal_link_invalid" + elif events[-1] not in { + "apply_recovery_required", "apply_prepared", "apply_started", "apply_file_staged", + "apply_file_written", "apply_rollback_started", "apply_rollback_file_staged", + "apply_rollback_file_restored", + }: + return "candidate_apply_lifecycle_invalid" + return None + + +def row_run_id(receipts: Sequence[Mapping[str, Any]], sequence: int) -> object: + return next((row.get("run_id") for row in receipts if row.get("sequence") == sequence), None) + + +__all__ = [ + "APPLY_CONTRACT", "CANDIDATE_KEYS", "DECISION_KEYS", "REVIEW_CONTRACT", + "validate_apply_payload", "validate_candidate_ref", "validate_decision_receipt_contract", + "validate_decision_ref", "validate_review_payload", +] diff --git a/src/torq_cli/domain/run_evidence.py b/src/torq_cli/domain/run_evidence.py index 6953402..59e7625 100644 --- a/src/torq_cli/domain/run_evidence.py +++ b/src/torq_cli/domain/run_evidence.py @@ -7,6 +7,11 @@ from typing import Any from torq_cli.domain.evidence_transitions import transition_authority_finding +from torq_cli.domain.candidate_decision_evidence import ( + validate_apply_payload, + validate_decision_receipt_contract, + validate_review_payload, +) from torq_cli.domain.run_plan import ( PLAN_CONTRACT, initial_plan_body, @@ -403,6 +408,12 @@ def validate_receipt_payload( task_finding = validate_task_audit_payload(payload) if task_finding is not None: return task_finding + review_finding = validate_review_payload(payload) + if review_finding is not None: + return review_finding + apply_finding = validate_apply_payload(payload) + if apply_finding is not None: + return apply_finding if transition in ATTEMPT_TRANSITIONS: if not isinstance(payload.get("role"), str): return "attempt_role_invalid" @@ -810,6 +821,9 @@ def validate_v2_receipt_contract( task_finding = validate_task_receipt_contract(receipts, sealed=sealed) if task_finding is not None: return task_finding + decision_finding = validate_decision_receipt_contract(receipts, sealed=sealed) + if decision_finding is not None: + return decision_finding attempts: dict[str, dict[str, Any]] = {} ordinals: dict[str, int] = {} repairs: dict[str, tuple[str, int, int]] = {} diff --git a/src/torq_cli/domain/task_review.py b/src/torq_cli/domain/task_review.py new file mode 100644 index 0000000..19c8684 --- /dev/null +++ b/src/torq_cli/domain/task_review.py @@ -0,0 +1,667 @@ +"""Historical, artifact-backed projection of one exact candidate result.""" + +from __future__ import annotations + +import difflib +import json +import re +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from torq_cli.adapters.candidate_provider import parse_candidate_output +from torq_cli.domain.candidate_decision_evidence import ( + REVIEW_CONTRACT, + validate_candidate_ref, + validate_decision_ref, +) +from torq_cli.domain.task_evidence import TASK_CONTRACT +from torq_cli.safety.receipts import ReceiptChain, read_verified_artifact, verify_receipt_store +from torq_cli.safety.task_workspace import ( + MAX_TASK_FILES, + MAX_TASK_FILE_BYTES, + MAX_TASK_TOTAL_BYTES, + canonical_json, + digest_bytes, + digest_json, + validate_relative_path, +) + +REVIEW_SCHEMA = "torq-task-review-v1" +_MAX_DIFF_CHARS = 262_144 +_TASK_ID = re.compile(r"run-task-[a-f0-9]{24}") + + +def _strict_json(raw: bytes, finding: str) -> Any: + def unique(pairs: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + raise ValueError(finding) + result[key] = value + return result + + def reject_constant(_value: str) -> object: + raise ValueError(finding) + + try: + return json.loads(raw, object_pairs_hook=unique, parse_constant=reject_constant) + except (UnicodeDecodeError, json.JSONDecodeError, TypeError) as exc: + raise ValueError(finding) from exc + + +def _source_bundle(value: object) -> dict[str, bytes]: + if not isinstance(value, list) or len(value) > MAX_TASK_FILES: + raise ValueError("task_review_input_invalid") + result: dict[str, bytes] = {} + total = 0 + for row in value: + if not isinstance(row, Mapping) or set(row) != { + "path", "content", "content_bytes", "content_hash" + }: + raise ValueError("task_review_input_invalid") + path = row.get("path") + content = row.get("content") + size = row.get("content_bytes") + content_hash = row.get("content_hash") + if not isinstance(path, str) or not isinstance(content, str): + raise ValueError("task_review_input_invalid") + path = validate_relative_path(path) + raw = content.encode("utf-8") + if ( + not isinstance(size, int) + or isinstance(size, bool) + or size != len(raw) + or size > MAX_TASK_FILE_BYTES + or content_hash != digest_bytes(raw) + or path.casefold() in {existing.casefold() for existing in result} + ): + raise ValueError("task_review_input_invalid") + total += size + if total > MAX_TASK_TOTAL_BYTES: + raise ValueError("task_review_input_invalid") + result[path] = raw + return result + + +def _manifest(files: Mapping[str, bytes]) -> str: + return digest_json( + [ + {"path": path, "content_bytes": len(content), "content_hash": digest_bytes(content)} + for path, content in sorted(files.items(), key=lambda item: item[0].casefold()) + ] + ) + + +def _newline(value: bytes) -> dict[str, object]: + crlf = value.count(b"\r\n") + without_crlf = value.replace(b"\r\n", b"") + lf = without_crlf.count(b"\n") + cr = without_crlf.count(b"\r") + kinds = sum(count > 0 for count in (crlf, lf, cr)) + return { + "style": "none" if kinds == 0 else "mixed" if kinds > 1 else "crlf" if crlf else "lf" if lf else "cr", + "crlf_count": crlf, + "lf_count": lf, + "cr_count": cr, + "final_newline": value.endswith((b"\n", b"\r")), + "bytes": len(value), + } + + +def _display_lines(value: bytes) -> list[str]: + text = value.decode("utf-8") + result: list[str] = [] + for line in text.splitlines(keepends=True): + if line.endswith("\r\n"): + result.append(line[:-2] + " [CRLF]") + elif line.endswith("\n"): + result.append(line[:-1] + " [LF]") + elif line.endswith("\r"): + result.append(line[:-1] + " [CR]") + else: + result.append(line + " [NO EOL]") + return result + + +def _change(path: str, before: bytes | None, after: bytes, operation: str) -> dict[str, object]: + before_text = "" if before is None else before.decode("utf-8") + after_text = after.decode("utf-8") + lines = difflib.unified_diff( + [] if before is None else _display_lines(before), + _display_lines(after), + fromfile=f"a/{path}", + tofile=f"b/{path}", + lineterm="\n", + ) + rendered = "".join(line if line.endswith("\n") else line + "\n" for line in lines) + complete = len(rendered) <= _MAX_DIFF_CHARS + return { + "operation": operation, + "path": path, + "base_hash": None if before is None else digest_bytes(before), + "result_hash": digest_bytes(after), + "base_text": None if before is None else before_text, + "result_text": after_text, + "base_newlines": None if before is None else _newline(before), + "result_newlines": _newline(after), + "diff": rendered[:_MAX_DIFF_CHARS], + "diff_complete": complete, + } + + +def _lineage_change(path: str, before: bytes | None, after: bytes | None) -> dict[str, object]: + if after is None: + assert before is not None + return { + "operation": "dropped_parent_create", + "path": path, + "parent_hash": digest_bytes(before), + "result_hash": None, + "summary": "The revision drops this parent-created file and restores original absence.", + } + operation = "added_in_revision" if before is None else "changed_from_parent" + change = _change(path, before, after, operation) + return { + "operation": operation, + "path": path, + "parent_hash": None if before is None else digest_bytes(before), + "result_hash": digest_bytes(after), + "diff": change["diff"], + "diff_complete": change["diff_complete"], + } + + +def _verify_correction_decision( + review_evidence_root: Path, + value: object, + parent: "ResolvedTaskReview", + child_plan_hash: str, + correction_revision: int, + correction_hash: str, +) -> None: + if not validate_decision_ref(value): + raise ValueError("task_review_correction_decision_invalid") + assert isinstance(value, Mapping) + decision_id = str(value["decision_id"]) + root = (review_evidence_root.absolute() / decision_id).absolute() + if root.parent != review_evidence_root.absolute() or verify_receipt_store(root).status != "verified": + raise ValueError("task_review_correction_decision_unverified") + manifest_raw = (root / "terminal-manifest.json").read_bytes() + rows = [ + _strict_json(line.encode("utf-8"), "task_review_correction_decision_invalid") + for line in (root / "receipts.jsonl").read_text(encoding="utf-8").splitlines() + ] + if len(rows) != 1 or not isinstance(rows[0], Mapping): + raise ValueError("task_review_correction_decision_invalid") + row = rows[0] + payload = row.get("payload") + expected = { + "decision_id": decision_id, + "decision_sequence": row.get("sequence"), + "decision_receipt_hash": row.get("receipt_hash"), + "terminal_manifest_hash": digest_bytes(manifest_raw), + } + if ( + dict(value) != expected + or not isinstance(payload, Mapping) + or payload.get("review_contract") != REVIEW_CONTRACT + or payload.get("event") != "correction_requested" + or payload.get("decision_id") != decision_id + or payload.get("candidate") != parent.candidate_ref + or payload.get("detail") + != { + "correction_revision": correction_revision, + "correction_hash": correction_hash, + "child_plan_hash": child_plan_hash, + } + ): + raise ValueError("task_review_correction_decision_mismatch") + + +def _verify_application_ref( + apply_evidence_root: Path, + review_evidence_root: Path, + value: object, + parent: "ResolvedTaskReview", +) -> None: + if not validate_decision_ref(value): + raise ValueError("task_review_continuation_application_invalid") + assert isinstance(value, Mapping) + application_id = str(value["decision_id"]) + root = (apply_evidence_root.absolute() / application_id).absolute() + if root.parent != apply_evidence_root.absolute() or verify_receipt_store(root).status != "verified": + raise ValueError("task_review_continuation_application_unverified") + manifest_raw = (root / "terminal-manifest.json").read_bytes() + rows = [ + _strict_json(line.encode("utf-8"), "task_review_continuation_application_invalid") + for line in (root / "receipts.jsonl").read_text(encoding="utf-8").splitlines() + ] + if not rows or not isinstance(rows[-1], Mapping): + raise ValueError("task_review_continuation_application_invalid") + row = rows[-1] + payload = row.get("payload") + expected = { + "decision_id": application_id, + "decision_sequence": row.get("sequence"), + "decision_receipt_hash": row.get("receipt_hash"), + "terminal_manifest_hash": digest_bytes(manifest_raw), + } + if ( + dict(value) != expected + or not isinstance(payload, Mapping) + or payload.get("event") != "candidate_applied" + or payload.get("application_id") != application_id + or payload.get("candidate") != parent.candidate_ref + ): + raise ValueError("task_review_continuation_application_mismatch") + _verify_acceptance_ref(review_evidence_root, payload.get("acceptance"), parent) + + +def _verify_acceptance_ref( + review_evidence_root: Path, + value: object, + parent: "ResolvedTaskReview", +) -> None: + if not validate_decision_ref(value): + raise ValueError("task_review_continuation_acceptance_invalid") + assert isinstance(value, Mapping) + decision_id = str(value["decision_id"]) + root = (review_evidence_root.absolute() / decision_id).absolute() + if root.parent != review_evidence_root.absolute() or verify_receipt_store(root).status != "verified": + raise ValueError("task_review_continuation_acceptance_unverified") + manifest_raw = (root / "terminal-manifest.json").read_bytes() + rows = [ + _strict_json(line.encode("utf-8"), "task_review_continuation_acceptance_invalid") + for line in (root / "receipts.jsonl").read_text(encoding="utf-8").splitlines() + ] + if len(rows) != 1 or not isinstance(rows[0], Mapping): + raise ValueError("task_review_continuation_acceptance_invalid") + row = rows[0] + payload = row.get("payload") + expected = { + "decision_id": decision_id, + "decision_sequence": row.get("sequence"), + "decision_receipt_hash": row.get("receipt_hash"), + "terminal_manifest_hash": digest_bytes(manifest_raw), + } + if ( + dict(value) != expected + or not isinstance(payload, Mapping) + or payload.get("review_contract") != REVIEW_CONTRACT + or payload.get("event") != "candidate_accepted" + or payload.get("decision_id") != decision_id + or payload.get("candidate") != parent.candidate_ref + ): + raise ValueError("task_review_continuation_acceptance_mismatch") + detail = payload.get("detail") + if ( + not isinstance(detail, Mapping) + or detail.get("source_scope_hash") != parent.candidate_ref["base_scope_manifest_hash"] + or not isinstance(detail.get("review_artifact"), Mapping) + ): + raise ValueError("task_review_continuation_acceptance_mismatch") + artifact = detail["review_artifact"] + assert isinstance(artifact, Mapping) + relative = artifact.get("artifact") + if not isinstance(relative, str): + raise ValueError("task_review_continuation_acceptance_artifact_invalid") + plain = read_verified_artifact(review_evidence_root, decision_id, relative) + if ( + ReceiptChain.hash_file(root / relative) != artifact.get("artifact_hash") + or digest_bytes(plain) != artifact.get("content_hash") + or digest_json(_strict_json(plain, "task_review_continuation_acceptance_artifact_invalid")) + != parent.candidate_ref["review_hash"] + ): + raise ValueError("task_review_continuation_acceptance_artifact_mismatch") + + +@dataclass(frozen=True, slots=True) +class ResolvedTaskReview: + envelope: dict[str, Any] + candidate_ref: dict[str, Any] + plan: dict[str, Any] + base_files: dict[str, bytes] + result_files: dict[str, bytes] + changed_paths: tuple[str, ...] + + +def resolve_task_review( + evidence_root: Path, + task_id: str, + ready_sequence: int, +) -> ResolvedTaskReview: + """Resolve one sealed task by exact sequence without consulting live source/cache.""" + + if ( + _TASK_ID.fullmatch(task_id) is None + or not isinstance(ready_sequence, int) + or isinstance(ready_sequence, bool) + or ready_sequence <= 0 + ): + raise ValueError("task_review_sequence_invalid") + root = (evidence_root.absolute() / task_id).absolute() + if root.parent != evidence_root.absolute(): + raise ValueError("task_review_task_id_invalid") + verification = verify_receipt_store(root) + if verification.status != "verified": + raise ValueError("task_review_store_unverified") + manifest_raw = (root / "terminal-manifest.json").read_bytes() + manifest = _strict_json(manifest_raw, "task_review_manifest_invalid") + if not isinstance(manifest, Mapping) or manifest.get("sealed") is not True: + raise ValueError("task_review_store_unsealed") + receipt_rows = [ + _strict_json(line.encode("utf-8"), "task_review_receipt_invalid") + for line in (root / "receipts.jsonl").read_text(encoding="utf-8").splitlines() + ] + rows = [row for row in receipt_rows if isinstance(row, Mapping)] + by_event: dict[str, Mapping[str, Any]] = {} + row_by_event: dict[str, Mapping[str, Any]] = {} + for row in rows: + payload = row.get("payload") + if isinstance(payload, Mapping) and payload.get("task_contract") == TASK_CONTRACT: + event = payload.get("event") + if isinstance(event, str): + by_event[event] = payload + row_by_event[event] = row + required = {"task_start_accepted", "candidate_generated", "candidate_check_completed", "candidate_ready"} + if not required.issubset(by_event): + raise ValueError("task_review_receipts_missing") + start = by_event["task_start_accepted"] + generated = by_event["candidate_generated"] + checked = by_event["candidate_check_completed"] + ready = by_event["candidate_ready"] + ready_row = row_by_event["candidate_ready"] + check_row = row_by_event["candidate_check_completed"] + if ready_row.get("sequence") != ready_sequence or ready.get("task_id") != task_id: + raise ValueError("task_review_sequence_mismatch") + + input_raw = read_verified_artifact(evidence_root, task_id, str(start["artifact"])) + candidate_raw = read_verified_artifact(evidence_root, task_id, str(generated["artifact"])) + check_raw = read_verified_artifact(evidence_root, task_id, str(checked["artifact"])) + for body, raw in ((start, input_raw), (generated, candidate_raw), (checked, check_raw)): + artifact_path = root / str(body["artifact"]) + if ( + ReceiptChain.hash_file(artifact_path) != body.get("artifact_hash") + or digest_bytes(raw) != body.get("artifact_content_hash") + ): + raise ValueError("task_review_artifact_hash_mismatch") + if digest_bytes(input_raw) != start.get("input_hash") or digest_bytes(check_raw) != checked.get("output_hash"): + raise ValueError("task_review_artifact_identity_mismatch") + + accepted = _strict_json(input_raw, "task_review_input_invalid") + bundle = _strict_json(candidate_raw, "task_review_candidate_invalid") + check = _strict_json(check_raw, "task_review_check_invalid") + if not isinstance(accepted, Mapping) or not isinstance(accepted.get("plan"), Mapping): + raise ValueError("task_review_input_invalid") + input_contract = accepted.get("contract") + if input_contract == "torq-candidate-input-v1": + if set(accepted) != {"contract", "plan", "files"}: + raise ValueError("task_review_input_invalid") + elif input_contract == "torq-candidate-input-v2": + if set(accepted) != {"contract", "plan", "files", "parent_context", "correction"}: + raise ValueError("task_review_input_invalid") + else: + raise ValueError("task_review_input_invalid") + plan = dict(accepted["plan"]) + plan_keys = { + "contract", "project_id", "goal", "draft_revision", "input_paths", "output_paths", + "absent_output_paths", "base_manifest_hash", "provider", "model", "provider_binary_hash", + "check_profile_id", "check_profile_version", "helper_hash", "limits", + } + plan_contract = plan.get("contract") + expected_plan_keys = plan_keys if plan_contract == "torq-candidate-plan-v1" else plan_keys | {"lineage"} + if ( + set(plan) != expected_plan_keys + or (input_contract, plan_contract) + not in { + ("torq-candidate-input-v1", "torq-candidate-plan-v1"), + ("torq-candidate-input-v2", "torq-candidate-plan-v2"), + } + ): + raise ValueError("task_review_plan_invalid") + plan_hash = digest_json(plan) + if plan_hash != start.get("plan_hash") or plan_hash != ready.get("plan_hash"): + raise ValueError("task_review_plan_hash_mismatch") + base = _source_bundle(accepted.get("files")) + for key in ("input_paths", "output_paths", "absent_output_paths"): + values = plan.get(key) + if not isinstance(values, list) or not all(isinstance(item, str) for item in values): + raise ValueError("task_review_plan_invalid") + safe = [validate_relative_path(item) for item in values] + if safe != values or len({item.casefold() for item in safe}) != len(safe): + raise ValueError("task_review_plan_invalid") + if set(base) != set(plan["input_paths"]): + raise ValueError("task_review_base_scope_mismatch") + if set(plan["absent_output_paths"]) != set(plan["output_paths"]) - set(base): + raise ValueError("task_review_absent_scope_mismatch") + base_hash = _manifest(base) + if base_hash != plan.get("base_manifest_hash") or base_hash != start.get("base_manifest_hash"): + raise ValueError("task_review_base_hash_mismatch") + + lineage_projection: dict[str, Any] | None = None + parent_result: dict[str, bytes] | None = None + if plan_contract == "torq-candidate-plan-v2": + lineage = plan.get("lineage") + parent_context = accepted.get("parent_context") + correction = accepted.get("correction") + if not isinstance(lineage, Mapping) or not isinstance(parent_context, Mapping): + raise ValueError("task_review_lineage_invalid") + if set(parent_context) != {"candidate", "files"} or not validate_candidate_ref(parent_context.get("candidate")): + raise ValueError("task_review_lineage_invalid") + parent_candidate = dict(parent_context["candidate"]) + parent = resolve_task_review( + evidence_root, str(parent_candidate["task_id"]), int(parent_candidate["ready_sequence"]) + ) + if parent.candidate_ref != parent_candidate: + raise ValueError("task_review_lineage_invalid") + parent_result = _source_bundle(parent_context.get("files")) + if parent_result != parent.result_files: + raise ValueError("task_review_parent_context_mismatch") + mode = lineage.get("mode") + if mode == "refinement": + if set(lineage) != { + "mode", "parent_candidate", "correction_revision", "correction_hash", + "root_base_scope_hash", + } or lineage.get("parent_candidate") != parent_candidate: + raise ValueError("task_review_lineage_invalid") + if base != parent.base_files or lineage.get("root_base_scope_hash") != base_hash: + raise ValueError("task_review_lineage_base_mismatch") + if ( + not isinstance(correction, Mapping) + or set(correction) != {"revision", "text", "content_hash", "decision"} + or not isinstance(correction.get("revision"), int) + or isinstance(correction.get("revision"), bool) + or correction["revision"] <= 0 + or not isinstance(correction.get("text"), str) + or digest_bytes(correction["text"].encode("utf-8")) != correction.get("content_hash") + or correction.get("revision") != lineage.get("correction_revision") + or correction.get("content_hash") != lineage.get("correction_hash") + or plan.get("goal") != correction.get("text") + ): + raise ValueError("task_review_correction_invalid") + _verify_correction_decision( + evidence_root.parent / "review-evidence", + correction.get("decision"), + parent, + plan_hash, + int(correction["revision"]), + str(correction["content_hash"]), + ) + lineage_projection = { + "mode": "refinement", + "parent_candidate": parent_candidate, + "correction_revision": correction["revision"], + "correction_hash": correction["content_hash"], + "parent_changes": [], + } + elif mode == "continuation": + if ( + set(lineage) != {"mode", "parent_candidate", "application"} + or lineage.get("parent_candidate") != parent_candidate + or correction is not None + or not validate_decision_ref(lineage.get("application")) + ): + raise ValueError("task_review_lineage_invalid") + _verify_application_ref( + evidence_root.parent / "apply-evidence", + evidence_root.parent / "review-evidence", + lineage["application"], + parent, + ) + lineage_projection = { + "mode": "continuation", + "parent_candidate": parent_candidate, + "application": dict(lineage["application"]), + "parent_changes": [], + } + else: + raise ValueError("task_review_lineage_invalid") + + if ( + not isinstance(bundle, Mapping) + or set(bundle) != {"contract", "manifest_hash", "operations", "raw_response"} + or bundle.get("contract") != "torq-candidate-bundle-v1" + or not isinstance(bundle.get("operations"), list) + or not isinstance(bundle.get("raw_response"), str) + or digest_bytes(bundle["raw_response"].encode("utf-8")) != generated.get("raw_response_hash") + ): + raise ValueError("task_review_candidate_invalid") + if start.get("provider") != plan.get("provider") or start.get("model") != plan.get("model"): + raise ValueError("task_review_provider_mismatch") + if ( + plan.get("check_profile_id") != "structural-v1" + or plan.get("check_profile_version") != "1.0.0" + or checked.get("check_profile_id") != plan.get("check_profile_id") + or checked.get("check_profile_version") != plan.get("check_profile_version") + or checked.get("helper_hash") != plan.get("helper_hash") + ): + raise ValueError("task_review_check_identity_mismatch") + output_paths = plan["output_paths"] + allowed = {validate_relative_path(item) for item in output_paths} + result = dict(base) + changed: list[str] = [] + changes: list[dict[str, object]] = [] + if not bundle["operations"] or len(bundle["operations"]) > MAX_TASK_FILES: + raise ValueError("task_review_operation_invalid") + parsed, _raw_hash = parse_candidate_output( + bundle["raw_response"].encode("utf-8"), plan_hash=plan_hash, input_hash=str(start["input_hash"]) + ) + expected_operations: list[dict[str, object]] = [] + for operation in parsed: + raw_content = str(operation["content"]).encode("utf-8") + expected_operations.append( + {**operation, "content_bytes": len(raw_content), "content_hash": digest_bytes(raw_content)} + ) + if bundle["operations"] != expected_operations: + raise ValueError("task_review_raw_operation_mismatch") + changed_folded: set[str] = set() + for operation in bundle["operations"]: + if not isinstance(operation, Mapping) or set(operation) != { + "operation", "path", "base_hash", "content", "content_bytes", "content_hash" + }: + raise ValueError("task_review_operation_invalid") + path_value = operation.get("path") + content_value = operation.get("content") + if not isinstance(path_value, str) or not isinstance(content_value, str): + raise ValueError("task_review_operation_invalid") + path = validate_relative_path(path_value) + after = content_value.encode("utf-8") + before = base.get(path) + kind = operation.get("operation") + valid_base = (kind == "create" and before is None and operation.get("base_hash") is None) or ( + kind == "replace" and before is not None and operation.get("base_hash") == digest_bytes(before) + ) + if ( + not valid_base + or path not in allowed + or path.casefold() in changed_folded + or len(after) > MAX_TASK_FILE_BYTES + or operation.get("content_bytes") != len(after) + or operation.get("content_hash") != digest_bytes(after) + or before == after + ): + raise ValueError("task_review_operation_invalid") + result[path] = after + changed.append(path) + changed_folded.add(path.casefold()) + changes.append(_change(path, before, after, str(kind))) + if ( + not changed + or len(result) > MAX_TASK_FILES + or sum(len(value) for value in result.values()) > MAX_TASK_TOTAL_BYTES + or _manifest(result) != bundle.get("manifest_hash") + or _manifest(result) != ready.get("candidate_manifest_hash") + ): + raise ValueError("task_review_candidate_hash_mismatch") + + if ( + not isinstance(check, Mapping) + or set(check) != {"contract", "checked", "status"} + or check.get("contract") != "torq-structural-result-v1" + or check.get("status") != "passed" + or checked.get("exit_code") != 0 + or checked.get("output_complete") is not True + or checked.get("termination") != "confirmed_empty" + ): + raise ValueError("task_review_check_invalid") + validators = {".py": "python_ast", ".json": "strict_json", ".md": "utf8_text", ".txt": "utf8_text"} + expected_checked = [ + {"path": path, "validator": validators[Path(path).suffix.casefold()]} + for path in sorted(result, key=str.casefold) + ] + if check.get("checked") != expected_checked or checked.get("candidate_manifest_hash") != _manifest(result): + raise ValueError("task_review_check_mismatch") + + if lineage_projection is not None and parent_result is not None: + comparison: list[dict[str, object]] = [] + for path in sorted(set(parent_result) | set(result), key=str.casefold): + parent_content = parent_result.get(path) + revision_content = result.get(path) + if parent_content != revision_content: + comparison.append(_lineage_change(path, parent_content, revision_content)) + lineage_projection["parent_changes"] = comparison + + immutable = { + "schema": "torq-task-review-core-v1", + "task_id": task_id, + "ready_sequence": ready_sequence, + "plan": { + "project_id": plan["project_id"], "goal": plan["goal"], "provider": plan["provider"], + "model": plan["model"], "input_paths": plan["input_paths"], "output_paths": plan["output_paths"], + "plan_hash": plan_hash, "base_scope_manifest_hash": base_hash, + "candidate_scope_manifest_hash": _manifest(result), + }, + "changes": changes, + "checks": { + "sequence": check_row["sequence"], "profile_id": checked["check_profile_id"], + "profile_version": checked["check_profile_version"], "exit_code": checked["exit_code"], + "output_complete": checked["output_complete"], "termination": checked["termination"], + "output": check, "helper_hash": checked["helper_hash"], "argv_hash": checked["argv_hash"], + "command_contract": "python -I -S ", + }, + "lineage": lineage_projection, + } + review_hash = digest_json(immutable) + terminal_hash = digest_bytes(manifest_raw) + candidate_ref = { + "task_id": task_id, + "ready_sequence": ready_sequence, + "ready_receipt_hash": ready_row["receipt_hash"], + "terminal_manifest_hash": terminal_hash, + "plan_hash": plan_hash, + "base_scope_manifest_hash": base_hash, + "input_hash": start["input_hash"], + "candidate_scope_manifest_hash": _manifest(result), + "check_sequence": check_row["sequence"], + "check_receipt_hash": check_row["receipt_hash"], + "review_hash": review_hash, + } + envelope = {"schema": REVIEW_SCHEMA, "verified": True, "review_hash": review_hash, "review": immutable} + if len(canonical_json(envelope).encode("utf-8")) > 2_097_152: + raise ValueError("task_review_payload_too_large") + return ResolvedTaskReview(envelope, candidate_ref, plan, base, result, tuple(changed)) + + +__all__ = ["REVIEW_SCHEMA", "ResolvedTaskReview", "resolve_task_review"] diff --git a/src/torq_cli/interfaces/cli.py b/src/torq_cli/interfaces/cli.py index cd8e250..d6e7a68 100644 --- a/src/torq_cli/interfaces/cli.py +++ b/src/torq_cli/interfaces/cli.py @@ -22,6 +22,7 @@ from torq_cli.application.chat_projection import reduce_chat_projection from torq_cli.application.chat_runtime import ChatRuntimeCoordinator from torq_cli.application.candidate_tasks import CandidateTaskService, TaskProject +from torq_cli.application.candidate_review import CandidateReviewService from torq_cli.application.workspace import classify_workspace_root from torq_cli.application.fleet import FleetProjector from torq_cli.application.live_runtime import build_live_runtime @@ -405,6 +406,7 @@ def main(argv: Sequence[str] | None = None) -> int: ) if args.serve: task_service = None + review_service = None task_runtime_root = None try: chat_controller = None @@ -537,6 +539,11 @@ def chat_snapshot_provider() -> Mapping[str, Any]: provider=args.task_provider, model=args.task_model, ) + review_service = CandidateReviewService( + tasks=task_service, + state_root=task_state_root, + common_authority_root=task_parent / "primary-authority", + ) server = create_fleet_server( projector, @@ -546,6 +553,7 @@ def chat_snapshot_provider() -> Mapping[str, Any]: chat_snapshot_provider=chat_snapshot_provider, workspace_chat_provider=args.chat_provider, task_service=task_service, + review_service=review_service, ) except (OSError, ValueError) as exc: if task_service is not None: diff --git a/src/torq_cli/interfaces/fleet_http.py b/src/torq_cli/interfaces/fleet_http.py index 31f8c3e..db7e117 100644 --- a/src/torq_cli/interfaces/fleet_http.py +++ b/src/torq_cli/interfaces/fleet_http.py @@ -154,6 +154,7 @@ class _Session: issued_at: float last_seen: float read_only: bool = False + subject_id: str = "" class FleetSessionManager: @@ -187,7 +188,9 @@ def exchange(self, nonce: str) -> str: self._nonce_spent = True now = self._clock() token = secrets.token_urlsafe(48) - self._sessions[token] = _Session(token, now, now) + self._sessions[token] = _Session( + token, now, now, subject_id="session-" + secrets.token_hex(16) + ) return token def authenticate(self, cookie_header: str | None, *, touch: bool = True) -> _Session | None: @@ -255,6 +258,7 @@ def rotate(self, session: _Session) -> str: session.issued_at, now, read_only=session.read_only, + subject_id=session.subject_id, ) self._read_recovery[session.token] = token return token @@ -332,6 +336,18 @@ def _reject_json_constant(value: str) -> object: raise ValueError("context_request_non_finite") +def _safe_finding(exc: BaseException, default: str) -> str: + if exc.args and isinstance(exc.args[0], str): + value = exc.args[0].split(":", 1)[0] + if ( + value.startswith(("task_", "candidate_")) + and value.replace("_", "").isalnum() + and len(value) <= 64 + ): + return value + return default + + class TaskHTTPService(Protocol): def capabilities(self) -> dict[str, Any]: ... def draft(self, project_id: str) -> dict[str, Any] | None: ... @@ -345,6 +361,25 @@ def task(self, task_id: str) -> dict[str, Any]: ... def history(self) -> list[dict[str, Any]]: ... +class ReviewHTTPService(Protocol): + def review(self, task_id: str, ready_sequence: int) -> dict[str, Any]: ... + def correction(self, task_id: str, ready_sequence: int) -> dict[str, Any]: ... + def save_correction(self, task_id: str, ready_sequence: int, *, text: str, expected_revision: int) -> dict[str, Any]: ... + def review_child_plan(self, task_id: str, ready_sequence: int, *, request_id: str, correction_revision: int, correction_hash: str, review_hash: str, subject_id: str) -> dict[str, Any]: ... + def replay_child_plan(self, task_id: str, ready_sequence: int, *, request_id: str, correction_revision: int, correction_hash: str, review_hash: str) -> dict[str, Any]: ... + def start_revision(self, *, request_id: str, plan_hash: str, replay_only: bool = False) -> dict[str, Any]: ... + def continue_task(self, *, request_id: str, application_id: str) -> dict[str, Any]: ... + def replay_continuation(self, *, request_id: str, application_id: str) -> dict[str, Any]: ... + def accept(self, *, request_id: str, task_id: str, ready_sequence: int, review_hash: str, subject_id: str) -> dict[str, Any]: ... + def replay_accept(self, *, request_id: str, task_id: str, ready_sequence: int, review_hash: str) -> dict[str, Any]: ... + def apply(self, *, request_id: str, candidate: Mapping[str, Any], acceptance: Mapping[str, Any], subject_id: str) -> dict[str, Any]: ... + def replay_apply(self, *, request_id: str, candidate: Mapping[str, Any], acceptance: Mapping[str, Any]) -> dict[str, Any]: ... + def application(self, application_id: str) -> dict[str, Any]: ... + def history(self, *, query: str = "", limit: int = 50, cursor: str | None = None) -> dict[str, Any]: ... + def recovery_status(self, project_id: str) -> dict[str, Any]: ... + def recover(self, project_id: str) -> dict[str, Any]: ... + + def create_fleet_server( projector: FleetProjector, *, @@ -360,6 +395,7 @@ def create_fleet_server( chat_snapshot_provider: Callable[[], Mapping[str, Any]] | None = None, workspace_chat_provider: str | None = None, task_service: TaskHTTPService | None = None, + review_service: ReviewHTTPService | None = None, ) -> ThreadingHTTPServer: if not _loopback_host(host): raise ValueError("fleet_loopback_required") @@ -687,6 +723,59 @@ def do_GET(self) -> None: # noqa: N802 except (OSError, ValueError): self._json(409, {"status": "blocked", "finding": "task_state_unavailable"}) return + review_match = re.fullmatch( + r"/api/v1/task-reviews/(run-task-[a-f0-9]{24})/([1-9][0-9]*)", + parsed.path, + ) + correction_match = re.fullmatch( + r"/api/v1/task-reviews/(run-task-[a-f0-9]{24})/([1-9][0-9]*)/correction", + parsed.path, + ) + application_match = re.fullmatch( + r"/api/v1/task-applications/(application-[a-f0-9]{24})", + parsed.path, + ) + if review_match is not None and review_service is not None: + try: + self._json(200, review_service.review(review_match.group(1), int(review_match.group(2)))) + except (OSError, ValueError) as exc: + self._json(409, {"status": "blocked", "finding": _safe_finding(exc, "task_review_unavailable")}) + return + if correction_match is not None and review_service is not None: + try: + self._json(200, {"correction": review_service.correction(correction_match.group(1), int(correction_match.group(2)))}) + except (OSError, ValueError) as exc: + self._json(409, {"status": "blocked", "finding": _safe_finding(exc, "task_review_unavailable")}) + return + if application_match is not None and review_service is not None: + try: + self._json(200, review_service.application(application_match.group(1))) + except (OSError, ValueError) as exc: + self._json(409, {"status": "blocked", "finding": _safe_finding(exc, "task_application_unavailable")}) + return + if parsed.path == "/api/v1/task-history" and review_service is not None: + values = parse_qs(parsed.query, keep_blank_values=True) + if set(values) - {"q", "limit", "cursor"} or any(len(item) != 1 for item in values.values()): + self._json(409, {"status": "blocked", "finding": "candidate_history_query_invalid"}) + return + try: + limit = int(values.get("limit", ["50"])[0]) + self._json(200, review_service.history( + query=values.get("q", [""])[0], limit=limit, + cursor=values.get("cursor", [None])[0], + )) + except (OSError, ValueError) as exc: + self._json(409, {"status": "blocked", "finding": _safe_finding(exc, "candidate_history_query_invalid")}) + return + recovery_match = re.fullmatch( + r"/api/v1/task-recovery/([A-Za-z0-9][A-Za-z0-9._-]{0,63})", parsed.path + ) + if recovery_match is not None and review_service is not None: + try: + self._json(200, review_service.recovery_status(recovery_match.group(1))) + except (OSError, ValueError) as exc: + self._json(409, {"status": "blocked", "finding": _safe_finding(exc, "task_apply_recovery_unavailable")}) + return draft_match = re.fullmatch(r"/api/v1/tasks/drafts/([A-Za-z0-9][A-Za-z0-9._-]{0,63})", parsed.path) if draft_match is not None and task_service is not None: try: @@ -863,6 +952,15 @@ def do_POST(self) -> None: # noqa: N802 r"/api/v1/tasks/drafts/([A-Za-z0-9][A-Za-z0-9._-]{0,63})/delete", path ) task_stop_match = re.fullmatch(r"/api/v1/tasks/(run-task-[a-f0-9]{24})/stop", path) + review_correction_match = re.fullmatch( + r"/api/v1/task-reviews/(run-task-[a-f0-9]{24})/([1-9][0-9]*)/correction", path + ) + review_child_match = re.fullmatch( + r"/api/v1/task-reviews/(run-task-[a-f0-9]{24})/([1-9][0-9]*)/child-plans", path + ) + review_recovery_match = re.fullmatch( + r"/api/v1/task-recovery/([A-Za-z0-9][A-Za-z0-9._-]{0,63})/recover", path + ) if path == "/api/v1/chat/turns": operation = "chat_submit" service_present = chat_controller is not None @@ -884,6 +982,27 @@ def do_POST(self) -> None: # noqa: N802 elif task_stop_match is not None: operation = "task_stop" service_present = task_service is not None + elif review_correction_match is not None: + operation = "review_correction" + service_present = review_service is not None + elif review_child_match is not None: + operation = "review_child_plan" + service_present = review_service is not None + elif path == "/api/v1/task-revisions": + operation = "review_revision" + service_present = review_service is not None + elif path == "/api/v1/task-continuations": + operation = "review_continuation" + service_present = review_service is not None + elif path == "/api/v1/task-reviews/accept": + operation = "review_accept" + service_present = review_service is not None + elif path == "/api/v1/task-applications": + operation = "review_apply" + service_present = review_service is not None + elif review_recovery_match is not None: + operation = "review_recover" + service_present = review_service is not None elif path in {"/api/v1/context", "/api/v1/fleet/context"}: operation = "context" service_present = context_injector is not None @@ -904,7 +1023,10 @@ def do_POST(self) -> None: # noqa: N802 return replay_only = False session = session_manager.claim_mutation(self.headers.get("Cookie")) - if session is None and operation == "task_start": + if session is None and operation in { + "task_start", "review_child_plan", "review_revision", "review_continuation", + "review_accept", "review_apply" + }: recovered = session_manager.recover_rotated_session(self.headers.get("Cookie")) if recovered is not None: session, _ = recovered @@ -951,6 +1073,12 @@ def do_POST(self) -> None: # noqa: N802 replay_only=replay_only, ) return + if operation.startswith("review_"): + self._review_post( + operation, review_correction_match, review_child_match, review_recovery_match, + session, replay_only=replay_only + ) + return snapshot = projector.snapshot() envelope = controls.envelope( snapshot, @@ -1327,6 +1455,140 @@ def _task_post( rotated = session_manager.rotate(session) self._json(409, {"status": "blocked", "finding": finding}, session_token=rotated) + def _review_post( + self, + operation: str, + correction_match: re.Match[str] | None, + child_match: re.Match[str] | None, + recovery_match: re.Match[str] | None, + session: _Session, + *, + replay_only: bool, + ) -> None: + assert review_service is not None + try: + payload = self._read_task_payload(allow_empty=operation == "review_recover") + if operation == "review_correction": + if replay_only or correction_match is None or set(payload) != {"text", "expected_revision"}: + raise ValueError("candidate_correction_request_invalid") + text = payload.get("text") + revision = payload.get("expected_revision") + if not isinstance(text, str) or not isinstance(revision, int) or isinstance(revision, bool): + raise ValueError("candidate_correction_request_invalid") + result = review_service.save_correction( + correction_match.group(1), int(correction_match.group(2)), + text=text, expected_revision=revision, + ) + elif operation == "review_child_plan": + if child_match is None or set(payload) != { + "request_id", "correction_revision", "correction_hash", "review_hash" + }: + raise ValueError("candidate_child_plan_request_invalid") + request_id = payload.get("request_id") + revision = payload.get("correction_revision") + correction_hash = payload.get("correction_hash") + review_hash = payload.get("review_hash") + if ( + not isinstance(request_id, str) + or not isinstance(revision, int) + or isinstance(revision, bool) + or not isinstance(correction_hash, str) + or not isinstance(review_hash, str) + ): + raise ValueError("candidate_child_plan_request_invalid") + if replay_only: + result = review_service.replay_child_plan( + child_match.group(1), int(child_match.group(2)), + request_id=request_id, correction_revision=revision, + correction_hash=correction_hash, review_hash=review_hash, + ) + else: + result = review_service.review_child_plan( + child_match.group(1), int(child_match.group(2)), + request_id=request_id, correction_revision=revision, + correction_hash=correction_hash, review_hash=review_hash, + subject_id=session.subject_id, + ) + elif operation == "review_revision": + if set(payload) != {"request_id", "plan_hash"}: + raise ValueError("candidate_revision_request_invalid") + request_id = payload.get("request_id") + plan_hash = payload.get("plan_hash") + if not isinstance(request_id, str) or not isinstance(plan_hash, str): + raise ValueError("candidate_revision_request_invalid") + result = review_service.start_revision( + request_id=request_id, plan_hash=plan_hash, replay_only=replay_only + ) + elif operation == "review_continuation": + if set(payload) != {"request_id", "application_id"}: + raise ValueError("candidate_continuation_request_invalid") + request_id = payload.get("request_id") + application_id = payload.get("application_id") + if not isinstance(request_id, str) or not isinstance(application_id, str): + raise ValueError("candidate_continuation_request_invalid") + method = ( + review_service.replay_continuation + if replay_only else review_service.continue_task + ) + result = method(request_id=request_id, application_id=application_id) + elif operation == "review_accept": + if set(payload) != {"request_id", "task_id", "ready_sequence", "review_hash"}: + raise ValueError("candidate_accept_request_invalid") + request_id = payload.get("request_id") + task_id = payload.get("task_id") + sequence = payload.get("ready_sequence") + review_hash = payload.get("review_hash") + if ( + not isinstance(request_id, str) or not isinstance(task_id, str) + or not isinstance(sequence, int) or isinstance(sequence, bool) + or not isinstance(review_hash, str) + ): + raise ValueError("candidate_accept_request_invalid") + if replay_only: + result = review_service.replay_accept( + request_id=request_id, task_id=task_id, + ready_sequence=sequence, review_hash=review_hash, + ) + else: + result = review_service.accept( + request_id=request_id, task_id=task_id, ready_sequence=sequence, + review_hash=review_hash, subject_id=session.subject_id, + ) + elif operation == "review_apply": + if set(payload) != {"request_id", "candidate", "acceptance"}: + raise ValueError("candidate_apply_request_invalid") + request_id = payload.get("request_id") + candidate = payload.get("candidate") + acceptance = payload.get("acceptance") + if not isinstance(request_id, str) or not isinstance(candidate, Mapping) or not isinstance(acceptance, Mapping): + raise ValueError("candidate_apply_request_invalid") + if replay_only: + result = review_service.replay_apply( + request_id=request_id, candidate=candidate, acceptance=acceptance, + ) + else: + result = review_service.apply( + request_id=request_id, candidate=candidate, acceptance=acceptance, + subject_id=session.subject_id, + ) + elif operation == "review_recover": + if replay_only or payload or recovery_match is None: + raise ValueError("task_apply_recovery_request_invalid") + result = review_service.recover(recovery_match.group(1)) + else: + raise ValueError("candidate_request_invalid") + rotated = session_manager.rotate(session) + self._json(200, {"status": "accepted", "result": result}, session_token=rotated) + except ConnectionError: + return + except (OSError, RuntimeError, ValueError) as exc: + finding = _safe_finding(exc, "candidate_request_invalid") + if replay_only: + self._json(409, {"status": "blocked", "finding": finding}) + else: + rotated = session_manager.rotate(session) + self._json(409, {"status": "blocked", "finding": finding}, session_token=rotated) + def _read_control_payload(self) -> Mapping[str, Any]: content_types = self.headers.get_all("Content-Type", failobj=[]) if len(content_types) != 1 or content_types[0].casefold() not in { diff --git a/src/torq_cli/safety/primary_marker.py b/src/torq_cli/safety/primary_marker.py new file mode 100644 index 0000000..8671cd2 --- /dev/null +++ b/src/torq_cli/safety/primary_marker.py @@ -0,0 +1,166 @@ +"""Shared per-user primary transaction marker under a kernel-held lease.""" + +from __future__ import annotations + +import json +import os +import re +import secrets +import stat +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +from torq_cli.domain.hermetic import LegacyConfigTooLarge, LegacyConfigUnreadable, ProtectedPathError, read_bounded_legacy_config +from torq_cli.safety.primary_transaction import AnchoredPrimary +from torq_cli.safety.receipts import ( + fsync_directory, + restrict_owner_only_directory, + restrict_owner_only_file, + signing_file_permissions_are_restricted, +) +from torq_cli.safety.task_workspace import canonical_json, validate_disjoint_roots + +_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}") +_HASH = re.compile(r"sha256:[a-f0-9]{64}") + + +class PrimaryMarkerAuthority: + def __init__(self, root: Path) -> None: + self.root = root.absolute() + validate_disjoint_roots([self.root]) + self.root.mkdir(parents=True, exist_ok=True) + restrict_owner_only_directory(self.root) + validate_disjoint_roots([self.root]) + + def marker_path(self, primary: AnchoredPrimary) -> Path: + return self.root / (primary.identity.digest().removeprefix("sha256:") + ".json") + + def read(self, primary: AnchoredPrimary) -> dict[str, Any] | None: + path = self.marker_path(primary) + if not os.path.lexists(path): + return None + metadata = path.stat(follow_symlinks=False) + if ( + not stat.S_ISREG(metadata.st_mode) + or path.is_symlink() + or metadata.st_nlink != 1 + or metadata.st_size > 16_384 + or not signing_file_permissions_are_restricted(path) + ): + raise ValueError("task_apply_marker_unsafe") + try: + raw = read_bounded_legacy_config(str(path)) + except (LegacyConfigTooLarge, LegacyConfigUnreadable, ProtectedPathError) as exc: + raise ValueError("task_apply_marker_unsafe") from exc + after = path.stat(follow_symlinks=False) + if ( + (metadata.st_dev, metadata.st_ino, metadata.st_size, metadata.st_mtime_ns) + != (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) + or len(raw) != metadata.st_size + ): + raise ValueError("task_apply_marker_changed") + def unique(pairs: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, child in pairs: + if key in result: + raise ValueError("task_apply_marker_invalid") + result[key] = child + return result + + def reject(_value: str) -> object: + raise ValueError("task_apply_marker_invalid") + try: + value = json.loads(raw, object_pairs_hook=unique, parse_constant=reject) + except json.JSONDecodeError as exc: + raise ValueError("task_apply_marker_invalid") from exc + keys = { + "schema", "primary_identity_hash", "installation_id", "application_id", + "authority_locator", "journal_hash", "phase", "revision", + } + if ( + not isinstance(value, dict) + or set(value) != keys + or value.get("schema") != "torq-primary-pending-v1" + or value.get("primary_identity_hash") != primary.identity.digest() + or value.get("phase") not in {"reserved", "prepared", "started", "recovering", "terminal"} + or not isinstance(value.get("installation_id"), str) + or _ID.fullmatch(value["installation_id"]) is None + or not isinstance(value.get("application_id"), str) + or _ID.fullmatch(value["application_id"]) is None + or not isinstance(value.get("authority_locator"), str) + or _ID.fullmatch(value["authority_locator"]) is None + or not isinstance(value.get("revision"), int) + or isinstance(value.get("revision"), bool) + or value["revision"] <= 0 + or not ( + value.get("journal_hash") is None and value.get("phase") == "reserved" + or isinstance(value.get("journal_hash"), str) + and _HASH.fullmatch(value["journal_hash"]) is not None + and value.get("phase") != "reserved" + ) + ): + raise ValueError("task_apply_marker_invalid") + return value + + def assert_clear(self, project_root: Path) -> None: + with AnchoredPrimary(project_root) as primary: + if self.read(primary) is not None: + raise ValueError("task_apply_recovery_pending") + + def write(self, primary: AnchoredPrimary, value: Mapping[str, Any]) -> dict[str, Any]: + path = self.marker_path(primary) + current = self.read(primary) + revision = 1 if current is None else int(current["revision"]) + 1 + record = dict(value) + record["revision"] = revision + # Validate the exact outbound shape before it becomes a durable block. + if ( + set(record) != { + "schema", "primary_identity_hash", "installation_id", "application_id", + "authority_locator", "journal_hash", "phase", "revision", + } + or record.get("schema") != "torq-primary-pending-v1" + or record.get("primary_identity_hash") != primary.identity.digest() + or not isinstance(record.get("installation_id"), str) + or _ID.fullmatch(record["installation_id"]) is None + or not isinstance(record.get("application_id"), str) + or _ID.fullmatch(record["application_id"]) is None + or not isinstance(record.get("authority_locator"), str) + or _ID.fullmatch(record["authority_locator"]) is None + or record.get("phase") not in {"reserved", "prepared", "started", "recovering", "terminal"} + or not ( + record.get("journal_hash") is None and record.get("phase") == "reserved" + or isinstance(record.get("journal_hash"), str) + and _HASH.fullmatch(record["journal_hash"]) is not None + and record.get("phase") != "reserved" + ) + ): + raise ValueError("task_apply_marker_invalid") + if current is not None and ( + current.get("installation_id") != record.get("installation_id") + or current.get("application_id") != record.get("application_id") + ): + raise ValueError("task_apply_marker_owned_elsewhere") + temporary = path.with_name(path.name + "." + secrets.token_hex(8) + ".tmp") + temporary.write_text(canonical_json(record), encoding="utf-8", newline="\n") + restrict_owner_only_file(temporary) + with temporary.open("r+b") as stream: + os.fsync(stream.fileno()) + os.replace(temporary, path) + restrict_owner_only_file(path) + fsync_directory(self.root) + return record + + def clear(self, primary: AnchoredPrimary, *, installation_id: str, application_id: str) -> None: + path = self.marker_path(primary) + current = self.read(primary) + if current is None: + return + if current.get("installation_id") != installation_id or current.get("application_id") != application_id: + raise ValueError("task_apply_marker_owned_elsewhere") + path.unlink() + fsync_directory(self.root) + + +__all__ = ["PrimaryMarkerAuthority"] diff --git a/src/torq_cli/safety/primary_transaction.py b/src/torq_cli/safety/primary_transaction.py new file mode 100644 index 0000000..a069a82 --- /dev/null +++ b/src/torq_cli/safety/primary_transaction.py @@ -0,0 +1,1303 @@ +"""Handle-anchored bounded writes for explicit candidate application.""" + +from __future__ import annotations + +import ctypes +import errno +import hashlib +import os +import re +import stat +import sys +from dataclasses import dataclass +from pathlib import Path, PurePosixPath +from collections.abc import Callable +from typing import Any + +from torq_cli.safety.task_workspace import ( + MAX_TASK_FILES, + MAX_TASK_FILE_BYTES, + digest_bytes, + validate_relative_path, +) + +_READ_CHUNK = 65_536 +_DARWIN_XATTR_LIST_LIMIT = 65_536 +_DARWIN_XATTR_COUNT_LIMIT = 128 +_DARWIN_ACL_TYPE_EXTENDED = 0x00000100 +_DARWIN_ACL_FIRST_ENTRY = 0 + + +def _darwin_libc() -> Any: + return ctypes.CDLL(None, use_errno=True) + + +def _darwin_xattrs(descriptor: int) -> list[str]: + """Enumerate xattr names through the open descriptor using Darwin's ABI.""" + function = _darwin_libc().flistxattr + function.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int] + function.restype = ctypes.c_ssize_t + capacity = 0 + for _attempt in range(3): + ctypes.set_errno(0) + required = int(function(descriptor, None, 0, 0)) + if required < 0: + raise RuntimeError("task_apply_metadata_unreadable") + if required == 0: + return [] + if required > _DARWIN_XATTR_LIST_LIMIT: + raise ValueError("task_apply_metadata_unsupported") + capacity = max(capacity, required) + buffer = ctypes.create_string_buffer(capacity) + ctypes.set_errno(0) + count = int(function(descriptor, buffer, capacity, 0)) + if count < 0: + if ctypes.get_errno() == errno.ERANGE: + continue + raise RuntimeError("task_apply_metadata_unreadable") + if count != required or count > capacity or count > _DARWIN_XATTR_LIST_LIMIT: + raise ValueError("task_apply_metadata_unsupported") + if count == 0: + return [] + raw = bytes(buffer.raw[:count]) + if not raw.endswith(b"\x00"): + raise ValueError("task_apply_metadata_unsupported") + encoded = raw[:-1].split(b"\x00") + if ( + len(encoded) > _DARWIN_XATTR_COUNT_LIMIT + or any(not item or len(item) > 127 for item in encoded) + ): + raise ValueError("task_apply_metadata_unsupported") + try: + return [item.decode("utf-8", errors="strict") for item in encoded] + except UnicodeDecodeError as exc: + raise ValueError("task_apply_metadata_unsupported") from exc + raise RuntimeError("task_apply_metadata_unstable") + + +def _darwin_acl_present(descriptor: int) -> bool: + """Detect a Darwin extended ACL through the open descriptor.""" + library = _darwin_libc() + get_acl = library.acl_get_fd_np + get_acl.argtypes = [ctypes.c_int, ctypes.c_int] + get_acl.restype = ctypes.c_void_p + get_entry = library.acl_get_entry + get_entry.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p)] + get_entry.restype = ctypes.c_int + free_acl = library.acl_free + free_acl.argtypes = [ctypes.c_void_p] + free_acl.restype = ctypes.c_int + ctypes.set_errno(0) + acl = get_acl(descriptor, _DARWIN_ACL_TYPE_EXTENDED) + if not acl: + # Apple Libc acl_get_fd_np initializes ACL to NULL and delegates to + # filesec_get_property(FILESEC_ACL), which sets ENOENT exactly when the + # held file has no FS_VALID_ACL property. Other NULL results are errors. + if ctypes.get_errno() == errno.ENOENT: + return False + raise RuntimeError("task_apply_metadata_unreadable") + entry = ctypes.c_void_p() + try: + ctypes.set_errno(0) + result = int(get_entry(acl, _DARWIN_ACL_FIRST_ENTRY, ctypes.byref(entry))) + if result == 0: + return True + if result == -1 and ctypes.get_errno() == errno.EINVAL: + return False + raise RuntimeError("task_apply_metadata_unreadable") + finally: + if free_acl(acl) != 0: + raise RuntimeError("task_apply_metadata_unreadable") + +if sys.platform != "win32": + import fcntl + + try: + _POSIX_DIRECTORY = os.O_DIRECTORY + _POSIX_NOFOLLOW = os.O_NOFOLLOW + except AttributeError as exc: # pragma: no cover - platform capability gate + raise RuntimeError("task_apply_platform_unsupported") from exc + + def _posix_lock(descriptor: int, *, release: bool = False) -> None: + operation = fcntl.LOCK_UN if release else fcntl.LOCK_EX | fcntl.LOCK_NB + fcntl.flock(descriptor, operation) + + def _posix_xattrs(descriptor: int) -> list[str]: + if sys.platform == "darwin": + result = _darwin_xattrs(descriptor) + if _darwin_acl_present(descriptor): + result.append("com.apple.system.acl") + return result + reader = getattr(os, "listxattr", None) + if reader is None: + raise RuntimeError("task_apply_platform_unsupported") + return list(reader(descriptor)) + + def _posix_apply_policy(descriptor: int, policy: dict[str, object]) -> None: + mode, uid, gid = (policy.get(key) for key in ("mode", "uid", "gid")) + if any(not isinstance(value, int) or isinstance(value, bool) for value in (mode, uid, gid)): + raise ValueError("task_apply_permission_invalid") + assert isinstance(mode, int) and isinstance(uid, int) and isinstance(gid, int) + os.fchmod(descriptor, mode) + os.fchown(descriptor, uid, gid) +else: + _POSIX_DIRECTORY = 0 + _POSIX_NOFOLLOW = 0 + def _posix_lock(descriptor: int, *, release: bool = False) -> None: + del descriptor, release + raise ValueError("task_apply_platform_unsupported") + + def _posix_xattrs(descriptor: int) -> list[str]: + del descriptor + raise ValueError("task_apply_platform_unsupported") + + def _posix_apply_policy(descriptor: int, policy: dict[str, object]) -> None: + del descriptor, policy + raise ValueError("task_apply_platform_unsupported") + + +@dataclass(frozen=True, slots=True) +class PrimaryIdentity: + platform: str + volume: int + file_id: int + + def value(self) -> dict[str, object]: + return {"platform": self.platform, "volume": self.volume, "file_id": self.file_id} + + def digest(self) -> str: + raw = f"{self.platform}:{self.volume}:{self.file_id}".encode("ascii") + return digest_bytes(raw) + + +@dataclass(frozen=True, slots=True) +class AnchoredFile: + path: str + content: bytes | None + content_hash: str | None + permission_policy: dict[str, object] | None + parent_identity: dict[str, int] + target_identity: dict[str, int] | None + + +def _bounded_read_fd(descriptor: int) -> bytes: + result = bytearray() + while len(result) <= MAX_TASK_FILE_BYTES: + try: + chunk = os.read(descriptor, min(_READ_CHUNK, MAX_TASK_FILE_BYTES + 1 - len(result))) + except InterruptedError: + continue + if not chunk: + break + result.extend(chunk) + if len(result) > MAX_TASK_FILE_BYTES: + raise ValueError("task_apply_file_too_large") + return bytes(result) + + +def _write_all_fd(descriptor: int, content: bytes) -> None: + view = memoryview(content) + written = 0 + while written < len(view): + try: + count = os.write(descriptor, view[written:]) + except InterruptedError: + continue + if count <= 0: + raise OSError("anchored write made no progress") + written += count + + +def _posix_identity(metadata: os.stat_result) -> dict[str, int]: + return { + "volume": int(metadata.st_dev), + "file_id": int(metadata.st_ino), + "size": int(metadata.st_size), + "mtime_ns": int(metadata.st_mtime_ns), + } + + +def _posix_parent_identity(metadata: os.stat_result) -> dict[str, int]: + return {"volume": int(metadata.st_dev), "file_id": int(metadata.st_ino)} + + +def _posix_stable_identity(metadata: os.stat_result) -> dict[str, int]: + return {"volume": int(metadata.st_dev), "file_id": int(metadata.st_ino)} + + +def _win_identity(info: tuple[int, int, int, bool, int, int, int]) -> dict[str, int]: + return { + "volume": info[0], "file_id": info[1], "size": info[5], "mtime": info[6] + } + + +def _win_parent_identity(info: tuple[int, int, int, bool, int, int, int]) -> dict[str, int]: + return {"volume": info[0], "file_id": info[1]} + + +def _win_stable_identity(info: tuple[int, int, int, bool, int, int, int]) -> dict[str, int]: + return {"volume": info[0], "file_id": info[1]} + + +class AnchoredPrimary: + """Hold the physical project root and mutate only handle-relative leaves.""" + + def __init__(self, root: Path) -> None: + self.root = root.absolute() + self._root_handle: int | None = None + self._mutex: int | None = None + self._closed = False + if sys.platform == "win32": + self._open_windows() + else: + self._open_posix() + + @property + def identity(self) -> PrimaryIdentity: + return self._identity + + def _open_posix(self) -> None: + if not self.root.is_absolute(): + raise ValueError("task_apply_primary_unsafe") + flags = os.O_RDONLY | _POSIX_DIRECTORY | _POSIX_NOFOLLOW + descriptor = os.open("/", flags) + try: + for part in self.root.parts[1:]: + child = os.open(part, flags, dir_fd=descriptor) + metadata = os.fstat(child) + if not stat.S_ISDIR(metadata.st_mode): + os.close(child) + raise ValueError("task_apply_primary_unsafe") + os.close(descriptor) + descriptor = child + except BaseException: + os.close(descriptor) + raise + metadata = os.fstat(descriptor) + if not stat.S_ISDIR(metadata.st_mode): + os.close(descriptor) + raise ValueError("task_apply_primary_unsafe") + try: + _posix_lock(descriptor) + except OSError as exc: + os.close(descriptor) + raise RuntimeError("task_apply_primary_busy") from exc + self._root_handle = descriptor + self._identity = PrimaryIdentity("posix", int(metadata.st_dev), int(metadata.st_ino)) + + def _open_windows(self) -> None: + if not self.root.drive or self.root.anchor != self.root.drive + "\\": + raise ValueError("task_apply_primary_unsafe") + drive_type = _kernel32().GetDriveTypeW(ctypes.c_wchar_p(self.root.anchor)) + if drive_type == 4: # DRIVE_REMOTE + raise ValueError("task_apply_primary_remote_unsupported") + handle = _win_open_path( + self.root.anchor, _GENERIC_READ | _READ_CONTROL | _SYNCHRONIZE, + _OPEN_EXISTING, _FILE_FLAG_BACKUP_SEMANTICS | _FILE_FLAG_OPEN_REPARSE_POINT, + ) + try: + for part in self.root.parts[1:]: + child = _nt_open_relative( + handle, part, _GENERIC_READ | _READ_CONTROL | _SYNCHRONIZE, + directory=True, create=False, + ) + info = _win_info(child) + if not info[3] or info[2] & _FILE_ATTRIBUTE_REPARSE_POINT: + _win_close(child) + raise ValueError("task_apply_primary_unsafe") + _win_close(handle) + handle = child + except BaseException: + _win_close(handle) + raise + info = _win_info(handle) + identity = PrimaryIdentity("windows", info[0], info[1]) + subject = _win_current_user_sid_string() + name = "Global\\TorqPrimary-" + hashlib.sha256( + f"{subject}:{identity.volume}:{identity.file_id}".encode("ascii") + ).hexdigest() + mutex = _win_mutex(name) + self._root_handle = handle + self._mutex = mutex + self._identity = identity + + def _posix_parent(self, relative: str) -> tuple[int, str]: + assert self._root_handle is not None + path = PurePosixPath(validate_relative_path(relative)) + descriptor = os.dup(self._root_handle) + flags = os.O_RDONLY | _POSIX_DIRECTORY | _POSIX_NOFOLLOW + try: + for part in path.parts[:-1]: + child = os.open(part, flags, dir_fd=descriptor) + metadata = os.fstat(child) + if not stat.S_ISDIR(metadata.st_mode): + os.close(child) + raise ValueError("task_apply_parent_unsafe") + os.close(descriptor) + descriptor = child + return descriptor, path.name + except FileNotFoundError as exc: + os.close(descriptor) + raise ValueError("task_apply_parent_missing") from exc + except BaseException: + os.close(descriptor) + raise + + def _windows_parent(self, relative: str) -> tuple[list[int], str]: + assert self._root_handle is not None + path = PurePosixPath(validate_relative_path(relative)) + handles = [self._root_handle] + try: + for part in path.parts[:-1]: + child = _nt_open_relative( + handles[-1], + part, + _GENERIC_READ | _READ_CONTROL | _SYNCHRONIZE, + directory=True, + create=False, + ) + info = _win_info(child) + if not info[3] or info[2] & _FILE_ATTRIBUTE_REPARSE_POINT: + _win_close(child) + raise ValueError("task_apply_parent_unsafe") + handles.append(child) + return handles, path.name + except FileNotFoundError as exc: + for handle in reversed(handles[1:]): + _win_close(handle) + raise ValueError("task_apply_parent_missing") from exc + except BaseException: + for handle in reversed(handles[1:]): + _win_close(handle) + raise + + def inspect(self, relative: str) -> AnchoredFile: + if sys.platform == "win32": + return self._inspect_windows(relative) + return self._inspect_posix(relative) + + def _inspect_posix(self, relative: str) -> AnchoredFile: + parent, leaf = self._posix_parent(relative) + try: + return self._inspect_posix_at(parent, leaf, relative) + finally: + os.close(parent) + + def _inspect_posix_at(self, parent: int, leaf: str, relative: str) -> AnchoredFile: + parent_metadata = os.fstat(parent) + flags = os.O_RDONLY | _POSIX_NOFOLLOW + try: + descriptor = os.open(leaf, flags, dir_fd=parent) + except FileNotFoundError: + return AnchoredFile(relative, None, None, None, _posix_parent_identity(parent_metadata), None) + try: + before = os.fstat(descriptor) + if not stat.S_ISREG(before.st_mode) or before.st_nlink != 1: + raise ValueError("task_apply_target_unsafe") + if before.st_mode & (stat.S_ISUID | stat.S_ISGID | stat.S_ISVTX): + raise ValueError("task_apply_metadata_unsupported") + if int(getattr(before, "st_flags", 0)) != 0: + raise ValueError("task_apply_metadata_unsupported") + if _posix_xattrs(descriptor): + raise ValueError("task_apply_metadata_unsupported") + content = _bounded_read_fd(descriptor) + after = os.fstat(descriptor) + if _posix_xattrs(descriptor): + raise ValueError("task_apply_metadata_unsupported") + if int(getattr(after, "st_flags", 0)) != int(getattr(before, "st_flags", 0)): + raise ValueError("task_apply_source_changed") + if _posix_identity(before) != _posix_identity(after) or len(content) != before.st_size: + raise ValueError("task_apply_source_changed") + policy = { + "platform": "posix", "mode": stat.S_IMODE(before.st_mode), + "uid": int(before.st_uid), "gid": int(before.st_gid), + } + return AnchoredFile( + relative, content, digest_bytes(content), policy, + _posix_parent_identity(parent_metadata), _posix_identity(before), + ) + finally: + os.close(descriptor) + + def _inspect_windows(self, relative: str) -> AnchoredFile: + handles, leaf = self._windows_parent(relative) + try: + return self._inspect_windows_at(handles[-1], leaf, relative) + finally: + for handle in reversed(handles[1:]): + _win_close(handle) + + def _inspect_windows_at(self, parent: int, leaf: str, relative: str) -> AnchoredFile: + parent_info = _win_info(parent) + try: + handle = _nt_open_relative( + parent, leaf, _GENERIC_READ | _READ_CONTROL | _SYNCHRONIZE, + directory=False, create=False, + ) + except FileNotFoundError: + return AnchoredFile(relative, None, None, None, _win_parent_identity(parent_info), None) + try: + before = _win_info(handle) + allowed = _FILE_ATTRIBUTE_ARCHIVE | _FILE_ATTRIBUTE_NORMAL + if before[3] or before[2] & ~allowed or before[4] != 1: + raise ValueError("task_apply_metadata_unsupported") + _win_require_single_stream(handle) + content = _win_read(handle) + after = _win_info(handle) + if _win_identity(before) != _win_identity(after) or len(content) != before[5]: + raise ValueError("task_apply_source_changed") + policy = { + "platform": "windows", "attributes": before[2] & allowed, + "security": _win_security(handle).hex(), + } + return AnchoredFile( + relative, content, digest_bytes(content), policy, + _win_parent_identity(parent_info), _win_identity(before), + ) + finally: + _win_close(handle) + + def create_permission_policy(self) -> dict[str, object]: + if sys.platform == "win32": + return {"platform": "windows", "attributes": _FILE_ATTRIBUTE_NORMAL, "security": _win_owner_security().hex()} + return {"platform": "posix", "mode": 0o600, "uid": os.getuid(), "gid": os.getgid()} + + def replace( + self, + relative: str, + *, + expected_before_hash: str | None, + expected_parent_identity: dict[str, int], + expected_target_identity: dict[str, int] | None, + content: bytes, + permission_policy: dict[str, object], + application_id: str, + operation_index: int, + staged_callback: Callable[[dict[str, int]], None] | None = None, + rollback: bool = False, + ) -> AnchoredFile: + if len(content) > MAX_TASK_FILE_BYTES: + raise ValueError("task_apply_file_too_large") + if sys.platform == "win32": + return self._replace_windows( + relative, expected_before_hash, expected_parent_identity, expected_target_identity, + content, permission_policy, application_id, operation_index, + staged_callback, + rollback, + ) + return self._replace_posix( + relative, expected_before_hash, expected_parent_identity, expected_target_identity, + content, permission_policy, application_id, operation_index, + staged_callback, + rollback, + ) + + def _replace_posix( + self, + relative: str, + expected: str | None, + expected_parent: dict[str, int], + expected_target: dict[str, int] | None, + content: bytes, + policy: dict[str, object], + application_id: str, + index: int, + staged_callback: Callable[[dict[str, int]], None] | None, + rollback: bool, + ) -> AnchoredFile: + parent, leaf = self._posix_parent(relative) + temporary = ( + f".torq-rb-{application_id}-{index}.tmp" + if rollback else f".torq-{application_id}-{index}.tmp" + ) + descriptor: int | None = None + renamed = False + try: + before = self._inspect_posix_at(parent, leaf, relative) + if ( + before.content_hash != expected + or before.parent_identity != expected_parent + or before.target_identity != expected_target + ): + raise ValueError("task_apply_source_changed") + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | _POSIX_NOFOLLOW + descriptor = os.open(temporary, flags, 0o600, dir_fd=parent) + _write_all_fd(descriptor, content) + if policy.get("platform") != "posix": + raise ValueError("task_apply_permission_invalid") + _posix_apply_policy(descriptor, policy) + os.fsync(descriptor) + staged_identity = _posix_stable_identity(os.fstat(descriptor)) + os.close(descriptor) + descriptor = None + staged = self._inspect_posix_at(parent, temporary, relative) + if ( + staged.content_hash != digest_bytes(content) + or staged.target_identity is None + or {key: staged.target_identity[key] for key in ("volume", "file_id")} + != staged_identity + ): + raise ValueError("task_apply_staged_mismatch") + if staged_callback is not None: + staged_callback(staged_identity) + staged_recheck = self._inspect_posix_at(parent, temporary, relative) + if ( + staged_recheck.content_hash != digest_bytes(content) + or staged_recheck.target_identity is None + or {key: staged_recheck.target_identity[key] for key in ("volume", "file_id")} + != staged_identity + or _posix_parent_identity(os.fstat(parent)) != expected_parent + ): + raise ValueError("task_apply_staged_mismatch") + current = self._inspect_posix_at(parent, leaf, relative) + if current.content_hash != expected or current.target_identity != expected_target: + raise ValueError("task_apply_source_changed") + os.replace(temporary, leaf, src_dir_fd=parent, dst_dir_fd=parent) + renamed = True + os.fsync(parent) + result = self._inspect_posix_at(parent, leaf, relative) + if ( + result.content_hash != digest_bytes(content) + or result.target_identity is None + or {key: result.target_identity[key] for key in ("volume", "file_id")} + != staged_identity + ): + raise ValueError("task_apply_result_mismatch") + finally: + if descriptor is not None: + os.close(descriptor) + if not renamed: + try: + os.unlink(temporary, dir_fd=parent) + os.fsync(parent) + except FileNotFoundError: + pass + os.close(parent) + return result + + def _replace_windows( + self, + relative: str, + expected: str | None, + expected_parent: dict[str, int], + expected_target: dict[str, int] | None, + content: bytes, + policy: dict[str, object], + application_id: str, + index: int, + staged_callback: Callable[[dict[str, int]], None] | None, + rollback: bool, + ) -> AnchoredFile: + handles, leaf = self._windows_parent(relative) + temporary = ( + f".torq-rb-{application_id}-{index}.tmp" + if rollback else f".torq-{application_id}-{index}.tmp" + ) + temp_handle: int | None = None + renamed = False + try: + before = self._inspect_windows_at(handles[-1], leaf, relative) + if ( + before.content_hash != expected + or before.parent_identity != expected_parent + or before.target_identity != expected_target + ): + raise ValueError("task_apply_source_changed") + temp_handle = _nt_open_relative( + handles[-1], + temporary, + _GENERIC_READ | _GENERIC_WRITE | _DELETE | _READ_CONTROL | _WRITE_DAC | _WRITE_OWNER | _SYNCHRONIZE, + directory=False, + create=True, + ) + _win_write(temp_handle, content) + if policy.get("platform") != "windows" or not isinstance(policy.get("security"), str): + raise ValueError("task_apply_permission_invalid") + _win_set_security(temp_handle, bytes.fromhex(str(policy["security"]))) + _win_set_attributes(temp_handle, policy.get("attributes")) + _win_flush(temp_handle) + staged_identity = _win_stable_identity(_win_info(temp_handle)) + staged = self._inspect_windows_at(handles[-1], temporary, relative) + if ( + staged.content_hash != digest_bytes(content) + or staged.target_identity is None + or {key: staged.target_identity[key] for key in ("volume", "file_id")} + != staged_identity + ): + raise ValueError("task_apply_staged_mismatch") + if staged_callback is not None: + staged_callback(staged_identity) + staged_recheck = self._inspect_windows_at(handles[-1], temporary, relative) + if ( + staged_recheck.content_hash != digest_bytes(content) + or staged_recheck.target_identity is None + or {key: staged_recheck.target_identity[key] for key in ("volume", "file_id")} + != staged_identity + or _win_parent_identity(_win_info(handles[-1])) != expected_parent + ): + raise ValueError("task_apply_staged_mismatch") + current = self._inspect_windows_at(handles[-1], leaf, relative) + if current.content_hash != expected or current.target_identity != expected_target: + raise ValueError("task_apply_source_changed") + _win_rename_relative(temp_handle, handles[-1], leaf, replace=expected is not None) + renamed = True + _win_flush(handles[-1]) + result = self._inspect_windows_at(handles[-1], leaf, relative) + if ( + result.content_hash != digest_bytes(content) + or result.target_identity is None + or {key: result.target_identity[key] for key in ("volume", "file_id")} + != staged_identity + ): + raise ValueError("task_apply_result_mismatch") + finally: + if temp_handle is not None: + if not renamed: + try: + _win_delete(temp_handle) + except OSError: + pass + _win_close(temp_handle) + for handle in reversed(handles[1:]): + _win_close(handle) + return result + + def remove( + self, + relative: str, + *, + expected_hash: str, + expected_parent_identity: dict[str, int], + expected_target_identity: dict[str, int], + ) -> None: + if sys.platform == "win32": + handles, leaf = self._windows_parent(relative) + try: + parent_info = _win_info(handles[-1]) + if _win_parent_identity(parent_info) != expected_parent_identity: + raise ValueError("task_apply_recovery_conflict") + handle = _nt_open_relative( + handles[-1], leaf, _GENERIC_READ | _DELETE | _READ_CONTROL | _SYNCHRONIZE, + directory=False, create=False, + ) + try: + before = _win_info(handle) + content = _win_read(handle) + after = _win_info(handle) + if ( + _win_identity(before) != expected_target_identity + or _win_identity(before) != _win_identity(after) + or digest_bytes(content) != expected_hash + ): + raise ValueError("task_apply_recovery_conflict") + _win_delete(handle) + finally: + _win_close(handle) + _win_flush(handles[-1]) + finally: + for handle in reversed(handles[1:]): + _win_close(handle) + else: + parent, leaf = self._posix_parent(relative) + try: + current = self._inspect_posix_at(parent, leaf, relative) + if ( + current.content_hash != expected_hash + or current.parent_identity != expected_parent_identity + or current.target_identity != expected_target_identity + ): + raise ValueError("task_apply_recovery_conflict") + os.unlink(leaf, dir_fd=parent) + os.fsync(parent) + finally: + os.close(parent) + + @staticmethod + def _staged_leaf(application_id: str, operation_index: int) -> str: + if ( + re.fullmatch(r"application-[a-f0-9]{24}", application_id) is None + or not isinstance(operation_index, int) + or isinstance(operation_index, bool) + or operation_index < 0 + or operation_index >= MAX_TASK_FILES + ): + raise ValueError("task_apply_staged_name_invalid") + return f".torq-{application_id}-{operation_index}.tmp" + + def inspect_staged( + self, relative: str, *, application_id: str, operation_index: int + ) -> AnchoredFile: + temporary = self._staged_leaf(application_id, operation_index) + if sys.platform == "win32": + handles, _leaf = self._windows_parent(relative) + try: + return self._inspect_windows_at(handles[-1], temporary, relative) + finally: + for handle in reversed(handles[1:]): + _win_close(handle) + parent, _leaf = self._posix_parent(relative) + try: + return self._inspect_posix_at(parent, temporary, relative) + finally: + os.close(parent) + + def inspect_rollback_staged( + self, relative: str, *, application_id: str, operation_index: int + ) -> AnchoredFile: + self._staged_leaf(application_id, operation_index) + temporary = f".torq-rb-{application_id}-{operation_index}.tmp" + if sys.platform == "win32": + handles, _leaf = self._windows_parent(relative) + try: + return self._inspect_windows_at(handles[-1], temporary, relative) + finally: + for handle in reversed(handles[1:]): + _win_close(handle) + parent, _leaf = self._posix_parent(relative) + try: + return self._inspect_posix_at(parent, temporary, relative) + finally: + os.close(parent) + + def commit_rollback_staged( + self, + relative: str, + *, + application_id: str, + operation_index: int, + expected_before_hash: str, + expected_before_identity: dict[str, int], + expected_parent_identity: dict[str, int], + staged_hash: str, + staged_identity: dict[str, int], + permission_policy: dict[str, object], + ) -> AnchoredFile: + self._staged_leaf(application_id, operation_index) + temporary = f".torq-rb-{application_id}-{operation_index}.tmp" + if sys.platform == "win32": + handles, leaf = self._windows_parent(relative) + temp_handle: int | None = None + try: + current = self._inspect_windows_at(handles[-1], leaf, relative) + staged = self._inspect_windows_at(handles[-1], temporary, relative) + if ( + current.content_hash != expected_before_hash + or current.target_identity != expected_before_identity + or current.parent_identity != expected_parent_identity + or staged.content_hash != staged_hash + or staged.target_identity is None + or {key: staged.target_identity[key] for key in ("volume", "file_id")} + != staged_identity + or staged.parent_identity != expected_parent_identity + or staged.permission_policy != permission_policy + ): + raise ValueError("task_apply_recovery_conflict") + temp_handle = _nt_open_relative( + handles[-1], temporary, + _GENERIC_READ | _DELETE | _READ_CONTROL | _SYNCHRONIZE, + directory=False, create=False, + ) + _win_rename_relative(temp_handle, handles[-1], leaf, replace=True) + _win_flush(handles[-1]) + result = self._inspect_windows_at(handles[-1], leaf, relative) + finally: + if temp_handle is not None: + _win_close(temp_handle) + for handle in reversed(handles[1:]): + _win_close(handle) + else: + parent, leaf = self._posix_parent(relative) + try: + current = self._inspect_posix_at(parent, leaf, relative) + staged = self._inspect_posix_at(parent, temporary, relative) + if ( + current.content_hash != expected_before_hash + or current.target_identity != expected_before_identity + or current.parent_identity != expected_parent_identity + or staged.content_hash != staged_hash + or staged.target_identity is None + or {key: staged.target_identity[key] for key in ("volume", "file_id")} + != staged_identity + or staged.parent_identity != expected_parent_identity + or staged.permission_policy != permission_policy + ): + raise ValueError("task_apply_recovery_conflict") + os.replace(temporary, leaf, src_dir_fd=parent, dst_dir_fd=parent) + os.fsync(parent) + result = self._inspect_posix_at(parent, leaf, relative) + finally: + os.close(parent) + if ( + result.content_hash != staged_hash + or result.target_identity is None + or {key: result.target_identity[key] for key in ("volume", "file_id")} + != staged_identity + ): + raise ValueError("task_apply_recovery_conflict") + return result + + def remove_staged( + self, + relative: str, + *, + application_id: str, + operation_index: int, + expected_hash: str, + expected_parent_identity: dict[str, int], + expected_target_identity: dict[str, int], + ) -> None: + temporary = self._staged_leaf(application_id, operation_index) + if sys.platform == "win32": + handles, _leaf = self._windows_parent(relative) + try: + if _win_parent_identity(_win_info(handles[-1])) != expected_parent_identity: + raise ValueError("task_apply_recovery_conflict") + handle = _nt_open_relative( + handles[-1], temporary, + _GENERIC_READ | _DELETE | _READ_CONTROL | _SYNCHRONIZE, + directory=False, create=False, + ) + try: + before = _win_info(handle) + content = _win_read(handle) + after = _win_info(handle) + if ( + _win_identity(before) != expected_target_identity + or _win_identity(before) != _win_identity(after) + or digest_bytes(content) != expected_hash + ): + raise ValueError("task_apply_recovery_conflict") + _win_delete(handle) + finally: + _win_close(handle) + _win_flush(handles[-1]) + finally: + for handle in reversed(handles[1:]): + _win_close(handle) + return + parent, _leaf = self._posix_parent(relative) + try: + current = self._inspect_posix_at(parent, temporary, relative) + if ( + current.content_hash != expected_hash + or current.parent_identity != expected_parent_identity + or current.target_identity != expected_target_identity + ): + raise ValueError("task_apply_recovery_conflict") + os.unlink(temporary, dir_fd=parent) + os.fsync(parent) + finally: + os.close(parent) + + def close(self) -> None: + if self._closed: + return + self._closed = True + if sys.platform == "win32": + if self._mutex is not None: + _win_release_mutex(self._mutex) + _win_close(self._mutex) + if self._root_handle is not None: + _win_close(self._root_handle) + elif self._root_handle is not None: + _posix_lock(self._root_handle, release=True) + os.close(self._root_handle) + + def __enter__(self) -> AnchoredPrimary: + return self + + def __exit__(self, *_args: object) -> None: + self.close() + + +# Windows native declarations are kept in this module so the public boundary +# has no pathname fallback once the primary root is held. +_GENERIC_READ = 0x80000000 +_GENERIC_WRITE = 0x40000000 +_DELETE = 0x00010000 +_READ_CONTROL = 0x00020000 +_WRITE_DAC = 0x00040000 +_WRITE_OWNER = 0x00080000 +_SYNCHRONIZE = 0x00100000 +_FILE_SHARE_ALL = 0x00000007 +_OPEN_EXISTING = 3 +_FILE_CREATE = 2 +_FILE_OPEN = 1 +_FILE_ATTRIBUTE_NORMAL = 0x00000080 +_FILE_ATTRIBUTE_READONLY = 0x00000001 +_FILE_ATTRIBUTE_ARCHIVE = 0x00000020 +_FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400 +_FILE_ATTRIBUTE_ENCRYPTED = 0x00004000 +_FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 +_FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 +_FILE_DIRECTORY_FILE = 0x00000001 +_FILE_NON_DIRECTORY_FILE = 0x00000040 +_FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020 +_FILE_OPEN_REPARSE_POINT = 0x00200000 +_OBJ_CASE_INSENSITIVE = 0x00000040 +_WAIT_OBJECT_0 = 0 + + +class _WinFileTime(ctypes.Structure): + _fields_ = [("low", ctypes.c_uint32), ("high", ctypes.c_uint32)] + + +class _WinFileInfo(ctypes.Structure): + _fields_ = [ + ("attributes", ctypes.c_uint32), ("created", _WinFileTime), ("accessed", _WinFileTime), + ("written", _WinFileTime), ("volume", ctypes.c_uint32), ("size_high", ctypes.c_uint32), + ("size_low", ctypes.c_uint32), ("links", ctypes.c_uint32), + ("index_high", ctypes.c_uint32), ("index_low", ctypes.c_uint32), + ] + + +class _UnicodeString(ctypes.Structure): + _fields_ = [("Length", ctypes.c_ushort), ("MaximumLength", ctypes.c_ushort), ("Buffer", ctypes.c_void_p)] + + +class _ObjectAttributes(ctypes.Structure): + _fields_ = [ + ("Length", ctypes.c_ulong), ("RootDirectory", ctypes.c_void_p), + ("ObjectName", ctypes.POINTER(_UnicodeString)), ("Attributes", ctypes.c_ulong), + ("SecurityDescriptor", ctypes.c_void_p), ("SecurityQualityOfService", ctypes.c_void_p), + ] + + +class _IoStatusBlock(ctypes.Structure): + _fields_ = [("Status", ctypes.c_void_p), ("Information", ctypes.c_size_t)] + + +class _FileRenameInfo(ctypes.Structure): + _fields_ = [ + ("ReplaceIfExists", ctypes.c_int), ("RootDirectory", ctypes.c_void_p), + ("FileNameLength", ctypes.c_uint32), ("FileName", ctypes.c_wchar * 1), + ] + + +def _win_dll(name: str) -> Any: + factory = getattr(ctypes, "WinDLL", None) + if factory is None: + raise RuntimeError("task_apply_platform_unsupported") + return factory(name, use_last_error=True) + + +def _win_last_error() -> int: + getter = getattr(ctypes, "get_last_error", None) + return int(getter()) if getter is not None else 0 + + +def _kernel32() -> Any: + return _win_dll("kernel32") + + +def _advapi32() -> Any: + return _win_dll("advapi32") + + +def _win_open_path(path: str, access: int, disposition: int, flags: int) -> int: + create = _kernel32().CreateFileW + create.argtypes = [ctypes.c_wchar_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_void_p] + create.restype = ctypes.c_void_p + handle = create(path, access, _FILE_SHARE_ALL, None, disposition, flags, None) + if handle in (None, ctypes.c_void_p(-1).value): + error = _win_last_error() + raise OSError(error, "CreateFileW failed") + return int(handle) + + +def _nt_open_relative(parent: int, name: str, access: int, *, directory: bool, create: bool) -> int: + buffer = ctypes.create_unicode_buffer(name) + encoded_bytes = len(name.encode("utf-16-le")) + unicode_name = _UnicodeString(encoded_bytes, encoded_bytes + 2, ctypes.cast(buffer, ctypes.c_void_p)) + attributes = _ObjectAttributes( + ctypes.sizeof(_ObjectAttributes), ctypes.c_void_p(parent), ctypes.pointer(unicode_name), + _OBJ_CASE_INSENSITIVE, None, None, + ) + io = _IoStatusBlock() + result = ctypes.c_void_p() + ntdll = _win_dll("ntdll") + call = ntdll.NtCreateFile + call.argtypes = [ + ctypes.POINTER(ctypes.c_void_p), ctypes.c_uint32, ctypes.POINTER(_ObjectAttributes), + ctypes.POINTER(_IoStatusBlock), ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, + ctypes.c_uint32, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_uint32, + ] + call.restype = ctypes.c_long + options = (_FILE_DIRECTORY_FILE if directory else _FILE_NON_DIRECTORY_FILE) | _FILE_SYNCHRONOUS_IO_NONALERT | _FILE_OPEN_REPARSE_POINT + status = call( + ctypes.byref(result), access, ctypes.byref(attributes), ctypes.byref(io), None, + _FILE_ATTRIBUTE_NORMAL, _FILE_SHARE_ALL, _FILE_CREATE if create else _FILE_OPEN, + options, None, 0, + ) + if status < 0 or result.value is None: + converter = ntdll.RtlNtStatusToDosError + converter.argtypes = [ctypes.c_long] + converter.restype = ctypes.c_ulong + error = int(converter(status)) + if error in {2, 3}: + raise FileNotFoundError(error, name) + if error in {80, 183}: + raise FileExistsError(error, name) + raise OSError(error, f"NtCreateFile failed: {name}") + return int(result.value) + + +def _win_info(handle: int) -> tuple[int, int, int, bool, int, int, int]: + info = _WinFileInfo() + call = _kernel32().GetFileInformationByHandle + if not call(ctypes.c_void_p(handle), ctypes.byref(info)): + raise OSError(_win_last_error(), "GetFileInformationByHandle failed") + file_id = (info.index_high << 32) | info.index_low + is_directory = bool(info.attributes & 0x10) + size = (info.size_high << 32) | info.size_low + modified = (info.written.high << 32) | info.written.low + return ( + int(info.volume), int(file_id), int(info.attributes), is_directory, + int(info.links), int(size), int(modified), + ) + + +def _win_read(handle: int) -> bytes: + call = _kernel32().ReadFile + result = bytearray() + while len(result) <= MAX_TASK_FILE_BYTES: + buffer = ctypes.create_string_buffer(min(_READ_CHUNK, MAX_TASK_FILE_BYTES + 1 - len(result))) + count = ctypes.c_uint32() + if not call(ctypes.c_void_p(handle), buffer, len(buffer), ctypes.byref(count), None): + raise OSError(_win_last_error(), "ReadFile failed") + if count.value == 0: + break + result.extend(buffer.raw[: count.value]) + if len(result) > MAX_TASK_FILE_BYTES: + raise ValueError("task_apply_file_too_large") + return bytes(result) + + +def _win_write(handle: int, content: bytes) -> None: + call = _kernel32().WriteFile + offset = 0 + while offset < len(content): + chunk = content[offset : offset + _READ_CHUNK] + buffer = ctypes.create_string_buffer(chunk) + count = ctypes.c_uint32() + if not call(ctypes.c_void_p(handle), buffer, len(chunk), ctypes.byref(count), None): + raise OSError(_win_last_error(), "WriteFile failed") + if count.value == 0: + raise OSError("WriteFile made no progress") + offset += count.value + + +def _win_flush(handle: int) -> None: + if not _kernel32().FlushFileBuffers(ctypes.c_void_p(handle)): + error = _win_last_error() + # Directory handles commonly reject FlushFileBuffers; no weaker path + # rename is introduced, and file data is already flushed. + if error not in {1, 5, 87}: + raise OSError(error, "FlushFileBuffers failed") + + +def _win_security(handle: int) -> bytes: + requested = 0x00000001 | 0x00000002 | 0x00000004 + needed = ctypes.c_uint32() + call = _advapi32().GetKernelObjectSecurity + call(ctypes.c_void_p(handle), requested, None, 0, ctypes.byref(needed)) + if needed.value == 0: + raise OSError(_win_last_error(), "GetKernelObjectSecurity size failed") + buffer = ctypes.create_string_buffer(needed.value) + if not call(ctypes.c_void_p(handle), requested, buffer, len(buffer), ctypes.byref(needed)): + raise OSError(_win_last_error(), "GetKernelObjectSecurity failed") + # Auto-inheritance control flags describe how Windows obtained the DACL, + # not the owner/group/DACL authority that this policy preserves. Setting a + # copied descriptor can legitimately clear these flags, so normalize them + # before binding or comparing the policy. + normalize = _advapi32().SetSecurityDescriptorControl + normalize.argtypes = [ctypes.c_void_p, ctypes.c_ushort, ctypes.c_ushort] + normalize.restype = ctypes.c_int + if not normalize(buffer, 0x0C00, 0): + raise OSError(_win_last_error(), "SetSecurityDescriptorControl failed") + return buffer.raw[: needed.value] + + +def _win_set_security(handle: int, descriptor: bytes) -> None: + requested = 0x00000001 | 0x00000002 | 0x00000004 + buffer = ctypes.create_string_buffer(descriptor) + if not _advapi32().SetKernelObjectSecurity(ctypes.c_void_p(handle), requested, buffer): + raise OSError(_win_last_error(), "SetKernelObjectSecurity failed") + + +def _win_current_user_sid_string() -> str: + token_query = 0x0008 + token_user = 1 + token = ctypes.c_void_p() + current = _kernel32().GetCurrentProcess + current.argtypes = [] + current.restype = ctypes.c_void_p + open_token = _advapi32().OpenProcessToken + open_token.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.POINTER(ctypes.c_void_p)] + open_token.restype = ctypes.c_int + if not open_token(current(), token_query, ctypes.byref(token)): + raise OSError(_win_last_error(), "OpenProcessToken failed") + try: + needed = ctypes.c_uint32() + get_information = _advapi32().GetTokenInformation + get_information.argtypes = [ + ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32, + ctypes.POINTER(ctypes.c_uint32), + ] + get_information.restype = ctypes.c_int + get_information(token, token_user, None, 0, ctypes.byref(needed)) + if needed.value == 0: + raise OSError(_win_last_error(), "GetTokenInformation size failed") + buffer = ctypes.create_string_buffer(needed.value) + if not get_information( + token, token_user, buffer, len(buffer), ctypes.byref(needed) + ): + raise OSError(_win_last_error(), "GetTokenInformation failed") + sid = ctypes.c_void_p.from_buffer(buffer).value + rendered = ctypes.c_wchar_p() + convert_sid = _advapi32().ConvertSidToStringSidW + convert_sid.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_wchar_p)] + convert_sid.restype = ctypes.c_int + if not convert_sid(sid, ctypes.byref(rendered)): + raise OSError(_win_last_error(), "ConvertSidToStringSidW failed") + try: + if rendered.value is None: + raise OSError("ConvertSidToStringSidW returned no value") + return rendered.value + finally: + _kernel32().LocalFree(rendered) + finally: + if token.value is not None: + _win_close(int(token.value)) + + +def _win_owner_security() -> bytes: + sid = _win_current_user_sid_string() + sddl = f"O:{sid}G:{sid}D:P(A;;FA;;;{sid})" + descriptor = ctypes.c_void_p() + convert = _advapi32().ConvertStringSecurityDescriptorToSecurityDescriptorW + convert.argtypes = [ + ctypes.c_wchar_p, ctypes.c_uint32, ctypes.POINTER(ctypes.c_void_p), + ctypes.POINTER(ctypes.c_uint32), + ] + convert.restype = ctypes.c_int + if not convert( + ctypes.c_wchar_p(sddl), 1, ctypes.byref(descriptor), None + ): + raise OSError( + _win_last_error(), + "ConvertStringSecurityDescriptorToSecurityDescriptorW failed", + ) + try: + get_length = _advapi32().GetSecurityDescriptorLength + get_length.argtypes = [ctypes.c_void_p] + get_length.restype = ctypes.c_uint32 + length = get_length(descriptor) + if not isinstance(length, int) or length <= 0: + raise OSError(_win_last_error(), "GetSecurityDescriptorLength failed") + return ctypes.string_at(descriptor, length) + finally: + _kernel32().LocalFree(descriptor) + + +class _WinBasicInfo(ctypes.Structure): + _fields_ = [ + ("CreationTime", ctypes.c_int64), + ("LastAccessTime", ctypes.c_int64), + ("LastWriteTime", ctypes.c_int64), + ("ChangeTime", ctypes.c_int64), + ("FileAttributes", ctypes.c_uint32), + ] + + +def _win_set_attributes(handle: int, value: object) -> None: + allowed = _FILE_ATTRIBUTE_ARCHIVE | _FILE_ATTRIBUTE_NORMAL + if not isinstance(value, int) or isinstance(value, bool) or value & ~allowed: + raise ValueError("task_apply_permission_invalid") + info = _WinBasicInfo(0, 0, 0, 0, value) + if not _kernel32().SetFileInformationByHandle( + ctypes.c_void_p(handle), 0, ctypes.byref(info), ctypes.sizeof(info) + ): + raise OSError(_win_last_error(), "FileBasicInfo failed") + + +def _win_require_single_stream(handle: int) -> None: + # FILE_STREAM_INFO names include the unnamed stream as ::$DATA. + buffer = ctypes.create_string_buffer(4096) + call = _kernel32().GetFileInformationByHandleEx + if not call(ctypes.c_void_p(handle), 7, buffer, len(buffer)): + raise OSError(_win_last_error(), "FileStreamInfo failed") + offset = 0 + names: list[str] = [] + while True: + next_offset = int.from_bytes(buffer.raw[offset : offset + 4], "little") + name_length = int.from_bytes(buffer.raw[offset + 4 : offset + 8], "little") + name = buffer.raw[offset + 24 : offset + 24 + name_length].decode("utf-16-le") + names.append(name) + if next_offset == 0: + break + offset += next_offset + if offset >= len(buffer): + raise ValueError("task_apply_metadata_unsupported") + if names != ["::$DATA"]: + raise ValueError("task_apply_metadata_unsupported") + + +def _win_rename_relative(handle: int, parent: int, name: str, *, replace: bool) -> None: + encoded = name.encode("utf-16-le") + offset = _FileRenameInfo.FileName.offset + buffer = ctypes.create_string_buffer(ctypes.sizeof(_FileRenameInfo) + len(encoded)) + header = _FileRenameInfo.from_buffer(buffer) + header.ReplaceIfExists = int(replace) + header.RootDirectory = ctypes.c_void_p(parent) + header.FileNameLength = len(encoded) + ctypes.memmove(ctypes.addressof(buffer) + offset, encoded, len(encoded)) + io = _IoStatusBlock() + ntdll = _win_dll("ntdll") + call = ntdll.NtSetInformationFile + call.argtypes = [ctypes.c_void_p, ctypes.POINTER(_IoStatusBlock), ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int] + call.restype = ctypes.c_long + status = call(ctypes.c_void_p(handle), ctypes.byref(io), buffer, len(buffer), 10) + if status < 0: + converter = ntdll.RtlNtStatusToDosError + converter.argtypes = [ctypes.c_long] + converter.restype = ctypes.c_ulong + raise OSError(int(converter(status)), "FileRenameInformation failed") + + +def _win_delete(handle: int) -> None: + value = ctypes.c_ubyte(1) + if not _kernel32().SetFileInformationByHandle(ctypes.c_void_p(handle), 4, ctypes.byref(value), 1): + raise OSError(_win_last_error(), "FileDispositionInfo failed") + + +def _win_mutex(name: str) -> int: + kernel = _kernel32() + call = kernel.CreateMutexW + call.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_wchar_p] + call.restype = ctypes.c_void_p + handle = call(None, 0, name) + if handle in (None, ctypes.c_void_p(-1).value): + raise OSError(_win_last_error(), "CreateMutexW failed") + already_exists = _win_last_error() == 183 + if already_exists: + _win_close(int(handle)) + raise RuntimeError("task_apply_primary_busy") + wait = kernel.WaitForSingleObject(ctypes.c_void_p(handle), 0) + if wait != _WAIT_OBJECT_0: + _win_close(int(handle)) + raise RuntimeError("task_apply_primary_busy") + return int(handle) + + +def _win_release_mutex(handle: int) -> None: + if not _kernel32().ReleaseMutex(ctypes.c_void_p(handle)): + raise OSError(_win_last_error(), "ReleaseMutex failed") + + +def _win_close(handle: int) -> None: + if not _kernel32().CloseHandle(ctypes.c_void_p(handle)): + raise OSError(_win_last_error(), "CloseHandle failed") + + +__all__ = ["AnchoredFile", "AnchoredPrimary", "PrimaryIdentity"] diff --git a/src/torq_cli/safety/receipts.py b/src/torq_cli/safety/receipts.py index 1dc7aba..d71b24c 100644 --- a/src/torq_cli/safety/receipts.py +++ b/src/torq_cli/safety/receipts.py @@ -144,6 +144,19 @@ def _canonical_for_verification(value: Mapping[str, Any]) -> bytes: ).encode() +def _nested_artifact_references(payload: Mapping[str, Any]) -> tuple[Mapping[str, Any], ...]: + detail = payload.get("detail") + if not isinstance(detail, Mapping): + return () + if payload.get("review_contract") == "torq-candidate-review-v1" and payload.get("event") == "candidate_accepted": + reference = detail.get("review_artifact") + return (reference,) if isinstance(reference, Mapping) else () + if payload.get("apply_contract") == "torq-candidate-apply-v1" and payload.get("event") == "apply_prepared": + reference = detail.get("journal_artifact") + return (reference,) if isinstance(reference, Mapping) else () + return () + + def _canonical_json(value: Mapping[str, Any]) -> str: return _canonical(value).decode("ascii") @@ -844,6 +857,10 @@ def get_or_create(self, run_id: str) -> bytes: _restrict_private_key(self.private_key_path) return key + def load_signing_key(self) -> bytes: + """Load the installation signing key without creating or chmod-ing it.""" + return self._read_regular_key(self.private_key_path) + @staticmethod def _get_or_create_secret(path: Path) -> bytes: try: @@ -988,6 +1005,53 @@ def __init__( if self._rollback_protected: self._initialize_or_resume_anchored_store() + @classmethod + def open_existing( + cls, + evidence_root: Path, + run_id: str, + keys: FileRunKeyStore, + *, + profile_version: str, + policy_version: str, + ) -> ReceiptChain: + """Open one covered existing chain without creating identity or evidence.""" + if not _valid_run_id(run_id): + raise ValueError("run_id_invalid") + root = evidence_root / run_id + if root.resolve(strict=True).parent != evidence_root.resolve(strict=True): + raise ValueError("run_id_invalid") + verification = verify_receipt_store(root) + if verification.status != "verified": + raise ValueError("receipt_store_not_writable:" + str(verification.finding or verification.status)) + manifest = json.loads((root / "terminal-manifest.json").read_text(encoding="utf-8")) + certificate_path = root / _RUN_CERTIFICATE_NAME + certificate = json.loads(certificate_path.read_text(encoding="utf-8")) + if ( + not isinstance(manifest, Mapping) + or not isinstance(certificate, Mapping) + or certificate.get("certificate_schema_version") not in _ROLLBACK_CERTIFICATE_SCHEMA_VERSIONS + ): + raise ValueError("receipt_store_not_writable:certificate_invalid") + self = cls.__new__(cls) + self.run_id = run_id + self.root = root + self.receipts_path = root / "receipts.jsonl" + self.key = keys.load_signing_key() + self._commit_observer = None + self.run_keys = keys.load_run_keys(run_id) + self.certificate_path = certificate_path + self.profile_version = profile_version + self.policy_version = policy_version + self.registry = PatternRegistry.default() + self._lock = RLock() + self._sequence = int(manifest["receipt_count"]) + self._previous = manifest.get("terminal_receipt_hash") + self._sealed = bool(manifest.get("sealed")) + self._manifest_generation = int(manifest["manifest_generation"]) + self._rollback_protected = True + return self + def _pin_signing_identity(self, evidence_root: Path) -> None: public_key = Ed25519PrivateKey.from_private_bytes(self.key).public_key().public_bytes_raw() pin_path = evidence_root / _PUBLIC_KEY_NAME @@ -1288,6 +1352,16 @@ def _recover_authenticated_uncovered_tail(self) -> None: or self.hash_file(artifact) != payload.get("artifact_hash") ): raise ValueError("uncovered_tail_artifact_invalid") + if isinstance(payload, Mapping): + resolved_root = self.root.resolve() + for reference in _nested_artifact_references(payload): + artifact = (resolved_root / str(reference.get("artifact"))).resolve(strict=False) + if ( + not artifact.is_relative_to(resolved_root) + or not artifact.exists() + or self.hash_file(artifact) != reference.get("artifact_hash") + ): + raise ValueError("uncovered_tail_artifact_invalid") previous = receipt_hash lifecycle_finding = validate_v2_receipt_contract(receipts, sealed=False) if lifecycle_finding is not None: @@ -1799,6 +1873,14 @@ def verify_receipt_store( return StoreVerification("tampered", "artifact_path_escape") if not artifact.exists() or ReceiptChain.hash_file(artifact) != payload.get("artifact_hash"): return StoreVerification("tampered", "artifact_hash_mismatch") + if isinstance(payload, Mapping): + resolved_root = root.resolve() + for reference in _nested_artifact_references(payload): + artifact = (resolved_root / str(reference.get("artifact"))).resolve(strict=False) + if not artifact.is_relative_to(resolved_root): + return StoreVerification("tampered", "artifact_path_escape") + if not artifact.exists() or ReceiptChain.hash_file(artifact) != reference.get("artifact_hash"): + return StoreVerification("tampered", "artifact_hash_mismatch") previous = receipt_hash receipts.append(envelope) @@ -2089,3 +2171,34 @@ def read_verified_artifact( run_id.encode("utf-8"), ) return plain + + +def read_verified_prefix_artifact( + evidence_root: Path, + run_id: str, + artifact_relative: str, +) -> bytes: + """Read an artifact from an authenticated covered unsealed recovery prefix.""" + if not _valid_run_id(run_id): + raise ValueError("run_id_invalid") + run_root = evidence_root / run_id + verification = verify_receipt_store(run_root) + if verification.status != "verified": + raise ValueError("artifact_store_not_verified") + manifest = json.loads((run_root / "terminal-manifest.json").read_text(encoding="utf-8")) + if not isinstance(manifest, dict) or manifest.get("sealed") is not False: + raise ValueError("artifact_store_not_recovery_prefix") + target = (run_root / artifact_relative).resolve(strict=True) + if not target.is_relative_to(run_root.resolve()): + raise ValueError("artifact_path_escape") + metadata = target.stat(follow_symlinks=False) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1 or target.is_symlink(): + raise ValueError("artifact_file_unsafe") + payload = target.read_bytes() + if not payload.startswith(_ARTIFACT_FORMAT) or len(payload) < 38: + raise ValueError("artifact_format_invalid") + keys = FileRunKeyStore(evidence_root).load_run_keys(run_id) + offset = len(_ARTIFACT_FORMAT) + return AESGCM(keys.artifact).decrypt( + payload[offset : offset + 12], payload[offset + 12 :], run_id.encode("utf-8") + ) diff --git a/tests/js/task_resume.test.cjs b/tests/js/task_resume.test.cjs index 1f713b9..a3b9fde 100644 --- a/tests/js/task_resume.test.cjs +++ b/tests/js/task_resume.test.cjs @@ -12,16 +12,28 @@ class Element { } addEventListener(name, fn) { (this.listeners[name] ||= []).push(fn); } async dispatch(name) { await Promise.all((this.listeners[name] || []).map((fn) => fn({target:this, preventDefault(){}}))); } - setAttribute() {} focus() {} querySelectorAll() { return []; } + setAttribute() {} focus() {} querySelector() { return null; } querySelectorAll() { return []; } } const ids = [ "task-view", "task-view-button", "workspace-view", "fleet-board", "workspace-view-button", "fleet-view-button", "skip-link", "task-draft-status", "task-project", "task-goal", "task-input-paths", "task-output-paths", "task-start", "task-plan-summary", "task-form", "task-clear", "task-review", "task-stop", "task-current", - "task-history-list" + "task-history-list", "task-history-search", "task-history-query", "task-history-more", "live-announcer", + "task-compose-view", "task-review-view", "review-back", "review-title", "review-goal", "review-identity", + "review-state", "review-alert", "review-tab-plan", "review-tab-changes", "review-tab-checks", + "review-panel-plan", "review-panel-changes", "review-panel-checks", "review-change-count", "review-files", + "review-diff", "review-correction", "review-correction-status", "review-correction-plan", "review-child-plan", + "review-start-revision", "review-accept", "review-apply-section", "review-apply", "review-apply-copy", + "review-continue-section", "review-continue", "review-hashes" + , "task-recovery-panel", "task-recovery-title", "task-recovery-message", "task-recover" ]; const elements = Object.fromEntries(ids.map((id) => [id, new Element(id)])); -const document = {body:new Element("body"), getElementById:(id) => elements[id] || null}; +["plan", "changes", "checks"].forEach((name) => { elements[`review-tab-${name}`].dataset.reviewTab = name; }); +const document = { + body:new Element("body"), + getElementById:(id) => elements[id] || null, + querySelectorAll:(selector) => selector === "[data-review-tab]" ? [elements["review-tab-plan"], elements["review-tab-changes"], elements["review-tab-checks"]] : [], +}; const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); let capabilityCalls = 0; async function fetch(path, options = {}) { @@ -41,6 +53,8 @@ async function fetch(path, options = {}) { return {ok:true, json:async () => ({result:{project_id:"project", goal:"next", input_paths:[], output_paths:["next.py"], revision:3}})}; } if (path === "/api/v1/tasks" && method === "GET") return {ok:true, json:async () => ({tasks:[]})}; + if (path === "/api/v1/task-history?q=&limit=50" && method === "GET") return {ok:true, json:async () => ({schema:"torq-candidate-history-v1", items:[], next_cursor:null})}; + if (path === "/api/v1/task-recovery/project" && method === "GET") return {ok:true, json:async () => ({schema:"torq-task-recovery-v1", state:"idle", owned:false, finding:null, application_id:null})}; if (path === "/api/v1/tasks/active-1") { return {ok:true, json:async () => ({task:{task_id:"active-1", state:"candidate_ready", verified:true, candidate_files:["old.py"], check:{exit_code:0}}})}; } diff --git a/tests/js/task_runtime.test.cjs b/tests/js/task_runtime.test.cjs index 26a26f9..76c0c8f 100644 --- a/tests/js/task_runtime.test.cjs +++ b/tests/js/task_runtime.test.cjs @@ -14,7 +14,7 @@ const context = { context.globalThis = context; vm.createContext(context); vm.runInContext(source, context, {filename:"task.js"}); -const {MutationQueue, EditGate, requestIdForPlan} = context.TorqTask; +const {MutationQueue, EditGate, ReviewGate, RecoveryGate, HistoryGate, stableRequestId, forgetAfterDefiniteRejection, requestIdForPlan, unwrap, formatNewlineMetadata, formatCheckOutput, canRecover, applicationApplied, applicationBlocksApply, applicationRetryIdentity, applicationOutcomeMessage} = context.TorqTask; (async () => { const queue = new MutationQueue(); @@ -37,12 +37,85 @@ const {MutationQueue, EditGate, requestIdForPlan} = context.TorqTask; const switchTicket = gate.capture("project-a", "draft-a2"); assert.equal(gate.accepts(switchTicket, "project-b", "draft-a2"), false, "project switch rejects stale load"); + const review = new ReviewGate(); + const oldSelection = review.select("task-a", 7); + const currentSelection = review.select("task-b", 11); + assert.equal(review.accepts(oldSelection), false, "delayed review cannot replace the current selection"); + assert.equal(review.accepts(currentSelection), true); + const pendingMutation = review.capture(); + review.select("task-a", 7); + assert.equal(review.accepts(pendingMutation), false, "delayed mutation cannot enable another candidate"); + const recovery = new RecoveryGate(); + const oldRecovery = recovery.select("project-a"); + recovery.select("project-b"); + assert.equal(recovery.accepts(oldRecovery), false, "delayed recovery status cannot replace a switched project"); + assert.equal(canRecover({state:"recovery_required",owned:false}), false, "another installation's recovery is never actionable"); + assert.equal(canRecover({state:"recovery_required",owned:true}), true); + const history = new HistoryGate(); + const oldQuery = history.select("first goal"); + const currentQuery = history.select("second goal"); + assert.equal(history.accepts(oldQuery), false, "delayed old-query history cannot replace a new search"); + assert.equal(history.accepts(currentQuery), true); + const hash = `sha256:${"1".repeat(64)}`; + const retryCandidate = {review_hash:hash}, retryAcceptance = {decision_id:"decision-a"}; + assert.equal(applicationApplied({state:"rejected",application_id:"application-r"}), false); + assert.equal(applicationApplied({state:"rolled_back",application_id:"application-b"}), false); + assert.equal(applicationApplied({state:"recovery_required",application_id:"application-x"}), false); + assert.equal(applicationApplied({state:"applied",application_id:"application-ok"}), true); + assert.equal(applicationBlocksApply({state:"rejected",application_id:"application-r"}), false, "signed rejection permits a fresh explicitly eligible Apply"); + assert.equal(applicationBlocksApply({state:"rolled_back",application_id:"application-b"}), false, "signed rollback permits a fresh explicitly eligible Apply"); + assert.equal(applicationBlocksApply({state:"recovery_required",application_id:"application-x"}), true); + assert.equal(applicationRetryIdentity(retryCandidate,retryAcceptance,{state:"rejected",application_id:"application-r"}), `${hash}.decision-a.application-r.rejected`); + assert.match(applicationOutcomeMessage({state:"rolled_back",application_id:"application-b"}), /original project files were restored/); + const values = new Map(); - const storage = {getItem:(key) => values.get(key) || null, setItem:(key, value) => values.set(key, value)}; + const storage = {getItem:(key) => values.get(key) || null, setItem:(key, value) => values.set(key, value), removeItem:(key) => values.delete(key)}; const crypto = {randomUUID:() => "stable-request"}; - const hash = `sha256:${"1".repeat(64)}`; assert.equal(requestIdForPlan(hash, storage, crypto), "stable-request"); assert.equal(requestIdForPlan(hash, storage, {randomUUID:() => "different"}), "stable-request", "ambiguous retry reuses request identity"); assert.equal(requestIdForPlan(hash, {getItem:() => {throw new Error("blocked");}}, crypto), `request-${hash.slice(7,31)}`); + + let generated = 0; + const mutationCrypto = {randomUUID:() => `mutation-${++generated}`}; + assert.equal(stableRequestId("accept", hash, storage, mutationCrypto), "mutation-1"); + assert.equal(stableRequestId("accept", hash, storage, mutationCrypto), "mutation-1", "accept retry reuses its identity"); + assert.equal(stableRequestId("apply", hash, storage, mutationCrypto), "mutation-2", "apply has a separate identity"); + assert.equal(stableRequestId("continue", "application-a", storage, mutationCrypto), "mutation-3"); + assert.equal(forgetAfterDefiniteRejection(new Error("response_lost"), "continue", "application-a", storage), false); + assert.equal(stableRequestId("continue", "application-a", storage, mutationCrypto), "mutation-3", "unknown outcome preserves Continue identity"); + const rejected = new Error("candidate_continuation_draft_occupied"); rejected.status = 409; + assert.equal(forgetAfterDefiniteRejection(rejected, "continue", "application-a", storage), true); + assert.equal(stableRequestId("continue", "application-a", storage, mutationCrypto), "mutation-4", "definite rejected response rotates Continue identity"); + + const directReview = { + schema: "torq-task-review-v1", + review_hash: hash, + review: {task_id: "task-a", ready_sequence: 7}, + }; + assert.equal(unwrap(directReview, "review"), directReview, "direct review envelope must retain its schema and hash"); + const accepted = { + schema: "torq-candidate-acceptance-v1", + state: "accepted", + candidate: {review_hash: hash}, + acceptance: {decision_id: "decision-a"}, + source_changed: false, + }; + const wrappedAccept = {status: "accepted", result: accepted}; + assert.equal(unwrap(wrappedAccept, "acceptance"), accepted, "mutation wrapper must yield the full acceptance result"); + assert.equal(unwrap(accepted, "acceptance"), accepted, "direct acceptance must not collapse to DecisionRef"); + const continued = {schema:"torq-candidate-continuation-v1", draft:{project_id:"calculator-project", revision:4}}; + const wrappedContinue = {status:"accepted", result:continued}; + assert.equal(unwrap(wrappedContinue, "draft"), continued, "wrapped Continue must retain its schema envelope"); + assert.equal(unwrap(wrappedContinue, "draft").draft.project_id, "calculator-project"); + assert.equal( + formatNewlineMetadata({style:"crlf", final_newline:false, bytes:27, line_count:2}, "ignored\n"), + "CRLF · 27 bytes · no final newline", + "structured backend newline metadata must not be string-coerced", + ); + assert.equal( + formatCheckOutput({contract:"torq-structural-result-v1",checked:[{path:"calculator.py",validator:"python_ast"}],status:"passed"}), + "Status: passed\nChecked files:\n• calculator.py — python ast", + "structured check output must remain readable", + ); console.log("task runtime contract checks passed"); })().catch((error) => { console.error(error); process.exitCode = 1; }); diff --git a/tests/test_candidate_decision_evidence.py b/tests/test_candidate_decision_evidence.py new file mode 100644 index 0000000..2247765 --- /dev/null +++ b/tests/test_candidate_decision_evidence.py @@ -0,0 +1,154 @@ +from __future__ import annotations + +from typing import Any + +from torq_cli.domain.candidate_decision_evidence import ( + APPLY_CONTRACT, + validate_decision_receipt_contract, +) + + +def _digest(character: str) -> str: + return "sha256:" + character * 64 + + +def _candidate() -> dict[str, Any]: + return { + "task_id": "run-task-" + "1" * 24, + "ready_sequence": 4, + "ready_receipt_hash": _digest("1"), + "terminal_manifest_hash": _digest("2"), + "plan_hash": _digest("3"), + "base_scope_manifest_hash": _digest("4"), + "input_hash": _digest("5"), + "candidate_scope_manifest_hash": _digest("6"), + "check_sequence": 3, + "check_receipt_hash": _digest("7"), + "review_hash": _digest("8"), + } + + +def _common() -> dict[str, Any]: + return { + "apply_contract": APPLY_CONTRACT, + "application_id": "application-" + "a" * 24, + "request_digest": _digest("9"), + "candidate": _candidate(), + "acceptance": { + "decision_id": "decision-" + "b" * 24, + "decision_sequence": 1, + "decision_receipt_hash": _digest("a"), + "terminal_manifest_hash": _digest("b"), + }, + "actor": {"subject_id": "session-one", "assurance": "local_operator_session"}, + } + + +def _row(sequence: int, event: str, detail: dict[str, Any]) -> dict[str, Any]: + return { + "run_id": "application-" + "a" * 24, + "sequence": sequence, + "transition": "audit", + "receipt_hash": _digest(format(sequence, "x")), + "payload": {**_common(), "event": event, "detail": detail}, + } + + +def test_prepared_application_can_seal_as_rejected_before_start() -> None: + rows = [ + _row(1, "apply_authority_created", {"installation_id": "installation-one"}), + _row(2, "apply_prepared", { + "journal_artifact": { + "artifact": "artifacts/primary-journal.enc", + "artifact_hash": _digest("c"), "content_hash": _digest("d"), + }, + "journal_hash": _digest("d"), "primary_identity_hash": _digest("e"), + "operation_count": 1, + }), + _row(3, "apply_rejected", {"reason_code": "task_apply_recovery_aborted"}), + ] + assert validate_decision_receipt_contract(rows, sealed=True) is None + + +def test_staged_and_written_progress_must_crosslink_exact_receipt() -> None: + rows = [ + _row(1, "apply_authority_created", {"installation_id": "installation-one"}), + _row(2, "apply_prepared", { + "journal_artifact": { + "artifact": "artifacts/primary-journal.enc", + "artifact_hash": _digest("c"), "content_hash": _digest("d"), + }, + "journal_hash": _digest("d"), "primary_identity_hash": _digest("e"), + "operation_count": 1, + }), + _row(3, "apply_started", { + "prepared_sequence": 2, "prepared_receipt_hash": _digest("2"), + }), + _row(4, "apply_file_staged", { + "started_sequence": 3, "operation_index": 0, "path": "a.py", + "result_hash": _digest("f"), "staged_identity": {"volume": 1, "file_id": 2}, + }), + _row(5, "apply_file_written", { + "started_sequence": 3, "staged_sequence": 4, + "staged_receipt_hash": _digest("4"), "operation_index": 0, + "path": "a.py", "result_hash": _digest("f"), + }), + _row(6, "candidate_applied", { + "started_sequence": 3, "journal_hash": _digest("d"), + "result_scope_manifest_hash": _digest("6"), "operation_count": 1, + }), + ] + assert validate_decision_receipt_contract(rows, sealed=True) is None + rows[4]["payload"]["detail"]["staged_receipt_hash"] = _digest("0") + assert ( + validate_decision_receipt_contract(rows, sealed=True) + == "candidate_apply_progress_link_invalid" + ) + + +def test_rollback_progress_is_reverse_order_and_requires_restored_crosslinks() -> None: + rows = [ + _row(1, "apply_authority_created", {"installation_id": "installation-one"}), + _row(2, "apply_prepared", { + "journal_artifact": { + "artifact": "artifacts/primary-journal.enc", + "artifact_hash": _digest("c"), "content_hash": _digest("d"), + }, + "journal_hash": _digest("d"), "primary_identity_hash": _digest("e"), + "operation_count": 1, + }), + _row(3, "apply_started", { + "prepared_sequence": 2, "prepared_receipt_hash": _digest("2"), + }), + _row(4, "apply_file_staged", { + "started_sequence": 3, "operation_index": 0, "path": "a.py", + "result_hash": _digest("f"), "staged_identity": {"volume": 1, "file_id": 2}, + }), + _row(5, "apply_file_written", { + "started_sequence": 3, "staged_sequence": 4, + "staged_receipt_hash": _digest("4"), "operation_index": 0, + "path": "a.py", "result_hash": _digest("f"), + }), + _row(6, "apply_rollback_started", { + "caused_by_sequence": 5, "reason_code": "task_apply_result_mismatch", + }), + _row(7, "apply_rollback_file_staged", { + "rollback_started_sequence": 6, "operation_index": 0, "path": "a.py", + "base_hash": _digest("0"), "staged_identity": {"volume": 1, "file_id": 3}, + }), + _row(8, "apply_rollback_file_restored", { + "rollback_started_sequence": 6, "operation_index": 0, "path": "a.py", + "base_hash": _digest("0"), "staged_sequence": 7, + "staged_receipt_hash": _digest("7"), + }), + _row(9, "apply_rolled_back", { + "prepared_sequence": 2, "journal_hash": _digest("d"), + "restored_scope_manifest_hash": _digest("4"), + }), + ] + assert validate_decision_receipt_contract(rows, sealed=True) is None + rows.pop(7) + assert ( + validate_decision_receipt_contract(rows, sealed=True) + == "candidate_apply_terminal_link_invalid" + ) diff --git a/tests/test_candidate_history.py b/tests/test_candidate_history.py new file mode 100644 index 0000000..f33d5b8 --- /dev/null +++ b/tests/test_candidate_history.py @@ -0,0 +1,60 @@ +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from torq_cli.application.candidate_review import CandidateReviewService +from torq_cli.application.task_store import TaskStore + + +def test_history_cursor_survives_new_tasks_and_ordinals_survive_restart(tmp_path: Path) -> None: + store = TaskStore(tmp_path / "state") + plan = store.save_plan({"project_id": "app", "goal": "Straße correction"}) + body = {"project_id": "app", "plan_hash": plan["plan_hash"]} + first, _ = store.reserve("first", body) + second, _ = store.reserve("second", body) + restarted = TaskStore(tmp_path / "state") + assert restarted.reserve("first", body) == (first, False) + third, _ = restarted.reserve("third", body) + assert [item["history_ordinal"] for item in (first, second, third)] == [1, 2, 3] + + service = CandidateReviewService.__new__(CandidateReviewService) + service.tasks = SimpleNamespace( # type: ignore[assignment] + store=restarted, projects={"app": SimpleNamespace(label="My project")}, + evidence_root=tmp_path / "evidence", + ) + page = service.history(query="STRASSE", limit=1) + assert page["items"][0]["task_id"] == third["task_id"] + assert page["next_cursor"] == third["task_id"] + newest, _ = restarted.reserve("newest", body) + next_page = service.history(query="STRASSE", limit=1, cursor=page["next_cursor"]) + assert next_page["items"][0]["task_id"] == second["task_id"] + last = service.history(query="STRASSE", limit=1, cursor=next_page["next_cursor"]) + assert last["items"][0]["task_id"] == first["task_id"] + assert last["next_cursor"] is None + assert service.history(limit=1)["items"][0]["task_id"] == newest["task_id"] + with pytest.raises(ValueError, match="cursor_invalid"): + service.history(cursor="not-a-task") + with pytest.raises(ValueError, match="query_invalid"): + service.history(limit=True) + + +def test_legacy_history_keeps_explicit_undated_fallback_without_rewriting(tmp_path: Path) -> None: + store = TaskStore(tmp_path / "state") + plan = store.save_plan({"project_id": "app", "goal": "Legacy"}) + task, _ = store.reserve("legacy", {"project_id": "app", "plan_hash": plan["plan_hash"]}) + data = store.snapshot() + del data["tasks"][task["task_id"]]["history_ordinal"] + data["tasks"]["../outside"] = dict(task) + store._write(data) + before = store.path.read_bytes() + service = CandidateReviewService.__new__(CandidateReviewService) + service.tasks = SimpleNamespace( # type: ignore[assignment] + store=store, projects={}, evidence_root=tmp_path / "evidence", + ) + items = service.history()["items"] + assert len(items) == 1 + row = items[0] + assert row["created_at"] is None and row["legacy_order"] is True + assert row["history_ordinal"] is None + assert store.path.read_bytes() == before diff --git a/tests/test_candidate_review.py b/tests/test_candidate_review.py new file mode 100644 index 0000000..075a245 --- /dev/null +++ b/tests/test_candidate_review.py @@ -0,0 +1,297 @@ +from __future__ import annotations + +import os +import sys +import time +from pathlib import Path + +import pytest + +from torq_cli.adapters.candidate_provider import CandidateProviderCommand +from torq_cli.adapters.process import OwnedProcess +from torq_cli.application.candidate_review import CandidateReviewService +from torq_cli.application.candidate_tasks import CandidateTaskService, TaskProject +from torq_cli.safety.primary_transaction import AnchoredPrimary +from torq_cli.safety.receipts import verify_receipt_store + +pytestmark = pytest.mark.skipif(os.name != "nt", reason="native primary transaction fixture is Windows") + + +def _ready(service: CandidateTaskService, task_id: str) -> dict[str, object]: + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + result = service.task(task_id) + if result["state"] not in {"reserved", "preparing", "generating", "checking"}: + return result + time.sleep(0.02) + raise AssertionError("candidate did not finish") + + +def _fixture(tmp_path: Path) -> tuple[CandidateTaskService, Path, list[list[str]]]: + source = tmp_path / "source" + runtime = tmp_path / "runtime" + source.mkdir() + runtime.mkdir() + target = source / "calculator.py" + target.write_bytes(b"def add(left, right):\r\n return left - right") + launches: list[list[str]] = [] + provider_path = Path("tests/fixtures/candidate_provider.py").resolve() + + def owner(*args: object, **kwargs: object) -> OwnedProcess: + launches.append(list(args[0])) # type: ignore[arg-type] + return OwnedProcess(*args, **kwargs) # type: ignore[arg-type] + + def provider(prompt: str) -> CandidateProviderCommand: + return CandidateProviderCommand( + (sys.executable, "-I", "-S", str(provider_path)), str(runtime), + {"PYTHONIOENCODING": "utf-8"}, prompt.encode(), "fixture", "local-fixture", + ) + + service = CandidateTaskService( + projects=[TaskProject("calculator", "Calculator", source)], + state_root=tmp_path / "state", work_root=tmp_path / "work", + provider_factory=provider, provider="fixture", model="local-fixture", owner_factory=owner, + ) + return service, target, launches + + +def test_review_accept_apply_and_new_session_replay_are_evidence_backed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + tasks, target, launches = _fixture(tmp_path) + try: + draft = tasks.save_draft( + "calculator", goal="Fix addition", input_paths=["calculator.py"], + output_paths=["calculator.py"], expected_revision=0, + ) + plan = tasks.review_plan( + project_id="calculator", draft_revision=draft["revision"], + input_paths=["calculator.py"], output_paths=["calculator.py"], + ) + started = tasks.start(request_id="build-one", plan_hash=plan["plan_hash"]) + assert _ready(tasks, str(started["task_id"]))["state"] == "candidate_ready" + assert len(launches) == 2 + service = CandidateReviewService( + tasks=tasks, state_root=tmp_path / "state", common_authority_root=tmp_path / "authority", + ) + review = service.review(str(started["task_id"]), 4) + change = review["review"]["changes"][0] + assert "[CRLF]" in change["diff"] and "[NO EOL]" in change["diff"] + accepted = service.accept( + request_id="accept-one", task_id=str(started["task_id"]), ready_sequence=4, + review_hash=review["review_hash"], subject_id="session-first", + ) + assert accepted["state"] == "accepted" + assert b"left - right" in target.read_bytes() + replay = service.accept( + request_id="accept-one", task_id=str(started["task_id"]), ready_sequence=4, + review_hash=review["review_hash"], subject_id="session-after-restart", + ) + assert replay == accepted + applied = service.apply( + request_id="apply-one", candidate=accepted["candidate"], + acceptance=accepted["acceptance"], subject_id="session-first", + ) + assert applied["state"] == "applied" + assert target.read_bytes() == b"def add(left, right):\n return left + right\n" + replay_apply = service.apply( + request_id="apply-one", candidate=accepted["candidate"], + acceptance=accepted["acceptance"], subject_id="session-after-restart", + ) + assert replay_apply == applied + original_context = service.store.save_continuation_context + original_update = service.store.update + + def interrupted_context(*args: object, **kwargs: object) -> None: + raise SystemExit("simulated process death after durable draft") + + def interrupted_update(*args: object, **kwargs: object) -> dict[str, object]: + raise SystemExit("simulated process death before reservation completion") + + monkeypatch.setattr(service.store, "save_continuation_context", interrupted_context) + monkeypatch.setattr(service.store, "update", interrupted_update) + with pytest.raises(SystemExit, match="reservation completion"): + service.continue_task( + request_id="continue-one", application_id=applied["application_id"] + ) + monkeypatch.setattr(service.store, "save_continuation_context", original_context) + monkeypatch.setattr(service.store, "update", original_update) + continuation = service.continue_task( + request_id="continue-one", application_id=applied["application_id"] + ) + assert service.continue_task( + request_id="continue-one", application_id=applied["application_id"] + ) == continuation + continued_draft = continuation["draft"] + continued_draft = tasks.save_draft( + "calculator", goal="Add another verified change", + input_paths=continued_draft["input_paths"], + output_paths=continued_draft["output_paths"], + expected_revision=continued_draft["revision"], + ) + continued_plan = tasks.review_plan( + project_id="calculator", draft_revision=continued_draft["revision"], + input_paths=continued_draft["input_paths"], + output_paths=continued_draft["output_paths"], + ) + assert continued_plan["contract"] == "torq-candidate-plan-v2" + assert continued_plan["lineage"]["mode"] == "continuation" + newest_draft = tasks.save_draft( + "calculator", goal="A newer continuation goal", + input_paths=continued_draft["input_paths"], + output_paths=continued_draft["output_paths"], + expected_revision=continued_draft["revision"], + ) + with pytest.raises(ValueError, match="task_plan_stale"): + tasks.start(request_id="stale-continuation", plan_hash=continued_plan["plan_hash"]) + tasks.delete_draft("calculator", expected_revision=newest_draft["revision"]) + empty_draft = tasks.draft("calculator") + assert empty_draft is not None + original_save = tasks.save_draft + raced = False + + def racing_save( + project_id: str, *, goal: str, input_paths: list[str], + output_paths: list[str], expected_revision: int, + ) -> dict[str, object]: + nonlocal raced + if not raced: + raced = True + original_save( + project_id, goal="Concurrent ordinary draft", + input_paths=input_paths, output_paths=output_paths, + expected_revision=expected_revision, + ) + return original_save( + project_id, goal=goal, input_paths=input_paths, + output_paths=output_paths, expected_revision=expected_revision, + ) + + monkeypatch.setattr(tasks, "save_draft", racing_save) + with pytest.raises(ValueError, match="task_draft_revision_conflict"): + service.continue_task( + request_id="continue-cas-race", application_id=applied["application_id"] + ) + assert service.store.active_continuation("calculator") is None + concurrent = tasks.draft("calculator") + assert concurrent is not None and concurrent["goal"] == "Concurrent ordinary draft" + ordinary_plan = tasks.review_plan( + project_id="calculator", draft_revision=concurrent["revision"], + input_paths=concurrent["input_paths"], output_paths=concurrent["output_paths"], + ) + assert ordinary_plan["contract"] == "torq-candidate-plan-v1" + assert len(launches) == 2 + assert verify_receipt_store( + service.review_evidence_root / accepted["acceptance"]["decision_id"] + ).status == "verified" + assert verify_receipt_store(service.apply_evidence_root / applied["application_id"]).status == "verified" + finally: + tasks.close() + + +def test_correction_creates_verified_immutable_child_task(tmp_path: Path) -> None: + tasks, target, launches = _fixture(tmp_path) + try: + draft = tasks.save_draft( + "calculator", goal="Fix addition", input_paths=["calculator.py"], + output_paths=["calculator.py"], expected_revision=0, + ) + plan = tasks.review_plan( + project_id="calculator", draft_revision=draft["revision"], + input_paths=draft["input_paths"], output_paths=draft["output_paths"], + ) + parent = tasks.start(request_id="build-parent", plan_hash=plan["plan_hash"]) + assert _ready(tasks, str(parent["task_id"]))["state"] == "candidate_ready" + reviews = CandidateReviewService( + tasks=tasks, state_root=tmp_path / "state", + common_authority_root=tmp_path / "authority", + ) + parent_review = reviews.review(str(parent["task_id"]), 4) + correction = reviews.save_correction( + str(parent["task_id"]), 4, text="Keep the corrected addition implementation.", + expected_revision=0, + ) + child_plan = reviews.review_child_plan( + str(parent["task_id"]), 4, request_id="review-child", + correction_revision=correction["revision"], + correction_hash=correction["content_hash"], + review_hash=parent_review["review_hash"], subject_id="session-one", + ) + assert reviews.review_child_plan( + str(parent["task_id"]), 4, request_id="review-child", + correction_revision=correction["revision"], + correction_hash=correction["content_hash"], + review_hash=parent_review["review_hash"], subject_id="session-two", + ) == child_plan + child = reviews.start_revision( + request_id="start-child", plan_hash=child_plan["plan_hash"] + ) + child_ready = _ready(tasks, str(child["task_id"])) + assert child_ready["state"] == "candidate_ready" + child_review = reviews.review(str(child["task_id"]), int(child_ready["ready_sequence"])) + assert child_review["review"]["lineage"]["mode"] == "refinement" + assert child_review["review"]["lineage"]["parent_candidate"]["task_id"] == parent["task_id"] + assert target.read_bytes() == b"def add(left, right):\r\n return left - right" + assert len(launches) == 4 + finally: + tasks.close() + + +def test_recovery_resumes_signed_rollback_after_native_restore( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + tasks, target, launches = _fixture(tmp_path) + original = target.read_bytes() + try: + draft = tasks.save_draft( + "calculator", goal="Fix addition", input_paths=["calculator.py"], + output_paths=["calculator.py"], expected_revision=0, + ) + plan = tasks.review_plan( + project_id="calculator", draft_revision=draft["revision"], + input_paths=draft["input_paths"], output_paths=draft["output_paths"], + ) + started = tasks.start(request_id="rollback-build", plan_hash=plan["plan_hash"]) + assert _ready(tasks, str(started["task_id"]))["state"] == "candidate_ready" + service = CandidateReviewService( + tasks=tasks, state_root=tmp_path / "state", + common_authority_root=tmp_path / "authority", + ) + review = service.review(str(started["task_id"]), 4) + accepted = service.accept( + request_id="rollback-accept", task_id=str(started["task_id"]), + ready_sequence=4, review_hash=review["review_hash"], subject_id="session", + ) + native_replace = AnchoredPrimary.replace + forward_failed = False + + def interrupted_replace(self: AnchoredPrimary, *args: object, **kwargs: object) -> object: + nonlocal forward_failed + result = native_replace(self, *args, **kwargs) # type: ignore[arg-type] + if kwargs.get("rollback") is True: + raise SystemExit("simulated death after rollback rename") + if not forward_failed: + forward_failed = True + raise RuntimeError("task_injected_apply_failure") + return result + + monkeypatch.setattr(AnchoredPrimary, "replace", interrupted_replace) + interrupted = service.apply( + request_id="rollback-apply", candidate=accepted["candidate"], + acceptance=accepted["acceptance"], subject_id="session", + ) + assert interrupted["state"] == "recovery_required" + assert target.read_bytes() == original + monkeypatch.setattr(AnchoredPrimary, "replace", native_replace) + + restarted = CandidateReviewService( + tasks=tasks, state_root=tmp_path / "state", + common_authority_root=tmp_path / "authority", + ) + recovered = restarted.recover("calculator") + assert recovered["state"] == "rolled_back" + assert restarted.recover("calculator")["state"] == "idle" + assert target.read_bytes() == original + assert len(launches) == 2 + finally: + tasks.close() diff --git a/tests/test_fleet_ui.py b/tests/test_fleet_ui.py index f0cfbe3..40fe99d 100644 --- a/tests/test_fleet_ui.py +++ b/tests/test_fleet_ui.py @@ -100,6 +100,17 @@ def test_fleet_ui_shell_is_public_but_contains_no_run_data(tmp_path: Path) -> No "task-review", "task-start", "task-stop", + "review-back", + "review-tab-plan", + "review-tab-changes", + "review-tab-checks", + "review-correction-plan", + "review-start-revision", + "review-accept", + "review-apply", + "review-continue", + "task-recover", + "task-history-more", } assert 'href="#fleet-board"' in markup assert 'aria-live="polite"' in markup @@ -158,6 +169,34 @@ def test_task_ui_is_bundled_and_names_bounded_candidate_behavior() -> None: assert "caps.active_task_id" in javascript assert "data-task-id" in javascript assert '@media (max-width: 760px)' in css + assert 'role="tablist" aria-label="Candidate evidence"' in html + assert 'Accept copy' not in html + assert "It does not modify your project" in html + assert "Apply to project" in html + assert '
float: diff --git a/tests/test_fleet_ui_runtime.py b/tests/test_fleet_ui_runtime.py index cc9ad8d..79917a1 100644 --- a/tests/test_fleet_ui_runtime.py +++ b/tests/test_fleet_ui_runtime.py @@ -20,3 +20,18 @@ def test_fleet_javascript_executes_core_envelope_and_notification_behaviors() -> text=True, ) assert completed.returncode == 0, completed.stderr + + +def test_task_javascript_rejects_delayed_selection_and_mutation_responses() -> None: + node = shutil.which("node") + if node is None: + pytest.skip("node_runtime_unavailable") + source_path = Path("src/torq_cli/data/fleet/task.js").resolve() + harness = Path("tests/js/task_runtime.test.cjs").resolve() + completed = subprocess.run( + [node, str(harness), str(source_path)], + check=False, + capture_output=True, + text=True, + ) + assert completed.returncode == 0, completed.stderr diff --git a/tests/test_hermetic.py b/tests/test_hermetic.py index 6e71694..735592c 100644 --- a/tests/test_hermetic.py +++ b/tests/test_hermetic.py @@ -77,6 +77,8 @@ def test_production_imports_forbid_subprocess() -> None: "torq_cli/safety/chat_evidence.py", "torq_cli/safety/task_workspace.py", "torq_cli/safety/state_lock.py", + "torq_cli/safety/primary_marker.py", + "torq_cli/safety/primary_transaction.py", ) ): # The evidence broker owns the authenticated local-only IPC @@ -89,8 +91,10 @@ def test_production_imports_forbid_subprocess() -> None: local_allow = {"sys"} else: local_allow = {"os"} - elif source_path.as_posix().endswith("torq_cli/application/task_store.py"): - # Durable task CAS/reservations need atomic replace and fsync. + elif source_path.as_posix().endswith( + ("torq_cli/application/task_store.py", "torq_cli/application/review_store.py") + ): + # Durable task and review CAS/reservations need atomic replace and fsync. local_allow = {"os"} elif source_path.as_posix().endswith("torq_cli/connectors/native_credentials.py"): # DISPLAY/WAYLAND_DISPLAY are explicit session-type facts only; diff --git a/tests/test_primary_transaction.py b/tests/test_primary_transaction.py new file mode 100644 index 0000000..2c0e595 --- /dev/null +++ b/tests/test_primary_transaction.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import ctypes +import errno +from pathlib import Path +from collections.abc import Callable +from typing import Any + +import pytest + +import torq_cli.safety.primary_transaction as primary_module +from torq_cli.safety.primary_transaction import AnchoredPrimary +from torq_cli.safety.task_workspace import digest_bytes + + +class _NativeFunction: + def __init__(self, callback: Callable[..., Any]) -> None: + self.callback = callback + self.argtypes: object = None + self.restype: object = None + + def __call__(self, *args: Any) -> Any: + return self.callback(*args) + + +class _DarwinLibc: + def __init__( + self, + *, + xattrs: bytes = b"", + acl: bool = False, + xattr_error: int | None = None, + acl_error: int | None = None, + ) -> None: + def list_xattrs( + _descriptor: Any, buffer: Any, size: Any, _options: Any + ) -> int: + if xattr_error is not None: + ctypes.set_errno(xattr_error) + return -1 + if buffer is None: + return len(xattrs) + if int(size) < len(xattrs): + ctypes.set_errno(errno.ERANGE) + return -1 + ctypes.memmove(buffer, xattrs, len(xattrs)) + return len(xattrs) + + def get_acl(_descriptor: Any, _kind: Any) -> int | None: + if acl_error is not None: + ctypes.set_errno(acl_error) + return None + if not acl: + ctypes.set_errno(errno.ENOENT) + return None + return 1234 + + def get_entry(*_args: Any) -> int: + return 0 + + self.flistxattr = _NativeFunction(list_xattrs) + self.acl_get_fd_np = _NativeFunction(get_acl) + self.acl_get_entry = _NativeFunction(get_entry) + self.acl_free = _NativeFunction(lambda *_args: 0) + + +def test_darwin_fd_metadata_adapter_is_bounded_and_fail_closed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(primary_module, "_darwin_libc", lambda: _DarwinLibc()) + assert primary_module._darwin_xattrs(7) == [] + assert primary_module._darwin_acl_present(7) is False + + monkeypatch.setattr( + primary_module, "_darwin_libc", lambda: _DarwinLibc(xattrs=b"user.note\x00") + ) + assert primary_module._darwin_xattrs(7) == ["user.note"] + monkeypatch.setattr(primary_module, "_darwin_libc", lambda: _DarwinLibc(acl=True)) + assert primary_module._darwin_acl_present(7) is True + + malformed = _DarwinLibc(xattrs=b"missing-terminator") + monkeypatch.setattr(primary_module, "_darwin_libc", lambda: malformed) + with pytest.raises(ValueError, match="task_apply_metadata_unsupported"): + primary_module._darwin_xattrs(7) + unavailable = _DarwinLibc(xattr_error=errno.ENOTSUP) + monkeypatch.setattr(primary_module, "_darwin_libc", lambda: unavailable) + with pytest.raises(RuntimeError, match="task_apply_metadata_unreadable"): + primary_module._darwin_xattrs(7) + acl_unavailable = _DarwinLibc(acl_error=errno.ENOTSUP) + monkeypatch.setattr(primary_module, "_darwin_libc", lambda: acl_unavailable) + with pytest.raises(RuntimeError, match="task_apply_metadata_unreadable"): + primary_module._darwin_acl_present(7) + + +def test_anchored_primary_replaces_creates_and_restores_exact_bytes(tmp_path: Path) -> None: + project = tmp_path / "project" + nested = project / "src" + nested.mkdir(parents=True) + target = nested / "value.py" + target.write_bytes(b"value = 1\n") + + with AnchoredPrimary(project) as primary: + before = primary.inspect("src/value.py") + assert before.content == b"value = 1\n" + with pytest.raises(RuntimeError, match="task_apply_primary_busy"): + AnchoredPrimary(project) + + replaced = primary.replace( + "src/value.py", + expected_before_hash=before.content_hash, + expected_parent_identity=before.parent_identity, + expected_target_identity=before.target_identity, + content=b"value = 2\n", + permission_policy=before.permission_policy or {}, + application_id="apply-" + "1" * 24, + operation_index=0, + ) + assert replaced.content_hash == digest_bytes(b"value = 2\n") + assert replaced.permission_policy == before.permission_policy + + absent = primary.inspect("src/new.py") + created = primary.replace( + "src/new.py", + expected_before_hash=None, + expected_parent_identity=absent.parent_identity, + expected_target_identity=None, + content=b"created = True\n", + permission_policy=primary.create_permission_policy(), + application_id="apply-" + "1" * 24, + operation_index=1, + ) + assert created.content == b"created = True\n" + + restored = primary.replace( + "src/value.py", + expected_before_hash=replaced.content_hash, + expected_parent_identity=replaced.parent_identity, + expected_target_identity=replaced.target_identity, + content=before.content, + permission_policy=before.permission_policy or {}, + application_id="apply-" + "1" * 24, + operation_index=2, + ) + assert restored.content_hash == before.content_hash + assert restored.permission_policy == before.permission_policy + assert created.target_identity is not None + primary.remove( + "src/new.py", + expected_hash=created.content_hash or "", + expected_parent_identity=created.parent_identity, + expected_target_identity=created.target_identity, + ) + + assert target.read_bytes() == b"value = 1\n" + assert not (nested / "new.py").exists() + assert list(nested.glob(".torq-*.tmp")) == [] + + +def test_anchored_primary_requires_existing_parent(tmp_path: Path) -> None: + project = tmp_path / "project" + project.mkdir() + with AnchoredPrimary(project) as primary: + with pytest.raises(ValueError, match="task_apply_parent_missing"): + primary.replace( + "missing/value.py", + expected_before_hash=None, + expected_parent_identity={}, + expected_target_identity=None, + content=b"value = 1\n", + permission_policy=primary.create_permission_policy(), + application_id="apply-" + "2" * 24, + operation_index=0, + ) diff --git a/tests/test_task_http.py b/tests/test_task_http.py index 67dfe36..7981ec4 100644 --- a/tests/test_task_http.py +++ b/tests/test_task_http.py @@ -52,6 +52,36 @@ def history(self) -> list[dict[str, Any]]: return [] +class _Reviews: + def __init__(self) -> None: + self.child: tuple[str, str] | None = None + self.continuation: tuple[str, str] | None = None + + def review_child_plan(self, task_id: str, ready_sequence: int, **body: Any) -> dict[str, Any]: + del task_id, ready_sequence + self.child = (body["request_id"], body["review_hash"]) + return {"schema": "torq-candidate-child-plan-v1", "plan_hash": "sha256:" + "2" * 64} + + def replay_child_plan(self, task_id: str, ready_sequence: int, **body: Any) -> dict[str, Any]: + del task_id, ready_sequence + if self.child != (body["request_id"], body["review_hash"]): + raise ValueError("candidate_request_replay_missing") + return {"schema": "torq-candidate-child-plan-v1", "plan_hash": "sha256:" + "2" * 64} + + def start_revision(self, *, request_id: str, plan_hash: str, replay_only: bool = False) -> dict[str, Any]: + del request_id, plan_hash, replay_only + return {"task_id": "run-task-" + "2" * 24, "state": "reserved"} + + def continue_task(self, *, request_id: str, application_id: str) -> dict[str, Any]: + self.continuation = (request_id, application_id) + return {"schema": "torq-candidate-continuation-v1", "draft": {"project_id": "project"}} + + def replay_continuation(self, *, request_id: str, application_id: str) -> dict[str, Any]: + if self.continuation != (request_id, application_id): + raise ValueError("candidate_request_replay_missing") + return {"schema": "torq-candidate-continuation-v1", "draft": {"project_id": "project"}} + + def _request(server: object, method: str, path: str, *, cookie: str | None = None, origin: str | None = None, body: object | None = None) -> tuple[int, dict[str, str], dict[str, Any]]: host, port = server.server_address[:2] # type: ignore[attr-defined] connection = http.client.HTTPConnection(host, port) @@ -108,3 +138,53 @@ def test_task_http_requires_session_origin_and_closed_request_body(tmp_path: Pat server.shutdown() server.server_close() thread.join(timeout=2) + + +def test_refinement_and_continuation_routes_are_closed_and_replayable(tmp_path: Path) -> None: + reviews = _Reviews() + server = create_fleet_server( + FleetProjector(tmp_path / "no-run"), port=0, task_service=_Tasks(), + review_service=reviews, # type: ignore[arg-type] + ) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + host, port = server.server_address[:2] + origin = f"http://{host}:{port}" + try: + bootstrap = _request(server, "GET", f"/bootstrap?nonce={server.fleet_bootstrap_nonce}&view=task") + cookie = bootstrap[1]["Set-Cookie"].split(";", 1)[0] + child_body = { + "request_id": "child-request", "correction_revision": 1, + "correction_hash": "sha256:" + "1" * 64, + "review_hash": "sha256:" + "2" * 64, + } + path = f"/api/v1/task-reviews/run-task-{'1' * 24}/4/child-plans" + denied = _request( + server, "POST", path, cookie=cookie, origin=origin, + body=child_body | {"unknown": True}, + ) + assert denied[0] == 409 and reviews.child is None + cookie = denied[1]["Set-Cookie"].split(";", 1)[0] + first = _request(server, "POST", path, cookie=cookie, origin=origin, body=child_body) + assert first[0] == 200 and first[2]["result"]["schema"] == "torq-candidate-child-plan-v1" + replay = _request(server, "POST", path, cookie=cookie, origin=origin, body=child_body) + assert replay[0] == 200 + cookie = replay[1]["Set-Cookie"].split(";", 1)[0] + continue_body = { + "request_id": "continue-request", + "application_id": "application-" + "3" * 24, + } + continued = _request( + server, "POST", "/api/v1/task-continuations", cookie=cookie, + origin=origin, body=continue_body, + ) + assert continued[0] == 200 + lost_response_replay = _request( + server, "POST", "/api/v1/task-continuations", cookie=cookie, + origin=origin, body=continue_body, + ) + assert lost_response_replay[0] == 200 + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2)