From 43f46cbfdb51e72b15246439c7677e85e4484598 Mon Sep 17 00:00:00 2001 From: King Flowers Date: Wed, 16 Sep 2026 18:33:52 -0500 Subject: [PATCH 1/6] docs: rewrite dashboard UX plan with counterevidence, artifact integrity rules, and build-tool parity goal Second research pass via agent-reach (Exa, Reddit, GitHub issues) added failure cases from Codex Desktop and Claude Code desktop: mislabelled review diffs, wrong diff base on Windows, unusable inline review, forced redesign backlash, and project/session conflation. The plan now states the build-tool parity goal up front, adds design principles, a status- filtered task list, full-height Needs review layout, a consequence and policy_ref on every pending action, artifact integrity rules as P3 release gates, opt-in Home with persisted default, and notifications in P1. Co-Authored-By: Claude Fable 5.1 --- docs/plans/2026-09-16-dashboard-ux-plan.md | 309 +++++++++++++++++++++ 1 file changed, 309 insertions(+) create mode 100644 docs/plans/2026-09-16-dashboard-ux-plan.md diff --git a/docs/plans/2026-09-16-dashboard-ux-plan.md b/docs/plans/2026-09-16-dashboard-ux-plan.md new file mode 100644 index 0000000..5bbfa86 --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-ux-plan.md @@ -0,0 +1,309 @@ +# TORQ task workspace: dashboard review and implementation plan + +Status: proposed, not implemented. Reviewed 2026-09-16, revised the same day after a second research pass. Scope: TORQ CLI in E:/Torq-CLI. + +Product goal, stated by the user on 2026-09-16: use TORQ CLI the way Google Antigravity, the Codex app, and Claude Code are used. Describe a task in ordinary language, get a plan, let the agent edit files and run commands, review the diff and checks, and iterate. The current dashboard cannot do this: its chat runs the provider with no tools and in plan mode, bound to an existing run. Everything below is in service of closing that gap without giving up the evidence guarantees those tools do not have. + +| What those tools do | TORQ today | Where this plan delivers it | +|---|---|---| +| Open a folder and start typing | Requires an existing run directory and a certified receipt chain | P0 entry states, P2 project selection and start service | +| Agent proposes a plan, user approves | Chat is plan-only with no execution path | P2 execution policy and accepted plan revision | +| Agent edits files and runs commands | Chat adapter passes an empty tools list | P2 governed run creation through existing services; never by unlocking the chat adapter | +| Review a diff and test results, then accept | Fleet shows evidence counts and lanes, not a diff | P3 Plan, Changes, and Checks views under the artifact integrity rules | +| Ask a follow-up and continue | No session persistence in the chat adapter | P1 drafts during work, P3 revision requests and task continuation | +| Get notified when it needs you | None | P1 notifications | + +P0 and P1 make the dashboard honest and usable. P2 is the phase that makes it a build tool. Do not call the goal met before P2's exit gate passes. + +Recommendation: make the default dashboard a task workspace where a user describes a goal, reviews a plan, starts governed work, and inspects the result with the evidence beside it. Retain Fleet as the detailed operations view. Preserve the existing trust gate and introduce an honest entry path before it. Ship the new Home as an opt-in view first; never switch an existing user's default silently. + +```mermaid +flowchart LR + A[Open project] --> B[Describe task and save draft] + B --> C[Check setup and capabilities] + C --> D[Review scope and execution policy] + D --> E[Create governed run through existing services] + E --> F[Plan and execute governed stages] + F --> G[Needs review: plan, changes, checks bound to evidence] + G --> H[Accept, request correction, or stop] + F --> I[Fleet details] + E --> J[Discuss this run when verified] +``` + +## What the repository actually does + +This was a source and contract review, not a live authenticated browser audit. No provider was called, credentials changed, or live run started. Existing untracked launcher/demo artifacts were inspected, not edited. The old TORQCLAW memory refers to another repository and is not this product's current implementation authority. + +| Priority | Finding and evidence | User consequence | Fix | +|---|---|---|---| +| P0 | `safety/chat_evidence.py:_certified_operator_key` requires receipt verification of `verified` or `live_catching_up` and a certified `operator_gateway` public key. | An empty or demo entry cannot act as a general build conversation. | Keep this boundary; offer draft, setup, and start-task capabilities separately. | +| P0 | `adapters/chat_provider.py:ChatProviderCommandFactory` invokes Claude with an empty `--tools` argument, `--permission-mode plan`, disabled slash commands, and no session persistence. | Unlocking this chat does not create an implementation agent. | Label current chat as run discussion; execute builds through the governed run service. | +| P0 | The untracked `torq-cli-dashboard.ps1` sets `runRoot` to `torq-demo-runs`. `RunController` creates `run-*` children; `FleetProjector` expects evidence directly inside its selected root. | The launcher supplies a collection directory to a single-run view. | Distinguish run collection and selected run. Present a run picker; never silently pick an arbitrary child. | +| P1 | `data/fleet/index.html` leads with GOVERNED FLEET, GOVERNANCE SIGNAL RAIL, VERIFIED REDUCER, profile, evidence counts, lanes, and sequence numbers. | The user must understand implementation concepts before finding useful work. | Put goal, next action, progress, and result first; move full technical state to Details/Fleet. | +| P1 | `chat.js:updateControls` disables typing when unavailable and while a turn is active; `applySnapshot` displays a raw finding. | Blocked users cannot prepare their task and have no guided next step. | Keep draft editing available independently; gate submission with an explanation and a recovery action. Do not imply queued dispatch. | +| P1 | `index.html` advertises files for chat; the Claude adapter rejects all attachments. | The UI promises an operation the selected provider cannot perform. | Server-provided capability metadata drives accepted files and help text. | +| P1 | There are separate Add context and chat composers with different semantics. | Sending instructions can mean recording future context or calling a provider. | One primary composer with an explicit purpose; place future-attempt context in task details. | +| P2 | A dense summary, lane board, settlement panel, and fixed command rail share the main page. | Attention is spread across operational telemetry. | Calm spacing, restrained color, a central conversation, and a full-height review panel when review is required. | + +The quoted diagnosis is accurate about the trust prerequisite but insufficient as a product resolution. The launcher path mismatch is an additional issue. Neither fixing that path nor obtaining a certificate alone establishes provider readiness, platform support, or build capability. The plain `torq run` path also has a separate `--live` branch; do not promise that any invocation automatically creates a live working builder. + +## Research evidence and limits + +Research accessed 2026-09-16 using agent-reach: doctor, Exa through mcporter, Reddit OpenCLI reads, and GitHub issue reads. Broad Reddit search returned noisy matches; targeted thread reads and Exa-indexed threads supplied the usable material. This is a purposive qualitative sample, not a representative sentiment survey or model ranking. Posts describe the experience on their publication date, not necessarily today's features. No claimed token savings, speedups, or model superiority are treated as measured results. + +### What users valued + +| Source and publication date | What users valued | Design implication | +|---|---|---| +| [Codex: Anyone Else Really Enjoying the Codex App?](https://www.reddit.com/r/codex/comments/1r6x43w/anyone_else_really_enjoying_the_codex_app/), 2026-02-17; direct thread read | A less cluttered environment, text and code together, easier switching among conversations, adjacent change views. | Project/task navigation, one main conversation, changes beside it. | +| [Codex App Review](https://www.reddit.com/r/codex/comments/1qvc1qf/codex_app_review/), 2026-02-04; Exa excerpt | Projects gathered in one place; completion notifications named as the feature the author "really needed"; a request that all limits be shown consistently. | Recent tasks, an attention inbox, completion notifications early, and usage shown consistently or labelled unknown. | +| [Antigravity switch discussion](https://www.reddit.com/r/google_antigravity/comments/1r7kut6/just_switched_to_google_antigravity_from_claude/), 2026-02-17; direct thread read | Planning, granular control, and visibility. Replies agree on control while strongly disagreeing on model quality. | Reviewable plans and visible scope; do not use model rankings to justify the UI. | +| [Antigravity appreciation](https://www.reddit.com/r/google_antigravity/comments/1twhg6b/appreciation_post_for_antigravity/), 2026-06-04; web-indexed post | Describing features conversationally and reviewing work as it proceeds. | Ordinary-language goals and accessible intermediate results. | +| [Claude Code: plan mode anyone?](https://www.reddit.com/r/ClaudeCode/comments/1nebqsp/plan_mode_anyone/), 2025-09-11; direct thread read | Refining plans, implementing in chunks, reviewing changes. Some replies find extended planning excessive. | Clear plan/run distinction and incremental progress; no compulsory ceremony for small requests. | +| [Claude Code planning workflow](https://www.reddit.com/r/ClaudeAI/comments/1ujkay1/whats_your_current_claude_code_planning_workflow/), 2026-06-30; Exa excerpt | Concern about retaining plans across sessions and managing context. | Durable task goals, plan revisions, resumable task summaries. | +| [The Orchestrator Seat](https://sdd.sh/2026/04/claude-code-desktop-redesign-parallel-sessions/), 2026-04-17; Exa excerpt | Status filtering (running, waiting for input, complete, failed) called "underrated" for finding the session that needs a decision; side chats that do not pollute the main context. | First-class status filter on the task list; run discussion kept out of the execution transcript. | + +### What went wrong elsewhere + +| Source and publication date | Failure observed | Rule adopted here | +|---|---|---| +| [Codex Desktop issue 40830](https://github.com/openai/codex/issues/40830), undated GitHub issue | Review pane labelled "Last turn" for a historical turn while rendering the newest worktree's diff. Reporter calls it a data-integrity defect and asks for fail-closed behaviour plus a two-turns-disjoint-files regression test. | Every Changes view is bound to one run and evidence sequence; header and hunks come from the same source; fail closed when unresolved. | +| [Codex Desktop issue 25823](https://github.com/openai/codex/issues/25823), undated GitHub issue | On Windows/WSL the Review summary diffed against git's empty tree, reporting the whole repository as deleted and stalling the app. | Define the diff base explicitly and test it on Windows paths. Windows is TORQ's production chat target. | +| [How am I supposed to review changes in this tiny 3 lines window?](https://www.reddit.com/r/codex/comments/1s7hw0a/how_i_am_supposed_to_review_changes_in_this_tiny/), 2026-03-30; Exa excerpt | Changes shown in a small inline preview forced accept-then-review in the git pane, mixed with earlier changes. The author stopped using the app. | The review panel is full height by default in the Needs review state and scoped to the current run's changes. | +| [New "improved" appearance of the app](https://www.reddit.com/r/ClaudeCode/comments/1smdnxg/new_improved_appearance_of_the_app/), 2026-04-15, and [Desktop UX Redesign Disaster](https://www.reddit.com/r/claude/comments/1sn4l00/desktop_ux_redesign_disaster_part_one_blue/), 2026-04-16; Exa excerpts | Users lost their layout mid-work with no way back; one compares it to cockpit instruments changing in flight. | New Home is opt-in first; the chosen default view persists per user; Fleet stays one click away. | +| [Claude Code issue 55936](https://github.com/anthropics/claude-code/issues/55936), reported around May 2026 | "New session" doubled as the folder picker, and recent sessions were conflated with recent folders. | Open project and New task are separate entry points; Recent projects and Recent tasks are separate lists. | +| [Claude Code Desktop after the redesign](https://nimbalyst.com/blog/claude-code-desktop-after-the-redesign/), 2026-04-21; vendor blog with a commercial interest | After a week, dozens of closed sessions cannot be found; browsing is not searching. Separates "running an agent" from "managing agents". | Tasks carry durable titles and goals; search over them lands in P3. Do not build an agent-management console before the single-task journey works. | +| [CopilotKit governed action approval](https://docs.copilotkit.ai/human-in-the-loop/governed-actions), vendor documentation, undated | Approval cards carry what, why, which policy decision, and what happens next, with allow, deny, and require-approval verdicts. | Blocked and pending actions carry a consequence and a policy reference, not only a message. | +| [Cursor cloud agent capabilities](https://www.learncursor.dev/learn/cursor-agents/cloud-agent-capabilities), 2026-06-26; third-party guide | Agents attach screenshots, logs, and recordings to the pull request so a reviewer can validate without checking out the branch. | The Checks panel shows the command, exit code, and evidence sequence, never a bare pass badge. | + +[Google's artifact documentation](https://antigravity.google/docs/artifacts/), accessed 2026-09-16, separately confirms plans, diffs, browser recordings, and artifact feedback as product concepts. Vendor documentation corroborates a pattern; it is not customer satisfaction evidence. + +Counterevidence still matters inside the positive threads: the Codex thread includes performance and keyboard complaints; the Claude thread questions planning overhead; the Antigravity thread disputes model comparisons. Copy the interaction patterns, not every feature or enthusiastic claim. + +## Design principles + +1. **The UI never claims more than the server can prove.** Draft, discussion, execution, verification, and acceptance are distinct claims with distinct labels. +2. **Every displayed artifact names its source.** A diff, a check, or a plan revision is bound to a run and an evidence sequence, and the binding is visible. +3. **Fail closed, visibly.** When a panel cannot resolve its source, it shows an error and disables the action. It never shows something adjacent and plausible. +4. **The next action is always on screen.** Every state has one main message and one primary action, with the reason and remedy when blocked. +5. **Drafts are never lost and never smuggled.** A draft survives setup, reconnect, and failure, and it never enters signed evidence until a start is recorded once. +6. **Change is opt-in.** Existing operators keep Fleet until they choose Home. Their choice persists. +7. **Plain words first, canonical terms one click away.** Backend vocabulary stays available in Details for operators and support. + +## Intended experience + +Assumption: the primary user is a builder who wants to describe work and supervise its completion. An expert operator remains a secondary user with access to Fleet. This assumption follows the user's stated desire to type and build and should be tested before expanding scope. + +### Sidebar and navigation + +```text +TORQ Project: Torq-CLI v | Settings + +Open project Recent projects: Torq-CLI, fleet-ui, demo (sample) ++ New task +Tasks [All] [Working] [Needs review] [Complete] [Failed] [Disconnected] + ● Add password reset Needs review 2 min ago + ○ Fix flaky receipt test Working step 3 of 5 + ✓ Rename settlement fields Complete yesterday +Fleet details +``` + +Open project and New task are separate actions. The status filter uses the same words as the state table below. Needs review sorts to the top by default. The sidebar collapses to a drawer on narrow screens. + +### Home: empty state + +```text +What would you like to work on in Torq-CLI? + +[ Describe a feature, bug, or question... ] +[ Fix a bug ] [ Plan a feature ] [ Review code ] Mode: Plan first v + +[ Continue ] Draft saved locally. Nothing is sent until you continue. + +Setup: provider not connected. [ Connect a provider ] [ Explore the sample task ] +``` + +With no provider configured, Continue saves the draft and opens setup. It must not appear to send an AI message successfully. Explore the sample task opens an explicitly read-only sample with a persistent "Sample" label. No demo is silently seeded as the user's working project. + +### Active task: Working + +```text +Add password reset Working · step 3 of 5 + +Conversation | Progress [ Details v ] + You: Add a password reset flow using the | ✓ Read auth module + existing email service. | ✓ Plan accepted (rev 2) + TORQ: Plan accepted. Starting step 3, | ● Writing reset handler + writing the reset handler. | ○ Add tests + | ○ Run checks + [ Add a follow-up for the next step... ] | + Sends when the current step finishes. | Usage: unknown until settled + [ Stop ] | Evidence: seq 41, verified +``` + +The composer stays editable while work runs. The helper text states exactly when the follow-up will be delivered; it never implies immediate injection. Stop shows "Stop requested" until ownership confirms termination. Streamed output is labelled provisional until it is settled into evidence. + +### Active task: Needs review + +```text +Add password reset Needs your review + +Conversation (collapsed) | [ Plan ] [ Changes ] [ Checks ] run-0042 · seq 44 + | + Show conversation > | Changes: 4 files, +126 / -6, bound to seq 44 + | src/auth/reset.py +88 -0 + | src/auth/routes.py +21 -3 + | tests/test_reset.py +17 -0 + | docs/auth.md +0 -3 + | ┌───────────────────────────────────────────┐ + | │ full-height diff of the selected file │ + | │ ... │ + | └───────────────────────────────────────────┘ + | + | Checks: pytest tests/test_reset.py exit 0 seq 43 + | ruff check src/auth exit 1 seq 43 + | 1 check failed. Not marked passed. + | +[ Accept changes ] [ Request a correction ] [ Stop ] +Accepting records your decision in evidence. It does not push, merge, or deploy. +``` + +The review panel takes the full content width; the conversation collapses to a toggle. The header, file list, counts, and hunks all come from the same evidence sequence, which is printed. A failed check stays visibly failed. The primary action states its consequence in one sentence. If any artifact cannot be resolved, the panel shows "Changes for this run could not be loaded" and the Accept action is disabled. + +### Blocked and recovery states + +```text +Add password reset Paused + +This task's history could not be verified. +Why: the receipt chain for run-0042 ended before seq 44. +What you can do: [ Inspect details ] [ Choose another task ] +Your draft is saved. +``` + +Every blocked state shows why, what the user can do, and that the draft is safe. + +### Narrow screens and accessibility + +On widths under a laptop breakpoint, the sidebar becomes a drawer and the Conversation, Plan, Changes, and Checks views become tabs; three columns are never squeezed. Default to the system theme and retain light/dark selection. Use sentence case, readable body text, clear focus rings, and semantic state labels. Reserve red for actual errors and amber for a required user action. Avoid decorative grids and repeated status badges. Preserve keyboard navigation, reduced-motion support, and screen-reader announcements for state changes without reading every streamed token. + +### Vocabulary + +| Fleet term | Workspace label | Where the canonical term remains | +|---|---|---| +| Governed lanes | Team activity | Details | +| Operator ledger | Needs your attention | Details | +| Evidence-backed usage | Usage | Details, with source | +| Verified seq | Evidence details, with the seq number shown | Review panel header and Details | +| Governed conversation | Discuss this run | Composer purpose label | +| Run root | Project | Details | + +A completed process, a verified record, a passed check, and accepted changes remain four distinct claims with four distinct labels. + +## Capabilities and state contract + +Do not model everything as one `runtimeAvailable` boolean. Introduce an additive server-owned capabilities response, proposed `GET /api/v1/workspace`, with independent run selection, provider configuration, authorization, verification, and execution readiness. + +Suggested fields: `selected_project_id`, `selected_run_id`, `draft_supported`, `can_discuss_run`, `can_start_task`, `can_cancel`, `can_accept`, `attachment_types`, `limits`, `usage_source`, `default_view`, and structured `pending_actions` and `blocked_actions`. Each action entry carries `action`, `verdict` (`allow`, `deny`, `require_approval`), `reason_code`, `message`, `consequence`, `remediation`, and `policy_ref`. Provider configuration is not proof of successful authentication; expose unknown separately from ready. All mutations recheck their prerequisites server-side. + +| State | Main message | Available action | +|---|---|---| +| No project | Open a project to get started. | Open project; explore sample; edit draft. | +| No task | What would you like to work on? | Edit draft; continue. | +| Provider missing | Connect a provider to continue. | Preserve draft; open setup. | +| Sample | You're exploring a sample task. | Read sample; start a real task. | +| Collection selected | Choose a task to open. | Select validated run entry. | +| Run not trusted | This task's history could not be verified. | Inspect details; select another task; explicit recovery where supported. | +| Ready for run discussion | Ask about this task. | Submit discussion; no claim of file editing. | +| Working | TORQ is working on step N of M. | Edit a follow-up draft; stop; inspect progress. | +| Needs review | Review the plan, changes, or checks to continue. | Exact eligible action with scope and consequence. | +| Complete | This task is complete. | Open result; start a follow-up task. | +| Failed | This task stopped with an error. | Read the error; retry where supported; start a new task. | +| Disconnected | Reconnect to check task status. | Preserve draft; refresh session; no blind replay. | +| Stop requested | Stop requested; process status is not confirmed. | Recovery workflow; no successful-stop claim. | + +Persist drafts in a separate workspace draft store with an explicit retention and delete policy. Never insert unsent drafts into signed run evidence. In the initial cosmetic phase, in-memory drafting is acceptable but must not claim reload persistence. A draft revision transferred into a run is recorded once, with its task and run identity; double-click and retry must not start duplicate jobs. + +## Artifact integrity rules + +These apply to the Plan, Changes, and Checks views and are release gates for P3. + +- **Binding.** Each view resolves from `(run_id, evidence_seq)`. The pair is printed in the panel header. +- **Single source.** File list, counts, paths, and hunks are derived from the same resolved artifact. No view mixes a header from one sequence with content from another. +- **Diff base.** The base is the run-start snapshot recorded in evidence, never HEAD, origin, or an empty tree. The base identity is available in Details. +- **Scope.** The default Changes view shows only this run's changes. Earlier runs are reachable through the task list, never merged into the current view. +- **Fail closed.** If resolution fails, the panel shows an explicit error and disables Accept. It never falls back to the latest available artifact. +- **Checks are evidence, not badges.** Each check shows its command, exit code, and sequence. A missing check is stated as missing. A failed check cannot be hidden by a summary state. +- **Regression tests.** Two runs with disjoint file sets each resolve to their own diff; a run with a missing artifact fails closed; the Windows path form of the run-start snapshot resolves correctly. + +## Technical design by layer + +| Layer | Responsibilities and interfaces | Failures, tests, and dependencies | +|---|---|---| +| Core logic / agent behavior | Add workspace and task-start application services. Reuse `application/setup.py`, `run_command.py`, and `live_runtime.py` where applicable. Keep existing run conversation separate from execution. | Audit the actual start lifecycle before wiring it; prove first-run bootstrapping works without a prior completed run. Refuse unsupported execution and stale plan revisions. | +| Data and integrations | Opaque project and run IDs map to server-approved directories. Capability metadata comes from adapters and policy. Provider credentials stay server-side. Artifact resolution is by `(run_id, evidence_seq)`. | Reject path traversal and invalid roots. Do not probe a paid provider merely by opening Home. Explain authentication, quota, and connectivity failures separately. Test artifact resolution on Windows paths. | +| State and memory | Separate draft, accepted plan revision, run binding, provisional output, and signed terminal transcript. Idempotent start tokens and restart recovery. Per-user default view and status filter preferences. | Test reload, two tabs, repeated start, crash after acceptance, and pending plan revision. Reuse existing single-owner guarantees. | +| Interface surfaces | Rework bundled HTML/CSS/JS; introduce the workspace view and retain Fleet details. New workspace and start routes are proposals, not existing APIs. No framework migration needed. | Test empty state, wrong root, provider mismatch, narrow layout, focus, drafts during work, full-height review, and truthful disabled actions. | +| Governance and safety | Reuse verification, certificate, exact-origin mutations, session rotation, and process ownership. A task-start coordinator invokes the existing authority path; it never manufactures evidence to unlock chat. Accept records a decision in evidence and performs no push, merge, or deploy. | Negative cases for forged certificates, stale sessions, unauthorized roots, invalid providers, start replay, and accept replay. Windows is the current production chat target; other platforms need explicit capability refusal. | +| Observability and feedback | Show next action, timestamps, reconnect status, check results with exit codes, usage with its source, and expandable evidence. Completion and needs-review notifications behind a browser permission prompt. Redacted local UX events for diagnostics. | No prompts, credentials, or full paths in analytics or notifications. Unknown cost remains unknown. Provisional output cannot become verified solely because it rendered. | +| Delivery and operations | Ship incrementally in the existing wheel-bundled app. Home is opt-in with a persisted default; Fleet remains reachable. Launcher opens Home or an explicitly selected run. | Test installed-wheel assets, bootstrap and session behavior, route compatibility, restart, and default-view persistence. Roll back navigation separately from stored tasks; never rewrite signed evidence. | + +The first-run lifecycle is the largest engineering uncertainty. The current CLI chat is bound to existing run evidence and uses the run directory as its working directory. Repository access, plan generation before execution, and the transition into a governed builder need explicit service contracts. Do not implement this by removing `--tools ""` or changing plan mode on the chat adapter. + +## Phased delivery and exit gates + +1. **P0: truthful entry and recovery.** Explicit sample, empty, and wrong-root states; individual run selection; separate Open project and New task; plain-language remedies with consequence and remediation; provider-driven attachment controls. Correct launcher behaviour without silently selecting the newest run or killing an unrelated port owner. Exit: no dead-end unexplained chat; selected root and provider capabilities are truthful. Relative effort: small to medium. +2. **P1: task workspace shell.** One main composer, task list with status filter, task titles, attention ordering, collapsible details, drafts editable during work, opt-in Home with a persisted default view, and completion and needs-review notifications behind a permission prompt. Exit: keyboard and narrow-screen flows work; existing Fleet users see no change until they opt in; Fleet controls retain their meaning. Relative effort: medium. +3. **P2: actual goal-to-run journey.** Project selection, setup status, durable drafts, explicit execution policy and scope, and idempotent creation through existing governed services. Exit: a clean configured installation starts and completes one real bounded task through the dashboard without manual run-directory or certificate handling. This phase is necessary for "type and build"; earlier phases alone are not completion. Relative effort: large; lifecycle audit required before scheduling. +4. **P3: review and refinement.** Plan, Changes, and Checks views under the artifact integrity rules; full-height review layout; revision requests; accept recorded as evidence; task continuation; search over task titles and goals. Exit: the user can inspect what changed and which checks ran with their exit codes, request a correction, find a past task by its goal, and return to it. Never make push, merge, or deploy implicit in accepting. Relative effort: medium to large depending on existing artifact availability. + +No calendar estimate is asserted; the live-start integration has not been implemented or timed. Non-goals: rebuilding an IDE, adding new providers, bypassing certificates, simultaneous chat execution, cloud hosting, mobile applications, an agent-management console, or automatic merge and deployment. + +## Acceptance and validation + +- A new user can enter a goal without an existing run; setup preserves it and explains the next required step. +- Open project and New task are distinct; recent projects and recent tasks are distinct lists. +- Sample content is visibly labelled and cannot dispatch live work. +- The selected run is an actual run directory, never its collection parent. +- UI actions match server capabilities, including Claude's current attachment restriction. +- Every blocked or pending action shows a reason, a consequence, and a remedy. +- Planning and discussion cannot be mistaken for implementation; build starts require the real execution path. +- Signed history is never backfilled from untrusted drafts or provisional stream output. +- Failed setup, start, or reconnect cannot silently lose a draft or duplicate execution. +- Stop remains pending until ownership confirms termination; uncertain cancellation remains visible. +- Every Changes and Checks view prints its run and evidence sequence, resolves from a single source, and fails closed when unresolved. +- The diff base is the recorded run-start snapshot and resolves on Windows paths. +- A failed check is never summarised as passed; a missing check is stated as missing. +- Accept records a decision and performs no push, merge, or deploy; a repeated Accept is idempotent. +- Existing users keep Fleet as their default until they choose Home; the choice persists across restarts. +- The task list filters by the state vocabulary in this document, and Needs review sorts first by default. +- At a narrow phone width, laptop widths, 200% zoom, and keyboard-only use, the composer, review panel, and recovery action stay usable. +- Retain existing chat and Fleet JS harnesses and HTTP and evidence tests; add lifecycle tests for the workspace contract and the artifact integrity regression tests. Include one installed-wheel browser flow and one authorized live bounded task before claiming end-to-end completion. + +Proposed usability targets, not measured facts: in five moderated sessions, at least four users identify the next action without explaining run roots or certificates, at least four correctly distinguish Plan, Run, and Sample, and at least four can say from the review screen whether the checks passed and what accepting will do. Measure time to first saved goal, setup abandonment, blocked-chat recurrence, review completion, and time to find a task started the previous day. Validate the main journey before optimising parallel-task features. + +Review-time verification: the existing chat and Fleet JavaScript runtime wrappers passed in the focused pytest attempts. The combined provider/UI selection did not pass as a whole: two provider tests could not create temporary directories because of Windows access-denied errors, including a retry using a workspace basetemp. This remains open and must be resolved or explained before P2 scheduling. No live browser or provider integration was tested. These results are baseline checks, not verification of the proposed design. + +## Stress test + +- **Contrarian, major:** a nicer composer still fails if no start-task service exists. Action: make the clean-install journey a release gate. What would change my mind: an already-working end-to-end dashboard start path. +- **Integrity, major:** a review panel that shows the wrong diff is worse than no review panel, and a shipping competitor has done exactly that. Action: artifact integrity rules are P3 release gates with regression tests. What would change my mind: nothing; this is the product's core promise. +- **Expansionist, minor:** task history and artifacts could make governed execution approachable to more builders, but an agent-management console would recreate clutter. Action: defer orchestration UX; ship search before boards. What would change my mind: observed frequent multi-task demand after first-task success. +- **First principles, major:** a user must express intent before a run can exist. Action: separate draft and setup authority from governed execution authority. What would change my mind: evidence that this dashboard is explicitly only an operations viewer. +- **Researcher, major:** community posts do not validate this audience or implementation. Action: test a clickable journey with target users. What would change my mind: direct task-completion evidence from those users. +- **Existing operator, major:** a forced default switch would repeat the redesign backlash observed elsewhere. Action: opt-in Home with a persisted default. What would change my mind: no active Fleet users at the time of shipping. +- **Buyer, major:** requiring CLI setup and certificate terminology at first use contradicts the intended experience. Action: guide setup and preserve the goal. What would change my mind: target operators consistently prefer CLI provisioning. + +**The verdict: RESHAPE.** + +**Why:** retain the evidence architecture while changing the entry point, adding the missing creation workflow, and making the evidence visible where the user makes decisions. + +**The brutal truth:** the current dashboard exposes internal correctness more clearly than user intent. Cosmetic changes alone cannot turn a restricted run conversation into a build agent, and a review surface that is not bound to evidence would discard the product's main advantage. + +**The riskiest assumption:** the governed execution lifecycle can support a straightforward first-task flow without weakening its guarantees. + +**The 48-hour cheap test:** prototype the empty Home, setup-needed, working, and needs-review states with the full-height review panel; run moderated task attempts; and run a service-level spike that starts one bounded governed task from a draft and resolves its Changes view from `(run_id, evidence_seq)`. This is a proposed experiment window, not a delivery estimate. + +**What would change the verdict:** if real run creation cannot be made available through a supported service, ship a clearly labelled run viewer with the artifact integrity rules and do not market it as a build workspace. + +Next action: implement P0 and the first-run lifecycle spike before committing to the full visual redesign. From a6716dcf2c585ac3a2e19d4317a56af6ba3ba741 Mon Sep 17 00:00:00 2001 From: King Flowers Date: Wed, 16 Sep 2026 18:38:34 -0500 Subject: [PATCH 2/6] docs: record that the provider test failure does not reproduce; drop it as a P2 blocker Co-Authored-By: Claude Fable 5.1 --- docs/plans/2026-09-16-dashboard-ux-plan.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plans/2026-09-16-dashboard-ux-plan.md b/docs/plans/2026-09-16-dashboard-ux-plan.md index 5bbfa86..f9ebfb0 100644 --- a/docs/plans/2026-09-16-dashboard-ux-plan.md +++ b/docs/plans/2026-09-16-dashboard-ux-plan.md @@ -282,7 +282,7 @@ No calendar estimate is asserted; the live-start integration has not been implem Proposed usability targets, not measured facts: in five moderated sessions, at least four users identify the next action without explaining run roots or certificates, at least four correctly distinguish Plan, Run, and Sample, and at least four can say from the review screen whether the checks passed and what accepting will do. Measure time to first saved goal, setup abandonment, blocked-chat recurrence, review completion, and time to find a task started the previous day. Validate the main journey before optimising parallel-task features. -Review-time verification: the existing chat and Fleet JavaScript runtime wrappers passed in the focused pytest attempts. The combined provider/UI selection did not pass as a whole: two provider tests could not create temporary directories because of Windows access-denied errors, including a retry using a workspace basetemp. This remains open and must be resolved or explained before P2 scheduling. No live browser or provider integration was tested. These results are baseline checks, not verification of the proposed design. +Review-time verification: in the first pass, two provider tests could not create temporary directories because of Windows access-denied errors, including a retry using a workspace basetemp. A clean re-run later on 2026-09-16 of every `tests/test_chat_*.py` and `tests/test_fleet_*.py` file passed in full (165 passed), and the provider selection alone passed with only the Linux and macOS platform gates skipped. The earlier failure is treated as machine state at review time, not a repository defect, and is not a P2 blocker. If it recurs, capture the temp path and the failing test name before retrying. No live browser or provider integration was tested. These results are baseline checks, not verification of the proposed design. ## Stress test From ff7fb346d43877ba73432b72c8c58510e7435855 Mon Sep 17 00:00:00 2001 From: King Flowers Date: Wed, 16 Sep 2026 21:32:04 -0500 Subject: [PATCH 3/6] feat: add governed dashboard workspace and P2 candidate builds --- README.md | 39 + ...26-09-16-dashboard-browser-verification.md | 34 + .../2026-09-16-dashboard-builder-handoff.md | 83 ++ ...2026-09-16-dashboard-g1d-build-contract.md | 41 + docs/plans/2026-09-16-dashboard-g1r-review.md | 25 + docs/plans/2026-09-16-dashboard-g2a-review.md | 29 + ...2026-09-16-dashboard-p2-builder-handoff.md | 77 ++ .../plans/2026-09-16-dashboard-p2-contract.md | 87 ++ ...026-09-16-dashboard-p2-g1d-verification.md | 42 + .../2026-09-16-dashboard-p2-g1r-review.md | 29 + .../2026-09-16-dashboard-p2-g2a-review.md | 102 +++ docs/plans/2026-09-16-dashboard-ux-plan.md | 18 +- docs/plans/2026-09-16-pr80-g1d-review.md | 24 + docs/releases/torq-cli-v0.2.0.md | 6 +- src/torq_cli/adapters/candidate_provider.py | 209 +++++ src/torq_cli/application/candidate_tasks.py | 760 ++++++++++++++++++ src/torq_cli/application/task_store.py | 220 +++++ src/torq_cli/application/workspace.py | 188 +++++ src/torq_cli/checkers/__init__.py | 1 + src/torq_cli/checkers/structural.py | 68 ++ src/torq_cli/data/fleet/chat.css | 178 ++++ src/torq_cli/data/fleet/chat.js | 283 ++++++- src/torq_cli/data/fleet/index.html | 137 +++- src/torq_cli/data/fleet/task.css | 39 + src/torq_cli/data/fleet/task.js | 268 ++++++ src/torq_cli/domain/run_evidence.py | 11 + src/torq_cli/domain/task_evidence.py | 376 +++++++++ src/torq_cli/interfaces/cli.py | 119 ++- src/torq_cli/interfaces/fleet_http.py | 365 ++++++++- src/torq_cli/safety/receipts.py | 73 +- src/torq_cli/safety/state_lock.py | 68 ++ src/torq_cli/safety/task_workspace.py | 364 +++++++++ tests/fixtures/candidate_provider.py | 25 + tests/js/chat_runtime.test.cjs | 63 +- tests/js/task_resume.test.cjs | 71 ++ tests/js/task_runtime.test.cjs | 48 ++ tests/test_candidate_task_integration.py | 190 +++++ tests/test_candidate_tasks.py | 111 +++ tests/test_chat_cli.py | 64 ++ tests/test_chat_http.py | 6 + tests/test_fleet_ui.py | 56 ++ tests/test_hermetic.py | 13 + tests/test_task_cli.py | 54 ++ tests/test_task_evidence.py | 153 ++++ tests/test_task_http.py | 110 +++ tests/test_task_ui_runtime.py | 43 + tests/test_workspace.py | 306 +++++++ 47 files changed, 5634 insertions(+), 42 deletions(-) create mode 100644 docs/plans/2026-09-16-dashboard-browser-verification.md create mode 100644 docs/plans/2026-09-16-dashboard-builder-handoff.md create mode 100644 docs/plans/2026-09-16-dashboard-g1d-build-contract.md create mode 100644 docs/plans/2026-09-16-dashboard-g1r-review.md create mode 100644 docs/plans/2026-09-16-dashboard-g2a-review.md create mode 100644 docs/plans/2026-09-16-dashboard-p2-builder-handoff.md create mode 100644 docs/plans/2026-09-16-dashboard-p2-contract.md create mode 100644 docs/plans/2026-09-16-dashboard-p2-g1d-verification.md create mode 100644 docs/plans/2026-09-16-dashboard-p2-g1r-review.md create mode 100644 docs/plans/2026-09-16-dashboard-p2-g2a-review.md create mode 100644 docs/plans/2026-09-16-pr80-g1d-review.md create mode 100644 src/torq_cli/adapters/candidate_provider.py create mode 100644 src/torq_cli/application/candidate_tasks.py create mode 100644 src/torq_cli/application/task_store.py create mode 100644 src/torq_cli/application/workspace.py create mode 100644 src/torq_cli/checkers/__init__.py create mode 100644 src/torq_cli/checkers/structural.py create mode 100644 src/torq_cli/data/fleet/task.css create mode 100644 src/torq_cli/data/fleet/task.js create mode 100644 src/torq_cli/domain/task_evidence.py create mode 100644 src/torq_cli/safety/state_lock.py create mode 100644 src/torq_cli/safety/task_workspace.py create mode 100644 tests/fixtures/candidate_provider.py create mode 100644 tests/js/task_resume.test.cjs create mode 100644 tests/js/task_runtime.test.cjs create mode 100644 tests/test_candidate_task_integration.py create mode 100644 tests/test_candidate_tasks.py create mode 100644 tests/test_task_cli.py create mode 100644 tests/test_task_evidence.py create mode 100644 tests/test_task_http.py create mode 100644 tests/test_task_ui_runtime.py create mode 100644 tests/test_workspace.py diff --git a/README.md b/README.md index 8b8fbfd..8ed3138 100644 --- a/README.md +++ b/README.md @@ -57,11 +57,50 @@ $ torq evidence verify --run-root torq-demo-runs/run-0d04c989291241d58830a964ce5 | `torq run` | The governed orchestration boundary. Dry-run by default; live needs `--allow-live` and `--policy-allow-live`. | | `torq evidence verify --run-root DIR` | Verify a run's receipt chain and artifacts. | | `torq fleet --run-root DIR --serve` | Evidence-backed Fleet control surface with attended chat. | +| `torq fleet --serve --task-project ID=DIR ...` | Open New task for bounded candidate generation and structural checks. | | `torq setup` / `torq auth` | Interactive config; credentials stored as opaque handles in the OS keychain or an attended encrypted file vault. | | `torq status` / `torq profile validate` / `torq harness inspect` | Attest the machine, the role profile, and the live harness before a run. | | `torq config import-v5-*` | Import normalized or raw Console V5 configuration (read-only projection). | | `torq trust readiness` | Report production-trust gaps (signing identity, receipt anchor). | +### Workspace dashboard + +`torq fleet --run-root DIR --serve` opens Fleet by default. Choose **Workspace** in +the header for a calmer, conversation-first view; the choice is saved locally. +`DIR` must be one individual TORQ run, not its parent collection. If a collection +is selected, Workspace lists safe relative run IDs and shows the exact relaunch +form without choosing a run automatically. + +Run discussion is opt-in and remains narrower than a build agent: + +```powershell +torq fleet --run-root .\torq-demo-runs\run-0123 --serve ` + --chat-provider claude --chat-model MODEL +``` + +Workspace can discuss verified run history when the configured provider and +session permit it. Discussion does not create or apply a change. Unsent text is stored only in browser `sessionStorage`, scoped to an +opaque identity for the selected root; **Clear draft** removes that scoped text. +Provider keys, attachments, and filesystem paths are never stored there. + +### New task + +New task is a separate opt-in launch and does not require an existing run directory: + +```powershell +torq fleet --serve --task-project app=C:\work\app ` + --task-provider claude --task-model MODEL ` + --task-claude-bin C:\Users\you\.local\bin\claude.exe +``` + +TORQ saves the goal and exact relative file scope under an owner-only application +state directory. Start authorizes one tools-off provider request. TORQ writes the +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. + ## Safety model - Agents never commit, push, or merge. The worktree stays unchanged until an audited, tree-pinned proposal receives explicit approval. diff --git a/docs/plans/2026-09-16-dashboard-browser-verification.md b/docs/plans/2026-09-16-dashboard-browser-verification.md new file mode 100644 index 0000000..96596b9 --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-browser-verification.md @@ -0,0 +1,34 @@ +# G1D independent browser verification + +Scope: bounded P0/P1 dashboard on implementation branch `feat/dashboard-workspace-pr80`. Local Python Fleet server at 127.0.0.1:8878 with a missing run root, authenticated through its real bootstrap exchange. No provider or live build was invoked. Playwright was used because agent-browser CLI was not installed. + +## Baseline + +The original page led with operational telemetry, disabled the input, and repeatedly requested unavailable chat SSE. At a 320px viewport the composer began around y=1614px. Screenshots are local working artifacts `tmp/dashboard-before.png` and `tmp/dashboard-before-mobile.png`. + +## Checks observed after implementation + +- New browser state defaults to Fleet, with the actual legacy composer and transcript still present. +- Workspace opt-in survives reload. Switching views retains the same draft and moves the real composer back to its Fleet slot correctly. +- With a missing run root, input is editable, Send is disabled, metadata explains the missing folder, attachments are unavailable, and execution/start capabilities are false. +- Typed draft survives reload with a truthful restored-for-this-tab status. Clear draft remains cleared after reload. +- No `/api/v1/chat/events` request is made when the configured runtime is unavailable. +- At 320px viewport width, document scroll width is 320px. The first implementation places next-action guidance around y=179 and the composer around y=500; final styling is checked separately below. +- Authenticated workspace metadata contains an opaque workspace identifier, reason/remedy, root kind and capabilities rather than the raw filesystem path. + +## Fault-injected UI checks + +These use browser-local synthetic metadata/transport responses. They demonstrate frontend behavior, not authenticated provider execution. + +- Changed the response identity from root A to root B: B opened with an empty draft. Entered B draft, restored A identity, and A's original text returned. No cross-root carryover. +- Deferred synthetic Send acceptance, delivered a stale no-active-turn snapshot, typed a newer draft, and attempted Send again. Exactly one POST reached the synthetic transport; the newer revision remained after acceptance and input stayed editable. +- Forced browser sessionStorage writes to throw QuotaExceededError. Draft stayed in memory and status changed to Held in this tab only; no false persistent-save claim. +- Returned HTTP 401 for workspace refresh. Draft stayed intact, Send remained disabled, and the UI explained the disconnect. Restoring the response recovered metadata. The injected HTTP failure generated the expected browser network error, not a JavaScript exception. + +## Final packaged verification + +Final visual refinements and Terra's backend eligibility findings were closed. G2A independently approved the bounded change after 31 targeted tests. + +Installed `tmp/dist-dashboard/torq_cli-0.2.0-py3-none-any.whl` without dependencies into `tmp/dashboard-wheel-install` and launched Python with isolated import resolution. The printed module path confirmed the server used that installed package. Authenticated browser smoke at 127.0.0.1:8879 confirmed Workspace and its draft survive reload, the missing-root input remains editable, Send remains disabled, execution capability is false, and the verbose evidence caption is hidden. At 320px, document width equals viewport width. Final packaged screenshots: `tmp/dashboard-wheel-mobile.png` and `tmp/dashboard-wheel-desktop.png`. + +Additional source UI checks covered dark theme, reduced motion, and CSS zoom at 200 percent without horizontal overflow. CSS zoom was used, not browser toolbar zoom. The primary setup action opens the setup details. No live provider, file editing, command execution, governed apply, or P2/P3 completion is claimed by these checks. diff --git a/docs/plans/2026-09-16-dashboard-builder-handoff.md b/docs/plans/2026-09-16-dashboard-builder-handoff.md new file mode 100644 index 0000000..b0b5fbd --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-builder-handoff.md @@ -0,0 +1,83 @@ +# Dashboard bounded P0/P1 builder handoff + +Date: 2026-09-16 +Branch: `feat/dashboard-workspace-pr80` +Baseline: `a6716dcf2c585ac3a2e19d4317a56af6ba3ba741` + +## Delivered scope + +This increment delivers the bounded P0/P1 contract: an opt-in Workspace view for +discussing an existing verified run, truthful authenticated workspace metadata, +safe root and collection classification, provider-driven attachment capability, +fresh submit eligibility checks, and browser-session drafts scoped to an opaque +workspace identity. Fleet remains the initial view and keeps its existing +operational controls. + +The CLI now classifies and verifies the selected root before constructing the key +store, chat evidence journal, or provider. The HTTP submit route independently +rechecks root trust, lifecycle writability, chat projection availability, and +active-turn state before forwarding a message. Cancellation remains available +when the session permits it even if sending is unavailable. + +The Workspace UI uses the real composer and transcript. It keeps draft editing +available while Send is gated, preserves distinct drafts per workspace for the +current browser tab, avoids unsupported event-stream retries, exposes actionable +setup recovery, and keeps provider/auth/execution claims fail-closed. + +## Changed files + +- `src/torq_cli/application/workspace.py`: bounded root discovery, link/reparse + rejection, verified-run classification, safe run identifiers, and opaque stable + workspace identity. +- `src/torq_cli/interfaces/cli.py`: root/trust preflight before identity, evidence, + or provider construction while retaining existing model/platform diagnostics. +- `src/torq_cli/interfaces/fleet_http.py`: authenticated `/api/v1/workspace` + metadata and fresh direct-submit eligibility enforcement. +- `src/torq_cli/data/fleet/index.html`, `chat.css`, and `chat.js`: opt-in Workspace, + responsive presentation, capability-driven controls, recovery actions, and + scoped resilient drafts. +- `tests/test_workspace.py`, `tests/test_chat_cli.py`, `tests/test_chat_http.py`, + `tests/test_fleet_ui.py`, and `tests/js/chat_runtime.test.cjs`: root, trust, + mutation-order, HTTP gate, capability, navigation, draft, and in-flight + regressions. +- `README.md` and `docs/plans/2026-09-16-dashboard-ux-plan.md`: launch guidance + and corrected actual phase scope. + +## Verification + +- `python -m pytest -p no:cacheprovider tests -k "workspace or chat or fleet"` + — **186 passed, 841 deselected in 50.17s**. This run used normal Windows temp + access because the restricted sandbox cannot create pytest temporary folders. +- `python -m ruff check src/torq_cli/application/workspace.py src/torq_cli/interfaces/cli.py src/torq_cli/interfaces/fleet_http.py tests/test_workspace.py tests/test_chat_cli.py tests/test_chat_http.py tests/test_fleet_ui.py` + — **passed**. +- `python -m mypy --cache-dir tmp/mypy-dashboard-review src` — **passed, no + issues in 82 source files** (independent G1D run). +- `node tests\js\chat_runtime.test.cjs src\torq_cli\data\fleet\chat.js` — + **passed**. +- `node --check src\torq_cli\data\fleet\chat.js` and `git diff --check` — + **passed**. +- `uv build --wheel --out-dir tmp\dist-dashboard` — **passed** and produced + `E:\Torq-CLI\tmp\dist-dashboard\torq_cli-0.2.0-py3-none-any.whl` + (274,206 bytes). + +G1D independently checked the source UI at desktop, 320 px, +200% CSS zoom, dark theme, storage failure, authentication failure, and workspace +identity changes. A separate desktop/mobile smoke check of the installed wheel returned authenticated workspace metadata, +restored the tab draft, kept Send disabled for a missing root, and included the +final responsive assets. The detailed observations and screenshot paths are in +`docs/plans/2026-09-16-dashboard-browser-verification.md`. G2A independently +approved the frozen implementation after 31 checks. + +## Deliberate limits + +- Workspace discusses an existing verified run. It cannot start a task, edit + files, run commands, present a governed diff, or accept/apply changes. +- Live dispatch still forbids tools and files, and the governed change + transaction remains design-only. P2 and P3 are not delivered. +- Provider authentication is not probed by metadata. No paid provider was called, + no credential was changed, and no live run was started. +- Draft persistence is limited to the current browser tab. Attachment binaries + are not persisted with drafts. +- A collection root requires the user to relaunch against one selected run; the + server does not silently switch roots. +- Nothing was pushed, merged, deployed, or committed by the builder. diff --git a/docs/plans/2026-09-16-dashboard-g1d-build-contract.md b/docs/plans/2026-09-16-dashboard-g1d-build-contract.md new file mode 100644 index 0000000..e221e95 --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-g1d-build-contract.md @@ -0,0 +1,41 @@ +# G1D handoff: PR 80 dashboard implementation + +Baseline: PR #80 head `a6716dcf2c585ac3a2e19d4317a56af6ba3ba741`; main `65135ec6aa78e5f0022b0dc439b0e867dc4f399e`. PR contains documentation only. Implementation branch: `feat/dashboard-workspace-pr80`. + +Roles explicitly requested by the operator: current assistant G1D; GPT-5.6 Sol G1R; GPT Daybreak Blue latest Builder; GPT-5.6 Terra G2A. Gate receipts are local review artifacts, not TORQ production run certificates. No merge, push, release, provider credential changes, or live paid execution is implied by this handoff. + +## Review findings to resolve + +1. P2 has a missing execution dependency. `LiveStageDispatcher` also forbids tools/file access, and the closed builder schema only accepts a short proposal string. `docs/design/governed-change-transaction.md` explicitly documents the unimplemented application transaction. Existing run creation is not a file-editing engine. P2 needs a separately reviewed execution/workspace/transaction implementation; no new UI may claim it exists. +2. The Working wireframe promises queued follow-up delivery without a queue contract. In this increment follow-ups remain unsent drafts, with explicit manual Send once ready. No silent submission on turn completion. +3. Provider `--no-session-persistence` does not mean TORQ cannot continue discussion: `chat_runtime.py` reconstructs a prompt from signed history. Distinguish discussion continuation from build continuation. +4. Fleet already supports open-action browser notifications. Reuse them; distinguish completion notifications from existing needs-attention alerts. +5. Draft persistence cannot be claimed while using memory-only storage. In this increment use explicitly labelled browser-session drafts, scoped to run/root identity, with Clear draft, quota/storage failure handling, and no automatic evidence insertion. Do not store auth tokens, keys, attachments, or filesystem paths in browser storage. +6. Correct the earlier claim that demo dry runs cannot be verified/certified. An isolated `execute_demo` experiment returned `mode=dry_run`, receipt verification `verified`, and an existing run certificate. Mode, trust, writable-session eligibility, and execution capability are separate axes. A sample-view policy must not be presented as a cryptographic impossibility. The sandbox initially refused multiprocessing pipe creation; the approved no-provider retry succeeded. + +## Executable increment + +Deliver the friendly entry/workspace and truthful capability foundation (bounded P0/P1), plus a documented lifecycle assessment. Full P2/P3 remain tracked requirements, not delivered by this increment. + +- Keep the legacy Fleet view as the initial default. Add an obvious Workspace/Fleet switch; only new Workspace localStorage state is the view preference (retain existing Fleet theme and notification-deduplication keys). Workspace is a polished responsive conversation-first view using existing bundled vanilla HTML/CSS/JS. Keep the original useful Fleet controls and evidence details reachable. No framework migration. +- Add authenticated, read-only workspace metadata (e.g. `GET /api/v1/workspace`) giving root kind (individual run, collection, empty/missing, unavailable), safe run identities, selected identity, actual discussion capabilities, and structured reason/remediation. No raw absolute paths, secrets, receipt bodies, or untrusted HTML in metadata. `can_start_task=false`, execution unsupported, and no decorative Build/Accept buttons pretending otherwise. +- A collection must show a clear choose-run state and safe identifiers. For this slice, give a concrete supported launch instruction with a relative run ID if runtime rebinding is not implemented. Do not switch mutable controllers by changing a projector path; preserve the existing per-run ownership/session invariant. CLI should explicitly diagnose collection roots when chat is requested, rather than mint keys for a parent collection. No arbitrary automatic newest-run selection. +- Root classification and receipt/certificate trust preflight must occur before `FileRunKeyStore.get_or_create_run_keys` or any chat identity/journal creation. Collection, missing, symlink/reparse, and untrusted roots with chat requested must fail or disable chat without key-store mutation. Metadata reads must not create keys or journals. +- Handle empty/missing/demo/untrusted/runtime-disabled/disconnected states with plain-language messages and an actionable Details/setup guidance panel. Do not classify a run as Sample by folder naming alone: use trustworthy run mode or label unknown. Do not classify every nonempty directory as a collection; bounded discovery of immediate `run-*` directories, reject symlink/reparse targets, no recursion. +- Derive attachment support from actual configured provider on the server. Claude: zero attachments; generic/no metadata defaults closed. Other supported adapters retain their existing limits. UI help, accept types, and disabled state match. Server remains authoritative on submission. +- Keep textarea editable while unavailable/working. Submission checks runtime readiness and active turn in handler, not merely disabled button. Draft text entered during an active turn must survive snapshots/completion. Do not queue or auto-send. Support Ctrl/Cmd+Enter; no accidental Enter submit. +- Drafts: browser-session storage, run/root-scoped using an opaque server identifier. Keep local unsent content separate from accepted chat content. Clear only the exact submitted revision after confirmed acceptance, preserving edits typed during request flight. Storage failure must state that the draft is only held in this tab. Preserve draft on error/expired session/reconnect. Empty-root draft cannot silently become a different run's instructions. +- The opaque `workspace_id` must remain stable for the same classified root across reload/reconnect within the browser session and differ across roots. Do not expose the raw path in it. Tests must demonstrate this stability and separation, not simply a random ID per request. +- Workspace should show the task/run title if verified; otherwise a neutral welcome. Suggestion chips insert editable prompts. Progress/usage/status comes from existing evidence; do not invent step counts, file diffs, cost, checks, or success. Raw finding remains available under Details. +- Safe visual hierarchy: project/task header, central conversation or empty state, nearby composer, concise next-action card, collapsible run details. Friendly sentence-case copy, restrained color, responsive at 320px, 200% zoom, visible keyboard focus, reduced motion, polite announcements. Keep legacy mode available. +- Add clear setup/help and README instructions explaining how to launch an individual run and what discussion can/cannot do. The existing untracked personal launcher is not a distributable product artifact: do not overwrite it. If a supported launcher is needed, add it under scripts with no hardcoded machine paths/model and never kill an unrelated port owner. + +## Boundaries and tests + +Keep certificate verification, exact-origin/session protections, signed transcript semantics, process cancellation semantics, and existing provider tool restrictions unchanged. No secrets or credentials in the browser. No server-controlled innerHTML. New endpoint uses existing authenticated-session checks and no-store headers. + +Test root classification (empty, missing, valid individual, collection, symlink, untrusted), metadata auth/redaction/capabilities, no mutation on metadata reads, submit gate, drafts during in-flight acceptance and active turn, draft scoping/storage failure, preference switching, unsupported attachments, and reconnect. Retain chat/Fleet existing tests, adjusting brittle source-string assertions only when behavior is preserved and replacement checks exist. + +Run targeted tests, ruff, mypy, packaging if assets change, then affected complete chat/Fleet regression. Verify a real locally served browser flow (fixture evidence allowed and labelled; no provider call), both views, blocked state, draft/edit/persistence, 320px layout and keyboard operation. Capture screenshots and findings. Browser fixtures prove UI behavior only. + +G1R must approve this bounded contract before Builder edits implementation. Builder supplies changed files, commands/results, screenshots, limitations. G2A independently reviews final diff and reruns relevant checks. Any gate rejection returns to Builder for corrections; do not equate a partial UI slice with completed build-tool parity. diff --git a/docs/plans/2026-09-16-dashboard-g1r-review.md b/docs/plans/2026-09-16-dashboard-g1r-review.md new file mode 100644 index 0000000..b269c65 --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-g1r-review.md @@ -0,0 +1,25 @@ +# PR 80 G1R review + +Reviewed PR #80 at exact head `a6716dcf2c585ac3a2e19d4317a56af6ba3ba741` against the repository implementation and the amended G1D build contract. This is a source and contract review. Reported CI and local fixture checks are baseline evidence only; no live provider, credential, paid request, file-editing agent, or governed change application was validated by this review. + +## Judgment + +- **Full goal-to-governed-build plan: REVISE.** The product direction is sound, but P2/P3 are not builder-ready as an implementation promise. The current live runtime is a tool-disabled decision pipeline and the governed change transaction remains design-only. +- **Amended bounded P0/P1 contract: APPROVE.** Builder handoff is ready for the friendly workspace, truthful capability metadata, root diagnostics, provider-driven attachment controls, session-scoped drafts, legacy Fleet preservation, and the specified UI/test work in `2026-09-16-dashboard-g1d-build-contract.md`. +- **Builder handoff scope:** `READY_FOR_BOUNDED_P0_P1`. It does not include task creation, file edits, command execution, diff/check review, acceptance/application, or build-tool parity. + +## Numbered findings + +1. **Blocking contradiction resolved by scope, not by existing runtime.** The main plan says P2 will edit files and run commands through existing governed services (`2026-09-16-dashboard-ux-plan.md:5-16,243-257`). `RunController.start` only invokes the governed orchestrator (`application/run_command.py:70-155`); its live dispatcher explicitly says not to use tools, access files, or execute commands and invokes Claude with `--tools ""` and plan mode (`adapters/live_provider.py:253-303`). The live runtime also creates an isolated temporary working directory outside the target roots (`application/live_runtime.py:49-63,164-175`). The builder response contract is only a closed `status` plus a proposal string of at most 120 characters (`domain/stage_response.py:7-26,39-58`). Therefore existing run creation cannot meet the P2 exit gate. + +2. **Governed application and review artifacts are missing executable contracts.** The authoritative transaction design says it is design-only and describes today's approval-without-application gap (`docs/design/governed-change-transaction.md:1-23,43-60`). The main plan's run-start snapshot, run-bound diff, check command/exit evidence, accepted revision, and governed application semantics (`2026-09-16-dashboard-ux-plan.md:227-258`) require a separately reviewed implementation before P2/P3 can ship. The bounded contract correctly keeps `can_start_task=false`, exposes execution as unsupported, and forbids decorative Build/Accept controls (`2026-09-16-dashboard-g1d-build-contract.md:18-23`). + +3. **The bounded server contract now preserves the per-run trust boundary.** The existing HTTP server owns one projector and rejects controller roots that differ from that projector (`interfaces/fleet_http.py:301-338`); it currently exposes only Fleet/chat reads and Fleet/chat/context/action/recovery mutations (`interfaces/fleet_http.py:445-494,625-669`). The approved increment adds authenticated read-only workspace metadata without mutable projector rebinding, requires bounded immediate-child discovery for collections, and preflights root classification plus receipt/certificate trust before any key-store or chat-journal mutation (`2026-09-16-dashboard-g1d-build-contract.md:20-24,33-39`). This is the correct pragmatic boundary for a useful dashboard slice. + +4. **Draft and continuation semantics are now executable and honest.** The child Claude process disables provider session persistence (`adapters/chat_provider.py:48-75`), while TORQ reconstructs bounded continuation from verified submitted/completed chat evidence (`application/chat_runtime.py:618-635`). The approved contract therefore treats this as discussion continuation only, keeps active/unavailable composers editable, forbids queued or automatic sends, clears only the exact revision durably accepted, and scopes browser-session drafts to a stable opaque workspace identity that changes across roots (`2026-09-16-dashboard-g1d-build-contract.md:10-13,25-28`). These rules close the earlier wireframe's unsupported follow-up-delivery promise. + +5. **Existing UI behavior is retained rather than re-labelled as new capability.** Fleet already persists theme and notification-deduplication state and emits browser notifications for newly open operator actions (`data/fleet/fleet.js:8-9,287-305,772-780`). The amended contract preserves those keys, keeps Fleet as the default until opt-in, and distinguishes existing needs-attention alerts from any future completion notification (`2026-09-16-dashboard-g1d-build-contract.md:12,20`). It also correctly treats dry-run mode, verified evidence, writable-session eligibility, and execution capability as separate axes (`2026-09-16-dashboard-g1d-build-contract.md:14`). + +## Required validation at Builder/G2A + +The Builder must provide changed files, commands/results, and labelled browser screenshots. G2A must independently verify root classification and no-mutation reads; preflight-before-key-mint behavior; capability redaction and authentication; provider attachment truth; exact-revision draft clearing; stable/separate workspace identities; Fleet-default preference behavior; reconnect and active-turn drafting; 320px, 200% zoom, focus, and keyboard behavior; packaged assets; and the affected complete chat/Fleet regression suite. A fixture browser flow proves UI behavior only. Do not report live provider or end-to-end build capability without a separately authorized live validation and the missing P2 execution transaction. diff --git a/docs/plans/2026-09-16-dashboard-g2a-review.md b/docs/plans/2026-09-16-dashboard-g2a-review.md new file mode 100644 index 0000000..d2cb8f7 --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-g2a-review.md @@ -0,0 +1,29 @@ +# PR 80 G2A gate receipt + +Reviewed the frozen implementation against baseline `a6716dcf2c585ac3a2e19d4317a56af6ba3ba741` and the approved bounded P0/P1 contract in `2026-09-16-dashboard-g1d-build-contract.md`. + +## Judgment + +**APPROVE — bounded P0/P1 only.** This receipt approves the friendly Workspace entry, authenticated read-only metadata, root/trust diagnostics, truthful discussion capability controls, session-scoped drafts, and retained Fleet view. It does not approve P2/P3 task creation, file editing, command execution, diff/check review, acceptance/application, or build-tool parity. + +## Trust and capability review + +- `application/workspace.py` classifies roots without creating keys, journals, or directories. It gives an opaque stable root identifier, rejects symlink/reparse roots and ancestors, bounds collection discovery to immediate `run-*` children, and does not select a collection member automatically. +- The `fleet --serve --chat-provider` CLI path performs root classification and verified snapshot trust checks before `FileRunKeyStore`, `ChatEvidenceJournal`, or provider construction. The new Windows-focused regression covers missing, collection, linked, and untrusted roots. +- `GET /api/v1/workspace` remains session-authenticated and no-store. It exposes the opaque workspace identity, safe run IDs, root/trust state, provider-derived attachment limits, and explicit non-execution capability flags without emitting the configured path, secrets, or receipt bodies. +- Direct chat submission now rechecks a fresh root shape and verified snapshot before dispatch, downgrades a closed or abandoned session, and refuses unavailable runtime or active-turn submissions. Cancellation ownership remains unchanged. The regression tests cover POST-before-GET closed, tampered, unavailable, and active states. +- The UI source stores drafts only in `sessionStorage` under the opaque workspace identity; it preserves in-flight edits, keeps the composer editable when discussion is unavailable, and retains Fleet as the default view. The requested execution capability stays false. + +## Independent validation + +```text +git diff --check a6716dcf2c585ac3a2e19d4317a56af6ba3ba741 +python -m pytest -q tests/test_workspace.py tests/test_chat_http.py tests/test_chat_cli.py tests/test_fleet_ui.py tests/test_chat_ui_runtime.py -p no:cacheprovider --basetemp E:\tmp\torq-g2a-final-targeted +31 passed +``` + +The Builder also reported clean focused 32/32, workspace/chat/fleet regression selection, Ruff, mypy over 82 source files, and wheel build. Browser fixture checks and screenshots are recorded separately in `2026-09-16-dashboard-browser-verification.md`. + +## Limits + +No live provider, credential, paid request, or execution engine was validated. This is a local review gate receipt, not a production run certificate. diff --git a/docs/plans/2026-09-16-dashboard-p2-builder-handoff.md b/docs/plans/2026-09-16-dashboard-p2-builder-handoff.md new file mode 100644 index 0000000..01e4b7d --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-p2-builder-handoff.md @@ -0,0 +1,77 @@ +# Dashboard P2 builder handoff + +Date: 2026-09-16 +Builder: GPT Daybreak Blue latest +Contract: `2026-09-16-dashboard-p2-contract.md` +Gate: Sol G1R `APPROVE — READY_FOR_P2_BUILDER` + +## Delivered scope + +P2 now provides a real bounded goal-to-candidate path. A configured Fleet launch can open **New task**, persist a project-scoped goal and file scope, review an immutable plan, submit one idempotent task, watch or stop it, and inspect a verified candidate result. The provider returns a closed JSON file-content envelope. TORQ validates and materializes those contents in a separate candidate root and launches only the packaged `structural-v1` helper through `OwnedProcess`. + +The source project remains unchanged. `candidate_ready` is released only from a verified and sealed task receipt chain after artifact decryption and independent identity checks. P2 does not expose an Apply or Accept action and does not claim unit tests, arbitrary command execution, OS sandboxing, or P3 delivery. + +## Implementation + +- `application/candidate_tasks.py` owns plan review, replay-before-revalidation, durable reservation, dispatch, cancellation, restart recovery, evidence append/seal, and independent candidate projection. +- `application/task_store.py` provides owner-only bounded durable drafts, plans, request reservations, monotonic tombstones, and closed-schema reads and writes. +- `domain/task_evidence.py` and `domain/run_evidence.py` enforce the discriminated `torq-candidate-task-v1` event schema, task/run identity, provider/model continuity, legal lifecycle ordering, and exactly one terminal before seal. +- `safety/task_workspace.py` and `safety/state_lock.py` enforce explicit UTF-8 scope, protected-path denial, held-ancestor guarded reads, exact candidate inventory, disjoint roots, and a kernel-backed single owner. +- `adapters/candidate_provider.py` supports the configured native Claude executable and existing supported CLI bridges with tools disabled and a closed JSON output contract. Binary and helper identities are pinned in the reviewed plan and rechecked before dispatch. +- `checkers/structural.py` performs fixed Python syntax, strict JSON, and UTF-8 checks without executing candidate code. +- `safety/receipts.py` adds no-create key loading and verified artifact readback so projection cannot create keys or trust mutable task-cache state. +- `interfaces/fleet_http.py` exposes authenticated, same-origin, closed-schema task routes. Mutation rotation is serialized in the browser. Exact start replay can recover one ambiguous rotated response without granting the old session general access or permitting a new dispatch. +- `interfaces/cli.py` accepts explicit project allowlists and derives safe state/work roots outside the source project when task roots are omitted. Ordinary Fleet still requires its run root. Native wrapper scripts are rejected. +- `data/fleet/index.html`, `task.css`, and `task.js` add the task workspace, durable scoped drafts, immediate plan invalidation, serialized mutations, stable request identity, active-task resume, Stop, and selectable history. The form stays disabled until its authoritative draft revision is loaded. + +The main dashboard plan now records P2 as a separately reviewed candidate-only implementation. README documents the launch shape, 32-file/64-KiB-per-file limits, structural checks, and the P3 boundary. + +## Repository tests added or extended + +- `tests/test_task_evidence.py` +- `tests/test_candidate_tasks.py` +- `tests/test_candidate_task_integration.py` +- `tests/test_task_http.py` +- `tests/test_task_cli.py` +- `tests/test_task_ui_runtime.py` +- `tests/js/task_runtime.test.cjs` +- `tests/js/task_resume.test.cjs` +- `tests/fixtures/candidate_provider.py` +- `tests/test_fleet_ui.py` +- `tests/test_hermetic.py` +- affected chat HTTP/CLI regressions + +The tests cover closed task evidence, no-create projection, unsealed/tampered downgrades, exact candidate inventory, empty-project creation, source immutability, accepted replay across draft changes and restarts, durable unknown termination, cancellation versus late completion, store ABA/reserved-key injection, provider output validation, HTTP authentication/origin/schema/recovery, CLI default task roots, and browser mutation/edit/request identity primitives. + +## Checks run by the builder + +- Focused P0/P1/P2 regression command: `python -m pytest -q -p no:cacheprovider tests/test_chat_http.py tests/test_task_http.py tests/test_task_ui_runtime.py tests/test_candidate_task_integration.py tests/test_task_evidence.py tests/test_candidate_tasks.py tests/test_task_cli.py tests/test_fleet_ui.py tests/test_hermetic.py` — **83 passed**. +- Final UI subset after the initialization gate: `python -m pytest -q -p no:cacheprovider tests/test_fleet_ui.py tests/test_task_ui_runtime.py` — **10 passed**. +- Terminal capability regression after installed-wheel review: `python -m pytest -q -p no:cacheprovider tests/test_task_ui_runtime.py` — **2 passed**; its DOM harness proves a resumed task reaching `candidate_ready` refreshes capabilities and permits review/start of the next task. +- `python -m ruff check src tests` — passed. +- `python -m mypy --cache-dir tmp/mypy-p2-final src` — passed, 90 source files. +- `node --check src/torq_cli/data/fleet/task.js` — passed. +- `node tests/js/task_runtime.test.cjs src/torq_cli/data/fleet/task.js` — passed. +- Independent slow-response DOM harness — passed: fields remained disabled through delayed capability/draft reads and the first autosave used the loaded revision. +- `git diff --check` — passed. +- `python -m build --wheel --outdir tmp/p2-final-dist` — passed. + +The restricted test run first encountered the known Windows temporary-directory ACL denial. The identical focused commands passed with normal temporary-directory access; no test was skipped or represented as a product failure. + +## Independent evidence available at handoff + +G1D's real fixture run used the production coordinator, real `OwnedProcess`, a separate provider fixture process, the packaged structural checker process, EvidenceBroker, and receipt verification. It produced a verified candidate, left the original source unchanged, used exactly two process launches, returned the same accepted task on replay and restart without redispatch, and rejected candidate-byte tampering and extra inventory. A separate empty-project run created a candidate file while leaving the original empty. These results are recorded in `2026-09-16-dashboard-p2-g1d-verification.md` and the referenced local reports. + +Authenticated source-browser checks covered the happy path, delayed plan response, durable reload/history, mobile width, auth/origin denials, and source immutability. Installed-wheel browser and final full-suite validation are owned by G1D after this freeze. + +No live Claude or paid provider request was made. Local provider work was limited to executable discovery and help/version preflight supplied by G1D. + +## Build artifact + +`E:\Torq-CLI\tmp\p2-final-dist\torq_cli-0.2.0-py3-none-any.whl` + +The wheel build log confirms inclusion of the task coordinator, evidence/store/workspace/provider modules, packaged structural checker, and `task.css`/`task.js`/`index.html` assets. + +## Remaining boundary + +P2 ends at a sealed candidate. The dashboard does not show a full source diff, run arbitrary project tests, refine a candidate conversationally, or apply it to the source tree. P3 requires its own reviewed transaction and must bind any later review/application to this immutable candidate result. diff --git a/docs/plans/2026-09-16-dashboard-p2-contract.md b/docs/plans/2026-09-16-dashboard-p2-contract.md new file mode 100644 index 0000000..87295ca --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-p2-contract.md @@ -0,0 +1,87 @@ +# P2: bounded goal-to-candidate execution + +Status: Sol G1R APPROVE / READY_FOR_P2_BUILDER; implementation underway. See `2026-09-16-dashboard-p2-g1r-review.md`. Builds on the uncommitted approved P0/P1 increment. This is implementation work, not another cosmetic milestone. + +```mermaid +flowchart LR + Project[Configured project] --> Draft[Durable goal and scope] + Draft --> Plan[Review exact execution plan] + Plan --> Start[Idempotent authorized start] + Start --> Snapshot[Separate bounded project snapshot] + Snapshot --> Provider[Owned provider returns file contents] + Provider --> Validate[Validate and write candidate] + Validate --> Check[Owned trusted check command] + Check --> Evidence[Seal signed result and artifacts] + Evidence --> Result[Candidate ready or explicit failure] +``` + +## Outcome and boundary + +A configured installation can select an approved project in the dashboard, save a goal, review its exact scope/policy, start once, and obtain actual generated or edited files plus a real check command result without manually creating a run or certificate. P2 finishes at a verified candidate in a separate workspace. It never represents this as application to the original project. P3 owns diff/refinement/accept/application UX and the separate governed primary-tree transaction; no primary writes or approval-to-completed shortcut is added here. + +Initial bounded execution uses structured file generation: the provider produces contents, while TORQ controls filesystem writes and check commands. It does not need an unrestricted agent shell. The UI names the supported check precisely (syntax/format validation is not unit testing). Broader execution policies must not be advertised as implemented. + +## Control and data contract + +1. Add an explicit task-capable launch configuration with server-approved project directories and a separate state root. Default state may be automatic outside the project. Project selection uses opaque IDs; HTTP never accepts arbitrary absolute directories or executable paths. Existing Fleet launch remains compatible. Opening the page never calls a provider. +2. Preserve discussion separately from New task. Task capabilities report provider configuration, supported execution policy, project eligibility, and active-task ownership independently of an existing Fleet run certificate. This is a new authorized task-creation path, not a bypass of the existing chat trust gate. +3. Persist drafts server-side with revision CAS, project binding, bounded contents, explicit delete, and honest persistence text. Retain them across server restart. Do not insert unsent drafts into run receipts. Browser edits during requests must not be cleared by an older acknowledgement. +4. A reviewable plan binds goal/draft revision, project ID, input snapshot identity, allowed output paths/scope, provider/model, check policy, and limits. An immutable plan digest is required on Start. Source or policy changes invalidate that plan. Approval authorizes provider submission and generation only in the displayed scope. +5. Start commits a durable reservation before any provider dispatch. A request ID plus canonical request digest identifies retries; the same key/body returns the same task and a different body conflicts. Simultaneous starts and multiple server processes cannot dispatch twice. State root has a kernel-backed single-owner lock. Interrupted reservations are recovered conservatively without automatic redispatch. +6. Each task gets a server-generated run ID, broker-created certificate/receipt store, isolated workspace and artifact directory. Reuse the broker/key/receipt authority path. Signed task-specific evidence must bind the accepted plan, base manifest, provider result identity, candidate manifest and exact check result. Result projection must validate semantic task state as well as cryptographic verification; generic signed audit prose is not alone a completion proof. No false v3 primary application claim. +7. Provider execution uses the existing credential boundary and OwnedProcess. Use a separate immutable runtime directory outside both source and evidence. Return a closed bounded JSON schema containing actual relative paths and UTF-8 file contents; reject duplicate keys/paths, invalid schema, path escape, protected paths, excessive output and unsupported operations. Provider output cannot choose executable argv or read arbitrary local files. Do not expose raw provider stderr or secrets to HTTP. +8. Snapshot selected ordinary files into a new owner-only candidate; reject links, reparse points, special files, traversal, Windows device/ADS paths and case aliases. Source, state, work and provider directories must not overlap. No keys, credentials, .git or protected source are copied or submitted. Bound file count, file size, total bytes and traversal work. The reviewed plan clearly states exclusions and supported scope. Recheck the source snapshot before dispatch and candidate identity before declaring ready. +9. Execute a fixed packaged check helper through OwnedProcess with no provider credentials and isolated Python imports. Initial policy may validate Python syntax and JSON/text format without importing/executing generated code. Record actual argv/command identity, exit code, output completeness and confirmed process-tree termination. Missing/failed checks cannot produce candidate_ready. Do not call process ownership an OS filesystem sandbox. +10. Progress uses durable states (reserved, preparing, generating, checking, candidate_ready, failed, interrupted, stop_requested/termination_unknown). Cancel and shutdown operate only on owned process trees. Unknown termination prevents successful cancellation and blocks another task until safe recovery. Reconnect/restart must not replay a provider call. Completed candidates remain addressable by task ID and pinned evidence/artifact identities; missing or changed evidence/artifacts downgrades the result. + +### Exact-content restriction (Terra design review) + +The initial policy accepts UTF-8 regular-file contents only. Scan source context before provider submission and candidate contents before writing, using the existing redaction registry, and require unchanged text; findings that alter text are a hard rejection, never a repair. Hash the exact UTF-8 bytes before artifact persistence. After broker `write_artifact`, decrypt/read back and require byte-for-byte equality. Signed task evidence binds raw content and encrypted artifact hashes. UI/plan states that secret-like output rejected by the scanner cannot be generated under this policy. No base64 workaround or misleading claim of a general binary artifact channel. Reject hardlinks and special filesystem nodes as well as links/reparse points; represent only regular-file changes and do not promise empty-directory changes. Recheck original source identity before candidate_ready as well as before dispatch. + +## Closed contracts required by G1R + +### Installation identity + +One state root is the installation authority for draft/task/request idempotency and the lifetime kernel lock. Deliberately different state roots are different installations and do not share idempotency. Derive separate sibling `state` and `work` directories under an automatic application-data parent (or accept explicit `--task-state-root` and `--task-work-root`), with the provider runtime in a third owner-only temporary root. Validate pairwise source/state/work/provider-runtime ancestor and case aliases before mutation. Evidence lives inside state; candidate work lives inside work. Do not interpret the state/evidence containment as prohibited: the disjointness applies to the named top-level trust boundaries. + +### Evidence lifecycle + +Use the existing receipt envelope/certificate/broker with `task_contract=torq-candidate-task-v1` and a closed inner `event`. The existing outer `audit` transition is reused as an observed coordinator event. Its discriminator selects a strict closed event schema and semantic state machine in BOTH append and independent verification paths, including task-ID consistency and exactly one terminal before seal. The semantic validator derives readiness; generic/non-discriminated audit receipts never count. Old cryptographic verification alone cannot project P2 readiness. Missing/unknown discriminator data cannot become P2 evidence by projection. + +The exact logical events are: `task_start_accepted` (request digest, immutable plan hash, scoped base manifest hash, canonical provider-input bundle hash); `candidate_generated` (accepted-plan identity, actual candidate manifest hash, encrypted candidate bundle reference and raw/cipher hashes); `candidate_check_completed` (generated sequence/hash, candidate hash, checker profile/version and executable helper hash, fixed argv identity, actual exit code, bounded output identity, output completeness and confirmed tree termination); `candidate_ready` (derived terminal linking all preceding evidence sequences/hashes and matching source recheck); and explicit failed/interrupted/cancelled terminals. At most one start, generated and check event per task in v1, in that order; ready requires all, check exit zero, unchanged source, complete output and confirmed termination. Failure can terminate an earlier phase; cancelled requires confirmed termination. Unknown termination is not cancelled and blocks new dispatch. Append and verification reject reorder, replay, duplicate terminal and post-terminal evidence. Seal once at a terminal. The result projector derives state from verified receipts and exact artifacts, never trusts the mutable task cache for readiness. + +`candidate_ready` seals an immutable P2 result. P3 will open a separate review/apply transaction bound to that result; P2 never calls the existing v2 approval resolver to obtain completed. + +Failure terminal names are exactly `task_failed`, `task_interrupted`, and `task_cancelled`. Their closed payload keys are `task_contract`, `event`, `task_id`, `phase`, `reason_code`, `caused_by_sequence`, `provider_dispatch`, and `termination`. `phase` is one of reserved/preparing/generating/checking; reason_code is a bounded machine code (no prose, paths or provider stderr); caused_by_sequence is null before a first event or the preceding sequence otherwise; provider_dispatch is a boolean; termination is one of not_started/confirmed_empty/unknown. Cancelled requires confirmed_empty, or not_started with provider_dispatch=false. Interrupted/unknown can never project cancelled or ready. Unknown ownership remains a blocking recovery condition even if an interrupted evidence terminal is sealed. + +### Provider input and output + +The initial file policy is at most 32 files, 65,536 bytes per file and 2,097,152 aggregate bytes. The smaller per-file bound permits reuse of the existing native, ancestor-handle-protected reader without weakening its legacy configuration defaults. Provider wire output is separately bounded to 1,048,576 bytes including JSON overhead; the workspace limit is not a promise that every maximum-size file can be generated in one response. + +The canonical input bundle contains the accepted plan and only explicitly scoped source paths, exact UTF-8 contents and hashes. Its canonical SHA-256 is in the accepted-start receipt. New output paths are explicitly allowed by the reviewed plan. No arbitrary project browsing or hidden source-context expansion. + +Provider wire output is a single duplicate-key-free object with exactly `contract`, `plan_hash`, `input_hash`, and `operations`. `contract` is `torq-candidate-output-v1`. Each wire operation has exactly `operation` (`create` or `replace`), `path`, `base_hash` (null only for create), and `content` (UTF-8 string). Input, plan and existing base hashes are supplied in the prompt for exact copying. The trusted host constructs a canonical result by adding `content_bytes` and `content_hash` from actual UTF-8 bytes, never asks the model to calculate them, and verifies all accepted plan/input/base identities. Signed evidence distinguishes host-derived hashes from provider assertions and pins the raw response identity. No delete, rename, binary or empty-directory operations in v1. Reject unknown keys, duplicate paths, non-NFC paths, case-fold aliases, unsupported extensions and stale base hashes. Operations cannot leave the exact approved output-path set. Generation must produce at least one actual changed file to report candidate_ready. + +Implement a task-specific CandidateProviderCommandFactory with at least one production provider adapter. Reuse credential/process primitives, not the proposal-only Chat/Live behavior. Capability is false unless provider/model/binary/credential availability, project/scope, owned-process platform and packaged checker preflight succeed. Authentication remains unknown until a real request succeeds; capability/preflight must not advertise authenticated status from local configuration alone. + +### Packaged checks + +Pin `check_profile_id=structural-v1`. Server constructs argv equivalent to `[trusted_python, -I, -S, packaged_helper, ...host_owned_manifest_reference]`; request/model never supplies argv or helper path. Pin the helper bytes' SHA-256 in the plan and check evidence and recheck before launch. Parse `.py` with syntax compilation/AST only (never execute/import), `.json` as strict JSON, and supported plain text as UTF-8. The plan names exactly which validators apply and that unit/integration tests are not run by this policy. Use clean environment without provider credentials, cwd=candidate, bounded timeout/output, and OwnedProcess confirmed empty termination. Any unvalidated file or missing check prevents ready. + +## Interface + +Add bundled task UI/JS with a project selector, durable goal editor, explicit scope/check explanation, Review plan, Start, progress, Stop, task history and a result summary with output file names and command/exit result. Keep Fleet default for its existing launch; a task launch can open the task workspace. Show provider setup problems without losing drafts. Preserve 320px layout and keyboard access. Never display Accept, arbitrary shell execution, all-tests-passed, applied, or build parity unless implemented and evidenced. + +## Delivery and tests + +Builder owns implementation after G1R approval. Root verifies package/browser. Terra performs independent G2A review. No framework migration, push, merge, deployment, credential changes or implicit paid smoke. + +Required integration oracle: exercise authenticated HTTP draft/plan/start using the production coordinator, a real OwnedProcess fixture provider returning actual file contents, the real checker subprocess and real broker. Verify files changed only in the candidate, original hashes unchanged, check exit observed, signed result resolves, and reload/restart returns the same task. Clearly label fixture generation rather than live vendor verification. Production provider command wiring is tested separately; a live vendor smoke can only be claimed if actually performed. + +Negative cases: invalid project/root links and overlap before mutation; protected/path/device/case/size attacks; stale plan/draft; duplicate starts and changed replay body; crash at acceptance/before dispatch/after output; cancellation during generation/check; process termination uncertainty; nonzero check/invalid provider output/output overflow; missing/tampered artifacts and certificates; session/origin/unknown fields/oversized body; no provider calls from GET; no secret-bearing check environment; browser revision races, disconnect and storage errors. + +Run affected complete chat/Fleet/task tests, meaningful real process integration on Windows, lint/type checks, package asset validation, and installed-wheel browser smoke. Expand to full repository tests because the change touches shared authority/transport paths. Report exact results and any untested live-vendor behavior. + +## Design stress test + +Verdict: RESHAPE the assumption that the existing proposal-only runner can build; add actual host-controlled candidate execution. The largest risk is a signed success record that does not prove the candidate bytes or check result. The acceptance oracle above must fail on substituted files, failed checks, interrupted dispatch and changed plan identity. Success means a generated, checked, evidence-bound candidate; original-project application is a separate claim and remains disabled. diff --git a/docs/plans/2026-09-16-dashboard-p2-g1d-verification.md b/docs/plans/2026-09-16-dashboard-p2-g1d-verification.md new file mode 100644 index 0000000..109f48f --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-p2-g1d-verification.md @@ -0,0 +1,42 @@ +# P2 independent G1D validation record + +Status: **PASS for the bounded P2 candidate-building scope**, verified 2026-09-16 America/Chicago (2026-09-17 UTC). Live-vendor authentication and P3 application are not included. + +## Baseline and local provider inspection + +- Captured source/assets/test hashes before P2 implementation in `tmp/p2-baseline-hashes.json` (160 files), preserving the approved but uncommitted P0/P1 increment. +- `python -m pytest tests -p no:cacheprovider`: 1012 passed, 13 skipped, 2 failed in 301.88s. Collection began before P2 files landed; this is baseline evidence, not a test of completed P2. Failures were the previous increment's undeclared `os` import boundary in `application/workspace.py` and stale release-note wording inconsistent with the existing local `v0.2.0` tag. +- Corrected `docs/releases/torq-cli-v0.2.0.md` to retain the historical candidate revision and distinguish the release tag from separate publication/attestation evidence. `python -m pytest tests/test_release_consistency.py -p no:cacheprovider`: 11 passed in 0.86s. Builder is correcting the explicit workspace import-boundary declaration. +- Read-only local Claude inspection: native `C:/Users/asdasd/.local/bin/claude.exe --version` returned `2.1.257 (Claude Code)`. `--help` confirmed tools-off, safe-mode, disabled session persistence/slash commands, plan permission mode and no-chrome flags. Help saved at `tmp/p2-claude-help.txt`. PATH resolves a batch wrapper, so a native executable is required for the new owned-process adapter. No auth command or provider request was invoked. + +## Independent integration observations + +- `tmp/p2-independent-run.py` uses the production task service, real Windows OwnedProcess, a clearly labelled local fixture provider, the real packaged structural checker, and real receipt authority. The corrected candidate changes subtraction to addition while the source hash remains unchanged. The service returns sealed verified candidate_ready with structural exit 0 and exactly two child launches. +- Latest existing-file report: `tmp/p2-independent-02037718/report.json`. Identical Start replay and replay after editing the draft return the original task, with no additional launch. Changing candidate bytes or adding an unrecorded file makes the result unready; restoring exact bytes/inventory restores readiness. Reconstructing the service preserves the verified result with zero redispatch. +- Empty-project report: `tmp/p2-independent-e7e5d0a5/report.json`. Zero source files and one allowed new output produced a verified generated file in the candidate; the original project remained empty. The same replay/tamper/inventory/restart checks passed. No pre-existing run or certificate was supplied. +- Early real browser/HTTP flow on port 8880 completed goal/scope -> Review plan -> Start building -> verified candidate, with a real fixture-provider and checker process. Saved goal and scope survived reload. Unauthenticated metadata returned 401, wrong-origin Start returned 403, and unknown request fields returned 409, with no extra process launch. Desktop and 320px layouts had no horizontal overflow. Initial console output contained only a missing favicon 404. +- Browser fault review exposed stale-plan enablement and loss of newer unsaved text; Builder is correcting these before the final browser gate. Early screenshots `tmp/p2-browser-first-desktop.png` and `tmp/p2-browser-first-mobile.png` are interim, not release evidence. + +## Subsequent integration checks + +- Production CLI startup succeeded with `fleet --serve --task-project calculator=... --task-provider claude --task-model sonnet --task-claude-bin ...`, without a run-root, state-root, or work-root argument. A child-shell `LOCALAPPDATA` override kept default state/work creation inside an isolated temporary directory. The bootstrap opened New task directly, with the heading "What would you like to build?" and provider authentication explicitly `not_checked`. No Start or vendor request was issued on that server. +- The updated source browser completed another actual fixture build, displayed `Candidate verified` and structural exit 0, and let history reopen that verified result. Saved goal and input/output scope survived reload. Editing after review disabled Start immediately. Delaying a plan request while editing left Start disabled and preserved the newer saved text. The 320px viewport had no horizontal overflow. +- A first-load interaction exposed a further initialization race: new text survived the response guard but the authoritative draft revision was initially skipped, causing a CAS conflict. A lost HTTP response also exposed the need for a narrow authenticated idempotent Start replay path when the rotated cookie is lost. These are being checked before the final gate. +- First broad P2 suite: **1040 passed, 13 skipped, 1 failed** in 106.53s. The failed chat-origin HTTP request was aborted by Windows. An isolated chat HTTP check during the next edit also caught a misplaced required `replay_only` argument. Neither result is represented as a passing final suite; the final rerun follows the HTTP corrections. + +## Final verification + +- Final full suite: `python -m pytest tests -p no:cacheprovider --basetemp E:/Torq-CLI/tmp/p2-final-pytest-3` — **1042 passed, 13 skipped in 103.89s**. The preceding full pass was 1041 passed/13 skipped; the final UI correction added a second-task regression. The final suite includes it. Windows owner-only fixture permissions required execution outside the restricted sandbox; no fixture permission checks were bypassed. +- `python -m ruff check src tests`: passed. `python -m mypy src`: passed, 90 source files. `git diff --check`: passed. Builder also passed Node syntax/runtime/DOM checks and the wheel build. +- Installed the final wheel into a fresh local target with `pip install --no-deps --no-index --target tmp/p2-wheel-install-final ...`. Launched the browser fixture with Python `-I`; the printed imported module was `tmp/p2-wheel-install-final/torq_cli/__init__.py`, not the source checkout. All packaged source/assets match the checkout bytes. +- Final wheel: `tmp/p2-final-dist/torq_cli-0.2.0-py3-none-any.whl`, SHA-256 `ef547cd476261eec58c5dc7b4a95db5edc4176edd0378035f08b541ae5afe10f`. +- Packaged browser initialization: delayed draft GETs by 1000ms, for both new and existing drafts. Fields remained disabled until the authoritative draft loaded; saved goal and exact scope survived reload. Deleting a draft survived reload, and recreating it saved revision 4 without an ABA conflict. +- Packaged lost-response test: allowed the server to accept Start, deliberately restored the old cookie and aborted delivery, then used Start again. The two request bodies were identical. Replay recovered the accepted task, with **one provider plus one checker launch**, and the source file stayed unchanged. Reload resumed `GENERATING`, followed by verified `candidate_ready` and structural exit 0. +- That test exposed stale capabilities after a resumed task ended. Builder fixed terminal capability refresh and added a durable DOM regression. On the rebuilt final wheel, the browser resumed an active task, reached a verified candidate, then reviewed and started a **second task without reloading**. Stop confirmed `CANCELLED`. Total launches were three: first provider/checker plus the cancelled second provider. `tmp/p2-wheel-browser-final/validation.json` records wheel parity, hash, launch count, and source immutability. +- History reopened the verified result. Final screenshots are `tmp/p2-wheel-desktop.png` and `tmp/p2-wheel-mobile.png`. Desktop 1440px and mobile 320px had no horizontal overflow. Dark theme, reduced-motion preference, focus outline, and 200% CSS zoom were checked; CSS zoom is not claimed as a native browser zoom audit. The deliberately aborted request produced an expected network error; it was not an application exception. +- The source task-only CLI launch required no run-root, certificate, or explicit state/work roots. Live authentication remained `not_checked` throughout that startup-only check. +- All root-owned fixture servers were stopped and the browser returned to `about:blank`. No commit, push, merge, deployment, or primary-project application was performed. Existing unrelated worktree artifacts were preserved. + +Independent design approval is recorded in `2026-09-16-dashboard-p2-g1r-review.md`; final audit approval is recorded separately in `2026-09-16-dashboard-p2-g2a-review.md`. Builder handoff: `2026-09-16-dashboard-p2-builder-handoff.md`. + +Fixture-generated files and local CLI help cannot establish live-vendor authentication or model behavior. Structural checks cannot establish unit-test correctness or primary-project application. Report those limitations separately from the implementation result. diff --git a/docs/plans/2026-09-16-dashboard-p2-g1r-review.md b/docs/plans/2026-09-16-dashboard-p2-g1r-review.md new file mode 100644 index 0000000..8da995e --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-p2-g1r-review.md @@ -0,0 +1,29 @@ +# Dashboard P2 G1R review + +Reviewed `2026-09-16-dashboard-p2-contract.md` against PR #80 head `a6716dcf2c585ac3a2e19d4317a56af6ba3ba741` and the current workspace, process, provider, broker, receipt, and approval implementations. + +## Judgment + +**APPROVE — `READY_FOR_P2_BUILDER`.** The amended contract is implementable as a bounded goal-to-candidate service and addresses the current proposal-only runner rather than relabelling it. P2 completion means a sealed, evidence-bound candidate in an isolated workspace with a successful `structural-v1` check. It does not mean the original project was modified, tests passed, or a change was accepted or applied. + +No live provider, credential, paid request, generated candidate, or primary-tree application was exercised by this review. Those remain implementation and validation evidence for Builder/G2A. + +## Findings + +1. **The execution mechanism is real and bounded.** Current live dispatch forbids tools, file access, and commands and runs Claude with empty tools in plan mode (`adapters/live_provider.py:253-303`); its builder schema is only a status and a 120-character proposal (`domain/stage_response.py:7-26,39-58`). The P2 contract instead defines a task-specific provider adapter that receives a canonical scoped source bundle and returns actual `create`/`replace` UTF-8 contents under `torq-candidate-output-v1` (`dashboard-p2-contract.md:55-63`). TORQ validates identities and writes the candidate; the provider never selects paths outside the reviewed plan or supplies executable commands. + +2. **Isolation does not rely on the existing copy sandbox unchanged.** `WorkspaceManager.create` currently copies the complete primary with links preserved and uses an existence lock (`safety/workspace.py:93-116`), which is insufficient for provider-bound source handling and crash-safe cross-process ownership. The approved contract requires disjoint source/state/work/runtime roots, owner-only bounded snapshots of explicitly scoped ordinary files, link/reparse/hardlink/device/ADS/case/protected-path rejection, finite traversal/byte limits, and source identity checks before dispatch and readiness (`dashboard-p2-contract.md:26-35,37-45`). Process ownership is correctly not described as an OS filesystem sandbox. + +3. **Start persistence and replay have executable invariants.** Draft revisions use server-side CAS; a reviewed plan binds goal revision, project, source identity, exact path scope, provider/model, checker, and limits; Start is keyed by a canonical request digest and durable reservation created before dispatch (`dashboard-p2-contract.md:26-31`). One installation state root owns idempotency and a kernel-held lifetime lock. Same-key/same-body replay returns the existing task, changed-body replay conflicts, and restart recovery never silently re-dispatches a provider. + +4. **Candidate readiness is a semantic evidence verdict.** The service reuses the existing broker/certificate/receipt envelope but discriminates `task_contract=torq-candidate-task-v1` inside an outer coordinator `audit` event. Strict closed payload checks run at append and independent verification, and a sequence validator enforces one task identity, ordered start/generated/check events, exactly one terminal, no post-terminal evidence, and terminal-before-seal (`dashboard-p2-contract.md:47-55`). Generic signed audit events cannot project readiness. `candidate_ready` must link the accepted plan, base/input identities, exact encrypted candidate bundle, raw and cipher hashes, checker identity/result, zero exit, complete output, confirmed process-tree termination, and unchanged source recheck. Projection derives from verified receipts and decrypted artifacts rather than the mutable task cache. + +5. **Exact candidate bytes survive the redaction boundary.** Existing `ReceiptChain.write_artifact` scans and may transform text before encrypting it (`safety/receipts.py:1485-1505`). The contract avoids a false exactness claim by requiring source and output scans to return unchanged text, hard-rejecting redaction findings, hashing raw UTF-8 bytes before persistence, and reading the encrypted artifact back to prove byte equality (`dashboard-p2-contract.md:37-39`). Binary, delete, rename, and empty-directory changes remain outside P2 v1. + +6. **Checks cannot become arbitrary model-controlled execution.** The only initial policy is `structural-v1`; the server constructs the fixed `trusted_python -I -S packaged_helper` argv, pins and rechecks helper bytes, strips provider credentials, and parses supported Python/JSON/text without importing or executing candidate code (`dashboard-p2-contract.md:63-65`). Candidate readiness requires an actual zero exit, bounded complete output, and confirmed empty process-tree termination. The UI must call this syntax/format validation, not unit tests or “all checks passed.” + +7. **P2 and P3 are cleanly separated.** `candidate_ready` seals an immutable P2 result. P3 must open a separate review/apply transaction bound to that result and may not use the current v2 approval resolver, whose approval path terminalizes as completed without applying a governed change (`application/orchestrator.py:1242-1300`; `docs/design/governed-change-transaction.md:18-23,43-60`). P2 exposes no Accept action and performs no source-project write. + +## Builder and G2A release gate + +Builder must satisfy the production-coordinator integration oracle with a real owned fixture-provider process, real packaged checker subprocess, and real broker: authenticated draft/plan/start, actual candidate file changes, unchanged source hashes, exact artifact readback, signed semantic readiness, idempotent replay, and restart recovery. Production provider command wiring must be tested separately. G2A must independently exercise the negative matrix in the contract, full affected and repository regressions, lint/type/package checks, and an installed-wheel browser flow. Fixture execution proves production plumbing but is not live-vendor validation; any live-provider claim requires an actually authorized and observed request. diff --git a/docs/plans/2026-09-16-dashboard-p2-g2a-review.md b/docs/plans/2026-09-16-dashboard-p2-g2a-review.md new file mode 100644 index 0000000..86cda9c --- /dev/null +++ b/docs/plans/2026-09-16-dashboard-p2-g2a-review.md @@ -0,0 +1,102 @@ +# Dashboard P2 G2A review + +## Verdict + +**APPROVE — bounded P2 goal-to-candidate scope.** + +The initial provisional verdict was held while the browser review found a +slow-load draft-revision race, a lost rotated-cookie Start retry, and stale +post-terminal task capability. The final implementation disables draft controls +until their authoritative revision loads, admits only an authenticated, +origin-checked replay of the same task Start request, and refreshes task +capabilities after a terminal result. The targeted regressions and final +installed-wheel/browser validation passed. + +The implementation creates a checked candidate only in its owner-controlled +work tree. Its readiness projection requires a verified, sealed task receipt +chain and exact artifact, source, checker, and candidate-inventory bindings. +It does not apply a candidate to the selected project or provide P3 review or +acceptance behavior. + +## Independent review evidence + +- Read the P2 contract and G1R receipt, then reviewed the task store, + coordinator, workspace snapshot/materialization, provider command contract, + structural checker, evidence state machine/projection, HTTP task seam, and + task browser runtime. +- Ran the final focused suite: + + ```text + PYTHONPATH=src python -m pytest -q tests/test_candidate_tasks.py \ + tests/test_candidate_task_integration.py tests/test_task_http.py \ + tests/test_task_evidence.py -p no:cacheprovider \ + --basetemp E:\tmp\torq-g2a-p2-final-focused-2 + 23 passed + ``` + + This includes a real Windows `OwnedProcess` fixture provider and the real + packaged checker, source-tree non-mutation, idempotent replay, signed-ready + projection, tampered candidate downgrade, unknown-termination blocking, and + the authenticated/origin-checked closed HTTP request contract. +- Ran the task browser-runtime contract: + + ```text + node tests/js/task_runtime.test.cjs src/torq_cli/data/fleet/task.js + task runtime contract checks passed + ``` + +- Used isolated temporary fixture harnesses for cases that were initially + missing from the repository tests: + - A Stop issued while the checker was held at a barrier, followed by a late + successful checker result, ended `cancelled` with `task_cancelled`; it did + not produce `candidate_ready`. + - An unconfirmed Stop ended `termination_unknown`; a new Start was blocked + both in the same service and after reconstructing the service on the same + state root. + - Flipping one byte of the encrypted candidate artifact changed a cached + ready task to `untrusted` with `artifact_hash_mismatch`. + +## Findings resolved during review + +The implementation now rejects task-store field injection, preserves draft +revision monotonicity through delete/recreate, fsyncs the durable reservation, +blocks unknown ownership before another reservation, and validates the provider +runtime as a fourth disjoint boundary. It rejects non-finite and duplicate-key +JSON, configured provider symlinks, unsafe candidate inventory, and a stale +queued Start after a draft edit. Candidate readiness is withheld unless the +manifest is sealed and fully verified; it decrypts and cross-checks accepted +input, raw provider output, candidate operations, checker output, helper hash, +candidate bytes, and current source identity. + +## Final gates + +- Final full repository suite reported by Root: **1042 passed, 13 skipped** in + 103.89 seconds. +- Final wheel/source asset parity SHA-256: + `ef547cd476261eec58c5dc7b4a95db5edc4176edd0378035f08b541ae5afe10f`. +- Root's rebuilt-wheel browser flow reloaded a generating task into a verified + candidate, reviewed and started a second task without a page reload, then + stopped it. It observed three owned launches total, no source change, + delete/reload/recreate draft revision 4, desktop/mobile no-overflow, + dark mode, 200% CSS zoom, focus, and reduced-motion checks. Owned servers + were stopped afterward. +- After the late browser findings, independently ran: + + ```text + node tests/js/task_resume.test.cjs src/torq_cli/data/fleet/task.js + node tests/js/task_runtime.test.cjs src/torq_cli/data/fleet/task.js + node E:\tmp\g2a-p2-task-slow-load.cjs + ``` + + All passed. The temporary slow-load DOM harness delays both capabilities and + an existing-draft read beyond the autosave threshold, verifies controls stay + disabled until revision 5 loads, and verifies the first subsequent autosave + uses revision 5. + +## Limits + +No live vendor request, credential validation, or paid smoke was performed. +`structural-v1` parses Python, strict JSON, and UTF-8 text; it does not execute +generated code or run unit/integration tests. The result is an isolated +candidate only. P3 primary-tree review, acceptance, and application remain out +of scope. diff --git a/docs/plans/2026-09-16-dashboard-ux-plan.md b/docs/plans/2026-09-16-dashboard-ux-plan.md index f9ebfb0..2ef837a 100644 --- a/docs/plans/2026-09-16-dashboard-ux-plan.md +++ b/docs/plans/2026-09-16-dashboard-ux-plan.md @@ -1,6 +1,16 @@ # TORQ task workspace: dashboard review and implementation plan -Status: proposed, not implemented. Reviewed 2026-09-16, revised the same day after a second research pass. Scope: TORQ CLI in E:/Torq-CLI. +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. + +Historical P0/P1 correction: that increment delivered only the opt-in Workspace, +truthful root/provider/session capability metadata, collection guidance, and +browser-session drafts. Existing live dispatch still cannot edit files or run commands, +so P2 was implemented through the separately reviewed bounded candidate service in +`2026-09-16-dashboard-p2-contract.md`. P2 creates and structurally checks an isolated, +evidence-bound candidate; it does not apply changes to the source project. Provider process persistence is disabled, but TORQ can +continue discussion by reconstructing a prompt from signed history. Fleet already +notifies for open operator actions. Verified dry-run evidence is valid evidence; +run mode, trust, session writability, and execution capability remain separate. Product goal, stated by the user on 2026-09-16: use TORQ CLI the way Google Antigravity, the Codex app, and Claude Code are used. Describe a task in ordinary language, get a plan, let the agent edit files and run commands, review the diff and checks, and iterate. The current dashboard cannot do this: its chat runs the provider with no tools and in plan mode, bound to an existing run. Everything below is in service of closing that gap without giving up the evidence guarantees those tools do not have. @@ -8,10 +18,10 @@ Product goal, stated by the user on 2026-09-16: use TORQ CLI the way Google Anti |---|---|---| | Open a folder and start typing | Requires an existing run directory and a certified receipt chain | P0 entry states, P2 project selection and start service | | Agent proposes a plan, user approves | Chat is plan-only with no execution path | P2 execution policy and accepted plan revision | -| Agent edits files and runs commands | Chat adapter passes an empty tools list | P2 governed run creation through existing services; never by unlocking the chat adapter | +| Agent edits files and runs commands | Chat and live dispatch forbid tools/files; application transaction is design-only | P2 depends on a separately reviewed execution/workspace/transaction implementation | | Review a diff and test results, then accept | Fleet shows evidence counts and lanes, not a diff | P3 Plan, Changes, and Checks views under the artifact integrity rules | -| Ask a follow-up and continue | No session persistence in the chat adapter | P1 drafts during work, P3 revision requests and task continuation | -| Get notified when it needs you | None | P1 notifications | +| Ask a follow-up and continue | Signed history reconstructs discussion context; build continuation is unavailable | P1 unsent drafts; P3 still needs revision/task continuation contracts | +| Get notified when it needs you | Fleet already alerts for newly open actions | Existing Fleet alerts; future completion alerts remain separate | P0 and P1 make the dashboard honest and usable. P2 is the phase that makes it a build tool. Do not call the goal met before P2's exit gate passes. diff --git a/docs/plans/2026-09-16-pr80-g1d-review.md b/docs/plans/2026-09-16-pr80-g1d-review.md new file mode 100644 index 0000000..2e064d3 --- /dev/null +++ b/docs/plans/2026-09-16-pr80-g1d-review.md @@ -0,0 +1,24 @@ +# PR 80 G1D review + +Reviewed exact head `a6716dcf2c585ac3a2e19d4317a56af6ba3ba741` against main `65135ec6aa78e5f0022b0dc439b0e867dc4f399e`. PR is two commits ahead, zero behind at fetch time, and changes one plan document. GitHub reported all listed checks successful. This is not proof of a working dashboard or execution engine. + +Verdict: revise before using the plan as a full build specification. The product direction is sound; the execution assumptions and several user-visible promises need correction. + +## Findings + +1. **High: P2 lacks a real file-editing execution path.** The plan proposes existing governed services as the implementation mechanism. `adapters/live_provider.py:266` forbids tools and filesystem access and line 298 disables tools. `domain/stage_response.py` only accepts a short builder proposal string. `docs/design/governed-change-transaction.md` explicitly remains design-only and documents approval without applying a change. Starting an existing live run cannot satisfy the proposed P2 exit gate. Add explicit dependencies for project isolation, editable workspace, actual command/check execution, pinned change artifacts, and governed application/acceptance semantics before claiming build parity. +2. **High: trust explanation conflates dry-run mode with invalid evidence.** `application/demo.py:execute_demo` uses the same `RunController.start` that creates the certificate and verifies receipts. An isolated no-provider experiment in this review returned dry_run / verified / certificate_exists=True. The prior statement that demo runs cannot be verified is incorrect. The launcher passes a collection parent to a single-run projector, which is an independent concrete defect. Session mutability and tool capability remain separate checks. +3. **Medium: queued follow-ups are promised without an implementation contract.** The working screen says the message sends when a step finishes. Define a durable queue with revision/cancellation/recovery semantics or keep text as an explicitly unsent draft requiring manual Send. The first increment adopts manual Send. +4. **Medium: continuation and notification baselines are inaccurate.** `chat_runtime.py:_provider_prompt` replays signed history despite the child provider's disabled persistence. `fleet.js:notifyActions` already provides notifications for open actions. Distinguish build continuation from conversation history and new completion alerts from existing action notifications. +5. **Medium: draft persistence statements conflict.** The plan says drafts never get lost and shows saved-local text while permitting memory-only drafting. Display persistence status from actual successful storage. Scope by an opaque root/run identity, preserve edits during submit, and document retention. + +## Disposition + +`2026-09-16-dashboard-g1d-build-contract.md` defines a bounded P0/P1 implementation for independent Sol G1R review. It preserves existing trust and mutation semantics, adds the friendly workspace, and reports the missing execution capability honestly. Full P2/P3 remain explicit follow-on requirements; this UI increment must not be labelled their completion. + +## Checks performed + +- Fetched main and the exact PR head; inspected both directions of history and the repository source. +- Six focused existing tests passed: chat provider, chat JS runtime wrapper, Fleet JS runtime wrapper. +- Isolated no-provider dry-run trust experiment passed after sandbox multiprocessing restrictions required an approved retry. +- No provider authentication, paid dispatch, primary-tree application, merge, or deployment performed. diff --git a/docs/releases/torq-cli-v0.2.0.md b/docs/releases/torq-cli-v0.2.0.md index 8eca00d..2730d89 100644 --- a/docs/releases/torq-cli-v0.2.0.md +++ b/docs/releases/torq-cli-v0.2.0.md @@ -2,9 +2,9 @@ Status: prepared from the protected-`main` release candidate commit `35f7990f904f4a648a659702f03168d6febc709a`. -Do not interpret this file as a tag, signature, GitHub release, or -published-artifact attestation. Those release actions remain to be performed -and recorded. +These notes describe that candidate. The `v0.2.0` tag identifies the release +revision; signatures, publication status, and artifact attestations are recorded +separately in the release evidence and are not established by these notes. ## Feature release diff --git a/src/torq_cli/adapters/candidate_provider.py b/src/torq_cli/adapters/candidate_provider.py new file mode 100644 index 0000000..a79c68e --- /dev/null +++ b/src/torq_cli/adapters/candidate_provider.py @@ -0,0 +1,209 @@ +"""Closed command and wire contracts for goal-to-candidate providers.""" + +from __future__ import annotations + +import json +import os +import stat +import sys +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path + +from torq_cli.connectors.credential_sources import ( + CredentialVault, + claude_compatible_environment, + safe_child_environment, +) +from torq_cli.safety.task_workspace import digest_bytes, validate_relative_path + +OUTPUT_CONTRACT = "torq-candidate-output-v1" +MAX_PROVIDER_OUTPUT = 1_048_576 + + +@dataclass(frozen=True, slots=True) +class CandidateProviderCommand: + argv: tuple[str, ...] + cwd: str + environment: Mapping[str, str] + input_data: bytes + provider: str + model: str + + +def _native_executable(path: Path) -> str: + original = path.absolute() + original_metadata = original.stat(follow_symlinks=False) + reparse = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)) + if original.is_symlink() or int(getattr(original_metadata, "st_file_attributes", 0)) & reparse: + raise ValueError("task_provider_binary_unsafe") + resolved = path.resolve(strict=True) + metadata = resolved.stat(follow_symlinks=False) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1 or resolved.is_symlink(): + raise ValueError("task_provider_binary_unsafe") + if os.name == "nt" and resolved.suffix.casefold() not in {".exe", ".com"}: + raise ValueError("task_provider_binary_not_native") + if os.name != "nt" and not os.access(resolved, os.X_OK): + raise ValueError("task_provider_binary_not_executable") + return str(resolved) + + +class CandidateProviderCommandFactory: + """Create immutable tools-off commands; provider output never selects argv.""" + + def __init__( + self, + *, + provider: str, + model: str, + runtime_root: Path, + base_environment: Mapping[str, str], + vault: CredentialVault | None = None, + claude_binary: Path | None = None, + ) -> None: + if not model or len(model) > 128 or "\x00" in model: + raise ValueError("task_model_invalid") + self.provider = provider.casefold() + self.model = model + self.runtime_root = runtime_root.resolve() + self.base_environment = dict(base_environment) + self.vault = vault + self.claude_binary = claude_binary + + def preflight(self) -> dict[str, object]: + if self.provider == "claude": + if self.claude_binary is None: + raise ValueError("task_claude_binary_required") + binary = _native_executable(self.claude_binary) + elif self.provider in {"deepseek", "kimi", "qwen", "zai"}: + bridge = Path(__file__).with_name("chat_bridge.py") + _native_executable(Path(sys.executable)) + if bridge.is_symlink() or not bridge.is_file(): + raise ValueError("task_provider_bridge_unsafe") + if self.vault is None: + raise ValueError("task_credential_source_required") + # Resolve the credential now without disclosing it. Authentication is + # still unknown until the provider accepts an actual request. + claude_compatible_environment(self.provider, self.vault, self.base_environment) + binary = str(Path(sys.executable).resolve()) + else: + raise ValueError("task_provider_unsupported") + return {"provider": self.provider, "model": self.model, "binary": binary, "authentication": "not_checked"} + + def __call__(self, prompt: str) -> CandidateProviderCommand: + if len(prompt.encode("utf-8")) > 3_000_000: + raise ValueError("task_provider_input_too_large") + if self.provider == "claude": + if self.claude_binary is None: + raise ValueError("task_claude_binary_required") + argv: tuple[str, ...] = ( + _native_executable(self.claude_binary), + "-p", + "--output-format", + "text", + "--model", + self.model, + "--tools", + "", + "--no-session-persistence", + "--permission-mode", + "plan", + "--disable-slash-commands", + "--safe-mode", + "--no-chrome", + ) + environment = safe_child_environment(self.base_environment) + input_data = prompt.encode("utf-8") + else: + if self.vault is None: + raise ValueError("task_credential_source_required") + bridge = Path(__file__).with_name("chat_bridge.py").resolve() + argv = (_native_executable(Path(sys.executable)), "-I", "-S", str(bridge)) + environment = claude_compatible_environment( + self.provider, self.vault, self.base_environment + ) + environment.update( + {"TORQ_CHAT_MODEL": self.model, "TORQ_CHAT_PROVIDER": self.provider, "PYTHONIOENCODING": "utf-8"} + ) + input_data = json.dumps( + {"text": prompt, "attachments": []}, sort_keys=True, separators=(",", ":") + ).encode("utf-8") + return CandidateProviderCommand(argv, str(self.runtime_root), environment, input_data, self.provider, self.model) + + +def _reject_pairs(pairs: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, value in pairs: + if key in result: + raise ValueError("task_provider_duplicate_key") + result[key] = value + return result + + +def _reject_constant(value: str) -> object: + del value + raise ValueError("task_provider_non_finite") + + +def parse_candidate_output( + raw: bytes, + *, + plan_hash: str, + input_hash: str, +) -> tuple[tuple[dict[str, object], ...], str]: + if not raw or len(raw) > MAX_PROVIDER_OUTPUT: + raise ValueError("task_provider_output_size_invalid") + try: + value = json.loads( + raw.decode("utf-8"), + object_pairs_hook=_reject_pairs, + parse_constant=_reject_constant, + ) + except (UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc: + raise ValueError("task_provider_output_invalid") from exc + if not isinstance(value, dict) or set(value) != {"contract", "plan_hash", "input_hash", "operations"}: + raise ValueError("task_provider_output_schema_invalid") + if value["contract"] != OUTPUT_CONTRACT or value["plan_hash"] != plan_hash or value["input_hash"] != input_hash: + raise ValueError("task_provider_output_binding_invalid") + operations = value["operations"] + if not isinstance(operations, list): + raise ValueError("task_provider_operations_invalid") + normalized: list[dict[str, object]] = [] + seen: set[str] = set() + for operation in operations: + if not isinstance(operation, dict) or set(operation) != {"operation", "path", "base_hash", "content"}: + raise ValueError("task_provider_operation_schema_invalid") + path_value = operation["path"] + if not isinstance(path_value, str): + raise ValueError("task_provider_path_invalid") + path = validate_relative_path(path_value) + if path.casefold() in seen: + raise ValueError("task_provider_path_duplicate") + seen.add(path.casefold()) + if operation["operation"] not in {"create", "replace"}: + raise ValueError("task_provider_operation_unsupported") + if operation["base_hash"] is not None and not ( + isinstance(operation["base_hash"], str) + and len(operation["base_hash"]) == 71 + and operation["base_hash"].startswith("sha256:") + ): + raise ValueError("task_provider_base_hash_invalid") + if not isinstance(operation["content"], str): + raise ValueError("task_provider_content_invalid") + normalized.append(dict(operation)) + return tuple(normalized), digest_bytes(raw) + + +def trusted_python_executable() -> str: + """Return the interpreter identity only at the audited adapter boundary.""" + return _native_executable(Path(sys.executable)) + + +__all__ = [ + "CandidateProviderCommand", + "CandidateProviderCommandFactory", + "MAX_PROVIDER_OUTPUT", + "OUTPUT_CONTRACT", + "parse_candidate_output", + "trusted_python_executable", +] diff --git a/src/torq_cli/application/candidate_tasks.py b/src/torq_cli/application/candidate_tasks.py new file mode 100644 index 0000000..195d4d5 --- /dev/null +++ b/src/torq_cli/application/candidate_tasks.py @@ -0,0 +1,760 @@ +"""Durable coordinator for bounded goal-to-candidate execution.""" + +from __future__ import annotations + +import json +import threading +import time +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Protocol, cast + +from torq_cli.adapters.candidate_provider import ( + CandidateProviderCommand, + CandidateProviderCommandFactory, + parse_candidate_output, + trusted_python_executable, +) +from torq_cli.adapters.process import ExitObservation, OwnedProcess +from torq_cli.application.task_store import TaskStore +from torq_cli.domain.task_evidence import TASK_CONTRACT +from torq_cli.safety.evidence_broker import EvidenceBroker +from torq_cli.safety.receipts import ( + FileRunKeyStore, + ReceiptChain, + read_verified_artifact, + restrict_owner_only_directory, + restrict_owner_only_file, + verify_receipt_store, +) +from torq_cli.safety.state_lock import InstallationStateLock +from torq_cli.safety.task_workspace import ( + SourceSnapshot, + canonical_json, + digest_bytes, + digest_json, + materialize_candidate, + snapshot_source, + snapshot_candidate_exact, + validate_disjoint_roots, + validate_relative_path, + verify_output_scope, +) + +CHECK_PROFILE_ID = "structural-v1" +CHECK_PROFILE_VERSION = "1.0.0" +PLAN_CONTRACT = "torq-candidate-plan-v1" +INPUT_CONTRACT = "torq-candidate-input-v1" + + +class ProcessOwner(Protocol): + pid: int + output_closed: bool + + def poll(self) -> int | None: ... + + def wait(self, *, timeout: float = 5.0) -> ExitObservation: ... + + def force_stop(self, *, timeout: float = 5.0) -> ExitObservation: ... + + def next_event(self, *, timeout: float) -> Any: ... + + def close(self) -> ExitObservation: ... + + +@dataclass(frozen=True, slots=True) +class TaskProject: + project_id: str + label: str + root: Path + + +def _helper_path() -> Path: + path = Path(__file__).parents[1] / "checkers" / "structural.py" + if not path.is_file() or path.is_symlink(): + raise ValueError("task_checker_missing") + return path.resolve() + + +def _hash_file(path: Path) -> str: + return digest_bytes(path.read_bytes()) + + +def _safe_reason(exc: BaseException) -> str: + if isinstance(exc, (InterruptedError, RuntimeError, ValueError)) and exc.args and isinstance(exc.args[0], str): + value = exc.args[0].split(":", 1)[0] + if value.startswith("task_") and value.replace("_", "").isalnum() and len(value) <= 64: + return value + return "task_execution_failed" + + +class CandidateTaskService: + """Single-owner task authority. GET methods never invoke a provider.""" + + def __init__( + self, + *, + projects: Sequence[TaskProject], + state_root: Path, + work_root: Path, + provider_factory: CandidateProviderCommandFactory | Callable[[str], CandidateProviderCommand], + provider: str, + model: str, + owner_factory: Callable[..., ProcessOwner] | None = None, + python_executable: Path | None = None, + acquire_lock: bool = True, + ) -> None: + if not projects or len(projects) > 32: + raise ValueError("task_projects_invalid") + ids = [project.project_id for project in projects] + if len(set(ids)) != len(ids) or any(not item or len(item) > 64 for item in ids): + raise ValueError("task_project_id_invalid") + roots = [project.root.absolute() for project in projects] + boundaries = [*roots, state_root.absolute(), work_root.absolute()] + if isinstance(provider_factory, CandidateProviderCommandFactory): + boundaries.append(provider_factory.runtime_root.absolute()) + validate_disjoint_roots(boundaries) + self.projects = {project.project_id: TaskProject(project.project_id, project.label, project.root.absolute()) for project in projects} + self.state_root = state_root.absolute() + self.work_root = work_root.absolute() + self._state_lock = InstallationStateLock(self.state_root) if acquire_lock else None + if not acquire_lock: + self.state_root.mkdir(parents=True, exist_ok=True) + restrict_owner_only_directory(self.state_root) + self.work_root.mkdir(parents=True, exist_ok=True) + restrict_owner_only_directory(self.work_root) + self.evidence_root = self.state_root / "evidence" + self.evidence_root.mkdir(parents=True, exist_ok=True) + restrict_owner_only_directory(self.evidence_root) + self.store = TaskStore(self.state_root) + self.provider_factory = provider_factory + self.provider = provider.casefold() + 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._lock = threading.RLock() + self._owner: ProcessOwner | None = None + self._active_task: str | None = None + self._cancel_requested: set[str] = set() + self._termination_unknown: set[str] = set() + self._worker: threading.Thread | None = None + self._recover_reservations() + + def close(self) -> None: + with self._lock: + active = self._active_task + if active is not None: + try: + self.stop(active) + except (OSError, RuntimeError, ValueError): + pass + if self._state_lock is not None: + self._state_lock.close() + + def _recover_reservations(self) -> None: + data = self.store.snapshot() + for task_id, task in data["tasks"].items(): + if task.get("state") in {"reserved", "preparing", "generating", "checking", "stop_requested"}: + phase = str(task.get("state")) + if phase == "stop_requested": + phase = "generating" if task.get("provider_dispatch") else "preparing" + provider_dispatched = bool(task.get("provider_dispatch")) + termination = "unknown" if provider_dispatched else "not_started" + final_state = "termination_unknown" if provider_dispatched else "interrupted" + try: + chain = ReceiptChain( + self.evidence_root, + task_id, + FileRunKeyStore(self.evidence_root), + profile_version="candidate-v1", + policy_version="candidate-v1", + ) + broker = EvidenceBroker(chain) + existing = chain.covered_receipts() + terminal_body = next( + ( + row["payload"] + for row in reversed(existing) + if isinstance(row.get("payload"), Mapping) + and row["payload"].get("event") + in {"candidate_ready", "task_failed", "task_interrupted", "task_cancelled"} + ), + None, + ) + if terminal_body is None: + self._append( + broker, + { + "task_contract": TASK_CONTRACT, + "event": "task_interrupted", + "task_id": task_id, + "phase": phase, + "reason_code": "task_coordinator_restarted", + "caused_by_sequence": chain.sequence or None, + "provider_dispatch": provider_dispatched, + "termination": termination, + }, + ) + broker.seal() + else: + verification = verify_receipt_store(self.evidence_root / task_id) + manifest = json.loads( + (self.evidence_root / task_id / "terminal-manifest.json").read_text( + encoding="utf-8" + ) + ) + if verification.status == "verified" and manifest.get("sealed") is True: + event = terminal_body.get("event") + final_state = { + "candidate_ready": "candidate_ready", + "task_failed": "failed", + "task_cancelled": "cancelled", + "task_interrupted": ( + "termination_unknown" + if terminal_body.get("termination") == "unknown" + else "interrupted" + ), + }[str(event)] + except (OSError, PermissionError, ValueError): + final_state = "interrupted" + self.store.update_task( + task_id, + state=final_state, + finding=(None if final_state == "candidate_ready" else "task_restart_interrupted"), + ) + + def capabilities(self) -> dict[str, Any]: + finding: str | None = None + try: + helper = _helper_path() + _hash_file(helper) + if isinstance(self.provider_factory, CandidateProviderCommandFactory): + self.provider_factory.preflight() + snapshot_source(next(iter(self.projects.values())).root, ()) + execution = True + except (OSError, ValueError): + execution = False + finding = "task_preflight_failed" + with self._lock: + active = self._active_task + blocked_unknown = any( + task.get("state") == "termination_unknown" + for task in self.store.snapshot()["tasks"].values() + if isinstance(task, dict) + ) + return { + "schema": "torq-task-capabilities-v1", + "execution_supported": execution, + "can_start_task": execution and active is None and not blocked_unknown, + "active_task_id": active, + "provider": {"name": self.provider, "model": self.model, "authentication": "not_checked"}, + "policy": { + "check_profile_id": CHECK_PROFILE_ID, + "description": "Python syntax, strict JSON, and UTF-8 text structure only; unit tests are not run.", + "applies_to_source": False, + }, + "projects": [{"id": item.project_id, "label": item.label} for item in self.projects.values()], + "finding": "task_termination_unknown" if blocked_unknown else finding, + } + + def draft(self, project_id: str) -> dict[str, Any] | None: + self._project(project_id) + value = self.store.snapshot()["drafts"].get(project_id) + if value is None: + return None + result = dict(value) + if result.get("goal") is None: + result["goal"] = "" + return result + + def save_draft( + self, + project_id: str, + *, + goal: str, + input_paths: list[str], + output_paths: list[str], + expected_revision: int, + ) -> dict[str, Any]: + 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( + project_id, + goal=goal, + input_paths=safe_inputs, + output_paths=safe_outputs, + expected_revision=expected_revision, + ) + + 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) + + def review_plan( + self, + *, + project_id: str, + draft_revision: int, + input_paths: Sequence[str], + output_paths: Sequence[str], + ) -> dict[str, Any]: + project = self._project(project_id) + draft = self.draft(project_id) + if draft is None or not draft["goal"] or draft["revision"] != draft_revision: + raise ValueError("task_draft_revision_stale") + if draft["input_paths"] != list(input_paths) or draft["output_paths"] != list(output_paths): + raise ValueError("task_draft_scope_stale") + base = snapshot_source(project.root, input_paths) + outputs = tuple(validate_relative_path(item) for item in output_paths) + if not outputs or len(set(item.casefold() for item in outputs)) != len(outputs): + raise ValueError("task_output_scope_invalid") + helper = _helper_path() + absent_outputs = verify_output_scope(project.root, input_paths, outputs) + provider_preflight: Mapping[str, object] = {} + if isinstance(self.provider_factory, CandidateProviderCommandFactory): + provider_preflight = self.provider_factory.preflight() + binary = provider_preflight.get("binary") + binary_hash = _hash_file(Path(str(binary))) if isinstance(binary, str) else digest_json({"fixture": self.provider}) + body = { + "contract": PLAN_CONTRACT, + "project_id": project_id, + "goal": draft["goal"], + "draft_revision": draft_revision, + "input_paths": list(sorted(entry.path for entry in base.entries)), + "output_paths": list(sorted(outputs)), + "absent_output_paths": list(absent_outputs), + "base_manifest_hash": base.manifest_hash, + "provider": self.provider, + "model": self.model, + "provider_binary_hash": binary_hash, + "check_profile_id": CHECK_PROFILE_ID, + "check_profile_version": CHECK_PROFILE_VERSION, + "helper_hash": _hash_file(helper), + "limits": {"files": 32, "file_bytes": 65536, "total_bytes": 2097152}, + } + return self.store.save_plan(body) + + def start(self, *, request_id: str, plan_hash: str) -> dict[str, Any]: + prior = self.store.replay(request_id, plan_hash) + if prior is not None: + return self.task(str(prior["task_id"])) + if any( + task.get("state") == "termination_unknown" + for task in self.store.snapshot()["tasks"].values() + if isinstance(task, dict) + ): + raise ValueError("task_termination_unknown") + plans = self.store.snapshot()["plans"] + 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") + self._revalidate_plan(plan) + request = {"plan_hash": plan_hash, "project_id": plan["project_id"]} + with self._lock: + if self._active_task is not None: + raise ValueError("task_runtime_busy") + task, created = self.store.reserve(request_id, request) + if not created: + return self.task(str(task["task_id"])) + self._active_task = str(task["task_id"]) + self._worker = threading.Thread(target=self._run, args=(str(task["task_id"]), plan_hash, plan), daemon=True) + self._worker.start() + return self.task(str(task["task_id"])) + + def replay_start(self, *, request_id: str, plan_hash: str) -> dict[str, Any]: + prior = self.store.replay(request_id, plan_hash) + if prior is None: + raise ValueError("task_request_replay_missing") + return self.task(str(prior["task_id"])) + + def stop(self, task_id: str) -> dict[str, Any]: + with self._lock: + current = self.store.snapshot()["tasks"].get(task_id) + if isinstance(current, dict) and current.get("state") in {"candidate_ready", "failed", "cancelled", "interrupted", "termination_unknown"}: + return self.task(task_id) + if task_id != self._active_task: + raise ValueError("task_not_active") + self._cancel_requested.add(task_id) + owner = self._owner + self.store.update_task(task_id, state="stop_requested") + if owner is not None: + observation = owner.force_stop(timeout=5) + if not observation.confirmed: + with self._lock: + self._termination_unknown.add(task_id) + self.store.update_task(task_id, state="termination_unknown", finding="task_termination_unknown") + return self.task(task_id) + + def history(self) -> list[dict[str, Any]]: + tasks = self.store.snapshot()["tasks"] + return [self.task(task_id) for task_id in reversed(list(tasks)[-50:])] + + def task(self, task_id: str) -> dict[str, Any]: + task = self.store.snapshot()["tasks"].get(task_id) + if not isinstance(task, dict): + raise ValueError("task_unknown") + projected = dict(task) + plan = self.store.snapshot()["plans"].get(task.get("plan_hash")) + if isinstance(plan, dict): + goal = str(plan.get("goal", "")).splitlines()[0][:120] + projected["goal_summary"] = goal + project = self.projects.get(str(plan.get("project_id"))) + projected["project_label"] = project.label if project is not None else "Configured project" + if task.get("state") == "candidate_ready": + projected.update(self._project_ready(task_id, task)) + projected.pop("request_id", None) + projected.pop("request_digest", None) + return projected + + def _project(self, project_id: str) -> TaskProject: + project = self.projects.get(project_id) + if project is None: + raise ValueError("task_project_unknown") + return project + + def _revalidate_plan(self, plan: Mapping[str, Any]) -> SourceSnapshot: + if ( + plan.get("contract") != PLAN_CONTRACT + or plan.get("provider") != self.provider + or plan.get("model") != self.model + or plan.get("check_profile_id") != CHECK_PROFILE_ID + or plan.get("check_profile_version") != CHECK_PROFILE_VERSION + ): + raise ValueError("task_plan_identity_invalid") + project = self._project(str(plan["project_id"])) + base = snapshot_source(project.root, [str(item) for item in plan["input_paths"]]) + verify_output_scope( + project.root, + [str(item) for item in plan["input_paths"]], + [str(item) for item in plan["output_paths"]], + expected_absent=[str(item) for item in plan["absent_output_paths"]], + ) + if base.manifest_hash != plan["base_manifest_hash"] or _hash_file(_helper_path()) != plan["helper_hash"]: + raise ValueError("task_plan_stale") + if isinstance(self.provider_factory, CandidateProviderCommandFactory): + current = self.provider_factory.preflight() + binary = current.get("binary") + if not isinstance(binary, str) or _hash_file(Path(binary)) != plan["provider_binary_hash"]: + raise ValueError("task_provider_binary_changed") + return base + + def _artifact(self, broker: EvidenceBroker, name: str, content: str) -> tuple[str, 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("task_artifact_content_changed") + relative = path.relative_to(broker.run_root).as_posix() + return relative, ReceiptChain.hash_file(path), digest_bytes(content.encode("utf-8")) + + def _append(self, broker: EvidenceBroker, body: Mapping[str, Any]) -> dict[str, Any]: + capability = broker.issue("orchestrator") + return broker.append(capability.token, "audit", body) + + def _run_process(self, command: CandidateProviderCommand, task_id: str, *, timeout: float) -> tuple[bytes, ExitObservation]: + owner = self.owner_factory(command.argv, cwd=command.cwd, env=command.environment, input_data=command.input_data) + with self._lock: + self._owner = owner + try: + stdout = bytearray() + overflow = False + deadline = time.monotonic() + timeout + stop_started = False + forced_deadline: float | None = None + while True: + event = owner.next_event(timeout=0.05) + if event is None: + if owner.poll() is not None and owner.output_closed: + break + if time.monotonic() >= deadline and not stop_started: + owner.force_stop(timeout=5) + stop_started = True + forced_deadline = time.monotonic() + 5 + elif forced_deadline is not None and time.monotonic() >= forced_deadline: + raise RuntimeError("task_termination_unknown") + continue + if event.channel == "stdout": + stdout.extend(event.data) + elif event.channel == "system": + overflow = True + if overflow or len(stdout) > 1_048_576: + raise ValueError("task_provider_output_overflow") + observation = owner.wait(timeout=5) + return bytes(stdout), observation + finally: + owner.close() + with self._lock: + if self._owner is owner: + self._owner = None + + def _run(self, task_id: str, plan_hash: str, plan: Mapping[str, Any]) -> None: + broker: EvidenceBroker | None = None + last_sequence: int | None = None + phase = "preparing" + provider_dispatched = False + try: + self.store.update_task(task_id, state=phase) + 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()} + 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) + start = self._append(broker, { + "task_contract": TASK_CONTRACT, "event": "task_start_accepted", "task_id": task_id, + "provider_dispatch": False, "request_digest": self.store.snapshot()["tasks"][task_id]["request_digest"], + "plan_hash": plan_hash, "base_manifest_hash": base.manifest_hash, "input_hash": input_hash, + "artifact": artifact, "artifact_hash": cipher_hash, "artifact_content_hash": content_hash, + "provider": self.provider, "model": self.model, + }) + last_sequence = int(start["sequence"]) + if task_id in self._cancel_requested: + raise InterruptedError("task_cancelled") + phase = "generating" + self.store.update_task(task_id, state=phase, provider_dispatch=True) + prompt = self._prompt(plan, input_bundle, plan_hash, input_hash) + command = self.provider_factory(prompt) + provider_dispatched = True + raw, observation = self._run_process(command, task_id, timeout=120) + with self._lock: + cancel_requested = task_id in self._cancel_requested + termination_unknown = task_id in self._termination_unknown + if cancel_requested: + if termination_unknown or not observation.confirmed: + raise RuntimeError("task_termination_unknown") + raise InterruptedError("task_cancelled") + if observation.returncode != 0 or not observation.confirmed or not observation.output_complete: + raise ValueError("task_provider_failed") + operations, raw_hash = parse_candidate_output(raw, plan_hash=plan_hash, input_hash=input_hash) + if self._revalidate_plan(plan).manifest_hash != base.manifest_hash: + raise ValueError("task_source_changed") + task_root = self.work_root / task_id + task_root.mkdir(parents=True, exist_ok=False) + restrict_owner_only_directory(task_root) + candidate = materialize_candidate(task_root / "candidate", base, operations, allowed_output_paths=plan["output_paths"]) + canonical_ops = [] + for operation in operations: + content = str(operation["content"]).encode("utf-8") + canonical_ops.append({**operation, "content_bytes": len(content), "content_hash": digest_bytes(content)}) + candidate_bundle = canonical_json( + { + "contract": "torq-candidate-bundle-v1", + "manifest_hash": candidate.manifest_hash, + "operations": canonical_ops, + "raw_response": raw.decode("utf-8"), + } + ) + artifact, cipher_hash, content_hash = self._artifact(broker, "candidate-bundle", candidate_bundle) + generated = self._append(broker, { + "task_contract": TASK_CONTRACT, "event": "candidate_generated", "task_id": task_id, + "provider_dispatch": True, "start_sequence": last_sequence, "plan_hash": plan_hash, + "input_hash": input_hash, "candidate_manifest_hash": candidate.manifest_hash, + "raw_response_hash": raw_hash, "artifact": artifact, "artifact_hash": cipher_hash, + "artifact_content_hash": content_hash, "provider": self.provider, "model": self.model, + "termination": "confirmed_empty", + }) + last_sequence = int(generated["sequence"]) + phase = "checking" + self.store.update_task(task_id, state=phase, candidate_files=[item.path for item in candidate.entries]) + check_output, check_observation, helper_hash, argv_hash = self._check(task_root, candidate) + with self._lock: + if task_id in self._termination_unknown: + raise RuntimeError("task_termination_unknown") + if task_id in self._cancel_requested: + raise InterruptedError("task_cancelled") + check_text = check_output.decode("utf-8") + artifact, cipher_hash, content_hash = self._artifact(broker, "structural-check", check_text) + checked = self._append(broker, { + "task_contract": TASK_CONTRACT, "event": "candidate_check_completed", "task_id": task_id, + "provider_dispatch": False, "generated_sequence": last_sequence, + "candidate_manifest_hash": candidate.manifest_hash, "check_profile_id": CHECK_PROFILE_ID, + "check_profile_version": CHECK_PROFILE_VERSION, "helper_hash": helper_hash, "argv_hash": argv_hash, + "exit_code": check_observation.returncode, "output_hash": digest_bytes(check_output), + "output_complete": check_observation.output_complete, "termination": "confirmed_empty" if check_observation.confirmed else "unknown", + "artifact": artifact, "artifact_hash": cipher_hash, "artifact_content_hash": content_hash, + }) + last_sequence = int(checked["sequence"]) + if check_observation.returncode != 0 or not check_observation.confirmed or not check_observation.output_complete: + raise ValueError("task_check_failed") + source_recheck = self._revalidate_plan(plan) + disk_candidate = snapshot_candidate_exact(task_root / "candidate", [item.path for item in candidate.entries]) + if disk_candidate.manifest_hash != candidate.manifest_hash: + raise ValueError("task_candidate_changed") + with self._lock: + if task_id in self._termination_unknown: + raise RuntimeError("task_termination_unknown") + if task_id in self._cancel_requested: + raise InterruptedError("task_cancelled") + ready = self._append(broker, { + "task_contract": TASK_CONTRACT, "event": "candidate_ready", "task_id": task_id, + "provider_dispatch": False, "start_sequence": int(start["sequence"]), + "generated_sequence": int(generated["sequence"]), "check_sequence": last_sequence, + "plan_hash": plan_hash, "base_manifest_hash": base.manifest_hash, "input_hash": input_hash, + "candidate_manifest_hash": candidate.manifest_hash, "source_recheck_hash": source_recheck.manifest_hash, + }) + del ready + broker.seal() + self.store.update_task(task_id, state="candidate_ready", finding=None, candidate_manifest_hash=candidate.manifest_hash, check_exit_code=0) + except BaseException as exc: + reason = _safe_reason(exc) + unknown = reason == "task_termination_unknown" + cancelled = isinstance(exc, InterruptedError) and reason == "task_cancelled" + state = "termination_unknown" if unknown else "cancelled" if cancelled else "failed" + if broker is not None: + try: + event = "task_interrupted" if unknown else "task_cancelled" if cancelled else "task_failed" + termination = "unknown" if unknown else "confirmed_empty" if provider_dispatched else "not_started" + self._append(broker, { + "task_contract": TASK_CONTRACT, "event": event, "task_id": task_id, + "phase": phase, "reason_code": reason, "caused_by_sequence": last_sequence, + "provider_dispatch": provider_dispatched, "termination": termination, + }) + broker.seal() + except BaseException: + state = "interrupted" + reason = "task_evidence_write_failed" + self.store.update_task(task_id, state=state, finding=reason) + finally: + with self._lock: + if self._active_task == task_id: + self._active_task = None + self._cancel_requested.discard(task_id) + self._worker = None + + def _prompt(self, plan: Mapping[str, Any], input_bundle: Mapping[str, Any], plan_hash: str, input_hash: str) -> str: + return ( + "Return only one JSON object with no markdown. Tools and filesystem access are unavailable. " + "The contract field must be exactly torq-candidate-output-v1. The exact schema is " + "{contract,plan_hash,input_hash,operations}; each operation is " + "{operation:create|replace,path,base_hash,content}. Produce at least one changed UTF-8 file " + "and only paths in allowed_output_paths.\n" + + canonical_json({"plan_hash": plan_hash, "input_hash": input_hash, "goal": plan["goal"], "allowed_output_paths": plan["output_paths"], "input": input_bundle}) + ) + + def _check(self, task_root: Path, candidate: SourceSnapshot) -> tuple[bytes, ExitObservation, str, str]: + helper = _helper_path() + helper_hash = _hash_file(helper) + manifest_path = task_root / "structural-manifest.json" + manifest_path.write_text(canonical_json({"contract": "torq-structural-check-v1", "files": [item.path for item in candidate.entries]}), encoding="utf-8") + restrict_owner_only_file(manifest_path) + argv = (str(self.python_executable), "-I", "-S", str(helper), str(manifest_path)) + command = CandidateProviderCommand(argv, str(task_root / "candidate"), {"PYTHONIOENCODING": "utf-8"}, b"", "host", CHECK_PROFILE_ID) + output, observation = self._run_process(command, "checker", timeout=30) + return output, observation, helper_hash, digest_json(list(argv)) + + def _project_ready(self, task_id: str, task: Mapping[str, Any]) -> dict[str, Any]: + root = self.evidence_root / task_id + verification = verify_receipt_store(root) + if verification.status != "verified": + return {"state": "untrusted", "finding": verification.finding or verification.status} + try: + manifest = json.loads((root / "terminal-manifest.json").read_text(encoding="utf-8")) + if manifest.get("sealed") is not True: + raise ValueError("task_evidence_unsealed") + receipts = [json.loads(line) for line in (root / "receipts.jsonl").read_text(encoding="utf-8").splitlines()] + bodies = [row["payload"] for row in receipts if row.get("payload", {}).get("task_contract") == TASK_CONTRACT] + started = next(body for body in bodies if body["event"] == "task_start_accepted") + 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") + 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"])) + if ( + digest_bytes(input_plain) != started["artifact_content_hash"] + or digest_bytes(candidate_plain) != generated["artifact_content_hash"] + or digest_bytes(check_plain) != checked["artifact_content_hash"] + or digest_bytes(input_plain) != started["input_hash"] + or digest_bytes(check_plain) != checked["output_hash"] + ): + raise ValueError("task_artifact_content_hash_mismatch") + input_bundle = json.loads(input_plain) + 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"] + if digest_json(plan) != started["plan_hash"] or started["plan_hash"] != ready["plan_hash"]: + raise ValueError("task_plan_artifact_mismatch") + base = self._revalidate_plan(plan) + if input_bundle.get("files") != base.bundle() or base.manifest_hash != started["base_manifest_hash"]: + raise ValueError("task_base_artifact_mismatch") + paths = list(plan["input_paths"]) + for path in plan["output_paths"]: + if path not in paths and (self.work_root / task_id / "candidate" / path).exists(): + paths.append(path) + disk = snapshot_candidate_exact(self.work_root / task_id / "candidate", paths) + if disk.manifest_hash != ready["candidate_manifest_hash"] or base.manifest_hash != ready["source_recheck_hash"]: + raise ValueError("task_result_identity_mismatch") + bundle = json.loads(candidate_plain) + check = json.loads(check_plain) + expected_validators = { + ".py": "python_ast", + ".json": "strict_json", + ".md": "utf8_text", + ".txt": "utf8_text", + } + expected_checked = [ + { + "path": item.path, + "validator": expected_validators[Path(item.path).suffix.casefold()], + } + for item in disk.entries + ] + expected_argv = ( + str(self.python_executable), + "-I", + "-S", + str(_helper_path()), + str(self.work_root / task_id / "structural-manifest.json"), + ) + raw_response = bundle.get("raw_response") + operations = bundle.get("operations") + if ( + bundle.get("contract") != "torq-candidate-bundle-v1" + or bundle.get("manifest_hash") != disk.manifest_hash + or not isinstance(raw_response, str) + or digest_bytes(raw_response.encode("utf-8")) != generated["raw_response_hash"] + or not isinstance(operations, list) + or check.get("status") != "passed" + or set(check) != {"contract", "checked", "status"} + or check.get("contract") != "torq-structural-result-v1" + or check.get("checked") != expected_checked + or checked["helper_hash"] != plan["helper_hash"] + or _hash_file(_helper_path()) != checked["helper_hash"] + or checked["candidate_manifest_hash"] != disk.manifest_hash + or checked["argv_hash"] != digest_json(list(expected_argv)) + ): + raise ValueError("task_result_artifact_mismatch") + parsed_operations, _ = parse_candidate_output( + raw_response.encode("utf-8"), + plan_hash=ready["plan_hash"], + input_hash=ready["input_hash"], + ) + expected_ops = [] + for operation in parsed_operations: + raw_content = str(operation["content"]).encode("utf-8") + expected_ops.append( + { + **operation, + "content_bytes": len(raw_content), + "content_hash": digest_bytes(raw_content), + } + ) + if operations != expected_ops: + raise ValueError("task_candidate_artifact_mismatch") + disk_by_path = {entry.path: entry.content_hash for entry in disk.entries} + if any( + disk_by_path.get(str(operation["path"])) != operation["content_hash"] + 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"]}} + except (OSError, ValueError, KeyError, StopIteration, json.JSONDecodeError): + return {"state": "untrusted", "finding": "task_result_verification_failed", "verified": False} + + +__all__ = ["CandidateTaskService", "TaskProject"] diff --git a/src/torq_cli/application/task_store.py b/src/torq_cli/application/task_store.py new file mode 100644 index 0000000..26130d6 --- /dev/null +++ b/src/torq_cli/application/task_store.py @@ -0,0 +1,220 @@ +"""Durable CAS drafts, immutable plans, and idempotent task reservations.""" + +from __future__ import annotations + +import json +import os +import secrets +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_json + +MAX_GOAL_CHARS = 16_384 + + +class TaskStore: + def __init__(self, state_root: Path) -> None: + self.root = state_root.resolve() + self.root.mkdir(parents=True, exist_ok=True) + restrict_owner_only_directory(self.root) + self.path = self.root / "tasks.json" + self._lock = threading.RLock() + if not self.path.exists(): + self._write({"schema": "torq-task-store-v1", "drafts": {}, "plans": {}, "requests": {}, "tasks": {}}) + + 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 > 4_194_304 + or not signing_file_permissions_are_restricted(self.path) + ): + raise ValueError("task_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) + raw = bytearray() + while len(raw) <= 4_194_304: + chunk = os.read(descriptor, min(65_536, 4_194_305 - len(raw))) + if not chunk: + break + raw.extend(chunk) + after = os.fstat(descriptor) + finally: + os.close(descriptor) + if len(raw) > 4_194_304 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("task_store_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_store_duplicate_key") + result[key] = child + return result + + def reject_constant(value: str) -> object: + del value + raise ValueError("task_store_non_finite") + + value = json.loads(bytes(raw), object_pairs_hook=unique, parse_constant=reject_constant) + if ( + not isinstance(value, dict) + or set(value) != {"schema", "drafts", "plans", "requests", "tasks"} + or value.get("schema") != "torq-task-store-v1" + or not all(isinstance(value.get(key), dict) for key in ("drafts", "plans", "requests", "tasks")) + ): + raise ValueError("task_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() + + def put_draft( + self, + project_id: str, + *, + goal: str, + input_paths: list[str], + output_paths: list[str], + expected_revision: int, + ) -> dict[str, Any]: + if not goal.strip() or len(goal) > MAX_GOAL_CHARS or "\x00" in goal: + raise ValueError("task_goal_invalid") + with self._lock: + data = self._read() + current = data["drafts"].get(project_id) + revision = 0 if current is None else current["revision"] + if expected_revision != revision: + raise ValueError("task_draft_revision_conflict") + draft = { + "project_id": project_id, + "goal": goal, + "input_paths": input_paths, + "output_paths": output_paths, + "revision": revision + 1, + } + data["drafts"][project_id] = draft + self._write(data) + return draft + + def delete_draft(self, project_id: str, *, expected_revision: int) -> None: + with self._lock: + data = self._read() + current = data["drafts"].get(project_id) + if current is None or current["revision"] != expected_revision: + raise ValueError("task_draft_revision_conflict") + data["drafts"][project_id] = { + "project_id": project_id, + "goal": None, + "input_paths": [], + "output_paths": [], + "revision": expected_revision + 1, + } + referenced = { + task.get("plan_hash") + for task in data["tasks"].values() + if isinstance(task, dict) + } + data["plans"] = { + digest: plan + for digest, plan in data["plans"].items() + if digest in referenced + or not ( + isinstance(plan, dict) + and plan.get("project_id") == project_id + and isinstance(plan.get("draft_revision"), int) + and plan["draft_revision"] <= expected_revision + ) + } + self._write(data) + + def save_plan(self, body: Mapping[str, Any]) -> dict[str, Any]: + plan = dict(body) + plan_hash = digest_json(plan) + with self._lock: + data = self._read() + existing = data["plans"].get(plan_hash) + if existing is not None and existing != plan: + raise ValueError("task_plan_hash_collision") + data["plans"][plan_hash] = plan + self._write(data) + return {**plan, "plan_hash": plan_hash} + + def reserve(self, request_id: str, request_body: Mapping[str, Any]) -> tuple[dict[str, Any], bool]: + if not request_id or len(request_id) > 128: + raise ValueError("task_request_id_invalid") + if set(request_body) != {"plan_hash", "project_id"} or not all( + isinstance(request_body.get(key), str) and request_body[key] + for key in ("plan_hash", "project_id") + ): + raise ValueError("task_request_body_invalid") + request_digest = digest_json(request_body) + with self._lock: + data = self._read() + prior = data["requests"].get(request_id) + if prior is not None: + if prior["request_digest"] != request_digest: + raise ValueError("task_request_replay_conflict") + return dict(data["tasks"][prior["task_id"]]), False + task_id = "run-task-" + secrets.token_hex(12) + task = { + **dict(request_body), + "task_id": task_id, + "request_id": request_id, + "request_digest": request_digest, + "state": "reserved", + "provider_dispatch": False, + "finding": None, + } + data["requests"][request_id] = {"request_digest": request_digest, "task_id": task_id} + data["tasks"][task_id] = task + self._write(data) + return task, True + + def replay(self, request_id: str, plan_hash: str) -> dict[str, Any] | None: + with self._lock: + data = self._read() + prior = data["requests"].get(request_id) + if prior is None: + return None + task = data["tasks"].get(prior.get("task_id")) + if not isinstance(task, dict) or task.get("plan_hash") != plan_hash: + raise ValueError("task_request_replay_conflict") + return dict(task) + + def update_task(self, task_id: str, **changes: object) -> dict[str, Any]: + with self._lock: + data = self._read() + current = data["tasks"].get(task_id) + if current is None: + raise ValueError("task_unknown") + current.update(changes) + self._write(data) + return dict(current) + + +__all__ = ["MAX_GOAL_CHARS", "TaskStore"] diff --git a/src/torq_cli/application/workspace.py b/src/torq_cli/application/workspace.py new file mode 100644 index 0000000..0de331a --- /dev/null +++ b/src/torq_cli/application/workspace.py @@ -0,0 +1,188 @@ +"""Read-only workspace classification and capability metadata.""" + +from __future__ import annotations + +import hashlib +import os +import re +import stat +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +_EVIDENCE_FILES = ("receipts.jsonl", "terminal-manifest.json", "run-certificate.json") +_SAFE_RUN_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}\Z") +_COLLECTION_RUN_ID = re.compile(r"run-[A-Za-z0-9][A-Za-z0-9._-]{0,119}\Z") +_TRUSTED_STATES = frozenset({"live_verified", "sealed_verified", "live_catching_up"}) +_MAX_COLLECTION_RUNS = 64 +_MAX_SCAN_ENTRIES = 256 + + +def _is_link_or_reparse(path: Path) -> bool: + try: + details = path.lstat() + except OSError: + return False + attributes = int(getattr(details, "st_file_attributes", 0)) + reparse_flag = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)) + return stat.S_ISLNK(details.st_mode) or bool(attributes & reparse_flag) + + +def _has_link_component(path: Path) -> bool: + current = Path(os.path.abspath(os.fspath(path))) + while True: + if _is_link_or_reparse(current): + return True + if current.parent == current: + return False + current = current.parent + + +def _workspace_id(root: Path) -> str: + canonical = os.path.normcase(os.path.abspath(os.fspath(root))) + digest = hashlib.sha256(canonical.encode("utf-8", errors="surrogatepass")).hexdigest() + return f"workspace_{digest[:32]}" + + +def _safe_run_id(value: object) -> str | None: + return value if isinstance(value, str) and _SAFE_RUN_ID.fullmatch(value) else None + + +def _collection_runs(root: Path) -> list[str]: + candidates: list[str] = [] + try: + scanner = os.scandir(root) + except OSError: + return candidates + with scanner: + for index, entry in enumerate(scanner): + if index >= _MAX_SCAN_ENTRIES or len(candidates) >= _MAX_COLLECTION_RUNS: + break + run_id = _safe_run_id(entry.name) + child = Path(entry.path) + if ( + run_id is None + or _COLLECTION_RUN_ID.fullmatch(entry.name) is None + or _is_link_or_reparse(child) + ): + continue + try: + if not entry.is_dir(follow_symlinks=False) or not all( + (child / name).is_file() for name in _EVIDENCE_FILES + ): + continue + except OSError: + continue + candidates.append(run_id) + return sorted(candidates, key=str.casefold) + + +def classify_workspace_root( + root: Path, + snapshot: Mapping[str, Any] | None = None, +) -> dict[str, Any]: + """Classify one configured root without creating keys, journals, or directories.""" + result: dict[str, Any] = { + "workspace_id": _workspace_id(root), + "root_kind": "unavailable", + "selected_run_id": None, + "runs": [], + "trusted": False, + "verification_state": "unknown", + "run_mode": "unknown", + "reason_code": "workspace_root_unavailable", + "message": "This workspace could not be opened.", + "remediation": "Check the run location and try again.", + } + if _has_link_component(root): + return { + **result, + "reason_code": "workspace_root_link_denied", + "message": "Linked run folders are not opened by Workspace.", + "remediation": "Launch Workspace with the real, local individual run folder.", + } + if not root.exists(): + return { + **result, + "root_kind": "missing", + "reason_code": "workspace_root_missing", + "message": "This run folder does not exist.", + "remediation": "Launch Workspace with an existing individual run folder.", + } + try: + if not root.is_dir(): + return { + **result, + "reason_code": "workspace_root_not_directory", + "message": "The selected workspace is not a folder.", + "remediation": "Choose an individual TORQ run folder.", + } + with os.scandir(root) as scanner: + has_entries = next(scanner, None) is not None + except OSError: + return result + if not has_entries: + return { + **result, + "root_kind": "empty", + "reason_code": "workspace_root_empty", + "message": "This folder does not contain a TORQ run yet.", + "remediation": "Create a run with the CLI, then launch Workspace with that run folder.", + } + + has_evidence_shape = any((root / name).exists() for name in _EVIDENCE_FILES) + if has_evidence_shape: + verification = snapshot.get("verification") if isinstance(snapshot, Mapping) else None + run = snapshot.get("run") if isinstance(snapshot, Mapping) else None + verification_state = ( + str(verification.get("state")) if isinstance(verification, Mapping) else "unknown" + ) + selected_run_id = _safe_run_id(run.get("run_id")) if isinstance(run, Mapping) else None + trusted = bool( + isinstance(snapshot, Mapping) + and snapshot.get("data_status") == "available" + and verification_state in _TRUSTED_STATES + and selected_run_id is not None + ) + if trusted: + mode = run.get("mode") if isinstance(run, Mapping) else None + return { + **result, + "root_kind": "individual_run", + "selected_run_id": selected_run_id, + "trusted": True, + "verification_state": verification_state, + "run_mode": mode if isinstance(mode, str) else "unknown", + "reason_code": None, + "message": "This run is ready to inspect.", + "remediation": None, + } + return { + **result, + "root_kind": "individual_run", + "selected_run_id": selected_run_id, + "verification_state": verification_state, + "reason_code": "workspace_run_untrusted", + "message": "This run's history could not be verified.", + "remediation": "Inspect Fleet details or choose another verified individual run.", + } + + runs = _collection_runs(root) + if runs: + return { + **result, + "root_kind": "collection", + "runs": runs, + "reason_code": "workspace_run_selection_required", + "message": "Choose an individual run to open.", + "remediation": "Relaunch with --run-root followed by one of the relative run IDs below.", + } + return { + **result, + "reason_code": "workspace_root_unrecognized", + "message": "This folder is not a TORQ run or run collection.", + "remediation": "Choose a folder containing one verified run, or a collection of run-* folders.", + } + + +__all__ = ["classify_workspace_root"] diff --git a/src/torq_cli/checkers/__init__.py b/src/torq_cli/checkers/__init__.py new file mode 100644 index 0000000..332cf5d --- /dev/null +++ b/src/torq_cli/checkers/__init__.py @@ -0,0 +1 @@ +"""Fixed host-owned candidate checks.""" diff --git a/src/torq_cli/checkers/structural.py b/src/torq_cli/checkers/structural.py new file mode 100644 index 0000000..46f9fe4 --- /dev/null +++ b/src/torq_cli/checkers/structural.py @@ -0,0 +1,68 @@ +"""Isolated structural-v1 checker. Never imports or executes candidate code.""" + +from __future__ import annotations + +import ast +import json +import sys +from pathlib import Path + + +def _reject_pairs(pairs: list[tuple[str, object]]) -> dict[str, object]: + value: dict[str, object] = {} + for key, child in pairs: + if key in value: + raise ValueError("duplicate_key") + value[key] = child + return value + + +def _reject_constant(value: str) -> object: + del value + raise ValueError("non_finite") + + +def main() -> int: + if len(sys.argv) != 2: + return 2 + try: + manifest = json.loads( + Path(sys.argv[1]).read_text(encoding="utf-8"), + object_pairs_hook=_reject_pairs, + parse_constant=_reject_constant, + ) + if not isinstance(manifest, dict) or set(manifest) != {"contract", "files"}: + raise ValueError("manifest_schema") + if manifest["contract"] != "torq-structural-check-v1" or not isinstance(manifest["files"], list): + raise ValueError("manifest_schema") + checked: list[dict[str, str]] = [] + for raw_path in manifest["files"]: + if not isinstance(raw_path, str): + raise ValueError("path_schema") + path = Path(raw_path) + content = path.read_text(encoding="utf-8") + suffix = path.suffix.casefold() + if suffix == ".py": + ast.parse(content, filename=path.name) + validator = "python_ast" + elif suffix == ".json": + json.loads( + content, + object_pairs_hook=_reject_pairs, + parse_constant=_reject_constant, + ) + validator = "strict_json" + elif suffix in {".md", ".txt"}: + validator = "utf8_text" + else: + raise ValueError("unsupported_extension") + checked.append({"path": raw_path, "validator": validator}) + print(json.dumps({"contract": "torq-structural-result-v1", "checked": checked, "status": "passed"}, sort_keys=True, separators=(",", ":"))) + return 0 + except (OSError, UnicodeError, SyntaxError, ValueError, json.JSONDecodeError) as exc: + print(json.dumps({"contract": "torq-structural-result-v1", "reason": type(exc).__name__, "status": "failed"}, sort_keys=True, separators=(",", ":"))) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/torq_cli/data/fleet/chat.css b/src/torq_cli/data/fleet/chat.css index 0dc5d97..89d5762 100644 --- a/src/torq_cli/data/fleet/chat.css +++ b/src/torq_cli/data/fleet/chat.css @@ -194,3 +194,181 @@ } .chat-send { --chat-send-fg: #17130a; } :root[data-theme="light"] .chat-send { --chat-send-fg: #ffffff; } + +.view-switch { + display: inline-flex; + padding: .2rem; + border: 1px solid var(--line); + border-radius: 999px; + background: var(--surface-1); +} +.view-switch button { + min-height: 2.35rem; + border: 0; + border-radius: 999px; + padding: .45rem .85rem; + color: var(--text-3); + background: transparent; + cursor: pointer; + font-size: .8rem; +} +.view-switch button[aria-pressed="true"] { + color: var(--text-1); + background: var(--surface-3); + box-shadow: 0 .15rem .5rem var(--shadow); +} + +.workspace[hidden] { display: none; } +.workspace { + width: min(74rem, 100%); + margin: 0 auto; + padding: clamp(2.5rem, 7vw, 6rem) 0 5rem; +} +.workspace-hero { max-width: 43rem; margin-bottom: 2.2rem; } +.workspace-context, +.workspace-label { + margin: 0; + color: var(--accent-soft); + font: 650 .72rem/1.4 "Cascadia Mono", Consolas, monospace; + letter-spacing: .08em; + text-transform: uppercase; +} +.workspace-hero h1 { + margin: .55rem 0 .75rem; + font: 720 clamp(2rem, 6vw, 3.65rem)/1.04 "Segoe UI", Aptos, system-ui, sans-serif; + letter-spacing: -.045em; +} +.workspace-summary { margin: 0; color: var(--text-2); font-size: 1.05rem; line-height: 1.65; } +.workspace-layout { display: grid; grid-template-columns: minmax(0, 1fr) minmax(17rem, 21rem); gap: 2rem; align-items: start; } +.workspace-main { min-width: 0; display: grid; gap: 1.25rem; } +.workspace-side { display: grid; gap: 1rem; position: sticky; top: 1rem; } + +.workspace-composer { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: .8rem; + padding: 1.2rem; + border: 1px solid var(--line); + border-radius: 1rem; + background: var(--surface-2); + box-shadow: 0 1.25rem 3.5rem var(--shadow); + backdrop-filter: none; +} +.composer-heading { grid-column: 1 / -1; display: flex; justify-content: space-between; align-items: start; gap: 1rem; } +.composer-heading strong { display: block; margin-top: .3rem; font-size: 1.05rem; } +.draft-state { color: var(--text-3); font-size: .75rem; white-space: nowrap; } +.draft-state[data-error="true"] { color: var(--state-needs_you-fg); } +.workspace-composer .chat-input { + grid-column: 1 / -1; + min-height: 8rem; + max-height: 22rem; + border-radius: .75rem; + padding: 1rem; + resize: vertical; + background: var(--surface-1); + font-size: 1rem; + line-height: 1.55; +} +.workspace-composer .chat-attachments { align-self: center; } +.composer-actions { display: flex; justify-content: flex-end; gap: .5rem; } +.composer-actions button { text-transform: none; letter-spacing: 0; border-radius: .6rem; font-family: inherit; font-size: .82rem; } +.chat-clear { margin-right: auto; border-color: transparent !important; color: var(--text-3); background: transparent; } +.workspace-composer .chat-help, +.workspace-composer .chat-status { grid-column: 1 / -1; font-family: inherit; font-size: .78rem; line-height: 1.45; text-transform: none; } + +.workspace-suggestions { display: flex; flex-wrap: wrap; gap: .55rem; } +.workspace-suggestions button, +.workspace-refresh { + min-height: 2.5rem; + border: 1px solid var(--line); + border-radius: 999px; + padding: .5rem .8rem; + color: var(--text-2); + background: var(--surface-1); + cursor: pointer; + font-size: .8rem; +} +.workspace-primary { + min-height: 2.5rem; + border: 1px solid var(--accent); + border-radius: .55rem; + padding: .5rem .8rem; + color: var(--workspace-primary-fg, #17130a); + background: var(--accent-soft); + cursor: pointer; + font-size: .8rem; + font-weight: 700; +} +:root[data-theme="light"] .workspace-primary { --workspace-primary-fg: #ffffff; } +.workspace-guidance-actions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: .85rem; } +.workspace-suggestions button:hover, +.workspace-refresh:hover { border-color: var(--accent); color: var(--text-1); } + +.workspace .chat-workspace { + min-height: 16rem; + margin: 0; + border-radius: 1rem; + overflow: hidden; + background: var(--surface-1); + box-shadow: none; +} +.workspace .chat-workspace .section-heading { padding: 1rem 1.1rem; } +.chat-empty { margin: 1rem 0; padding: 1rem; border-radius: .7rem; color: var(--text-3); background: var(--surface-2); line-height: 1.5; } +.next-action-card, +.run-picker, +.workspace-details { + border: 1px solid var(--line); + border-radius: .9rem; + padding: 1.1rem; + background: var(--surface-1); +} +.next-action-card { border-top: 3px solid var(--accent); } +.next-action-card h2, +.run-picker h2 { margin: .45rem 0 .7rem; font-family: inherit; } +.next-action-card p, +.workspace-details p { color: var(--text-2); font-size: .86rem; line-height: 1.55; } +.next-action-card p:empty { display: none; } +.workspace-refresh { border-radius: .55rem; } +.run-picker-row { display: grid; gap: .3rem; padding: .7rem 0; border-top: 1px solid var(--line); } +.run-picker-row code, +.workspace-details code { overflow-wrap: anywhere; color: var(--text-2); font-size: .72rem; } +.workspace-details summary { cursor: pointer; font-weight: 650; } +.workspace-details dl { margin: 1rem 0; } +.workspace-details dl div { display: grid; grid-template-columns: 6.5rem 1fr; gap: .6rem; padding: .45rem 0; border-bottom: 1px solid var(--line); } +.workspace-details dt { color: var(--text-3); } +.workspace-details dd { margin: 0; overflow-wrap: anywhere; color: var(--text-2); } + +body[data-view="workspace"] .governance-rail, +body[data-view="workspace"] #system-banner, +body[data-view="workspace"] #annotation-list, +body[data-view="workspace"] #fleet-board, +body[data-view="workspace"] #mini-monitor { display: none; } +body[data-view="workspace"] .topbar-facts { display: none; } +body[data-view="workspace"] #chat-evidence-note { display: none; } +body[data-view="workspace"] .shell { padding-bottom: 0; } +body[data-view="workspace"] { + background: + radial-gradient(circle at 18% 8%, color-mix(in srgb, var(--accent) 8%, transparent), transparent 34rem), + var(--surface-0); +} + +@media (max-width: 56rem) { + .workspace-layout { grid-template-columns: 1fr; } + .workspace-side { position: static; grid-row: 1; } + .workspace-main { grid-row: 2; } + .next-action-card { padding: 1rem; } +} + +@media (max-width: 40rem) { + .workspace { padding-top: 1.5rem; } + .workspace-hero { margin-bottom: 1.25rem; } + .workspace-layout { gap: 1rem; } + .workspace-side { grid-template-columns: 1fr; } + .workspace-composer { padding: .85rem; border-radius: .75rem; } + .composer-heading { display: grid; gap: .4rem; } + .draft-state { white-space: normal; } + .workspace-composer .chat-attachments { grid-column: 1 / -1; max-width: 100%; } + .composer-actions { grid-column: 1 / -1; flex-wrap: wrap; } + .composer-actions button { flex: 1 1 auto; } + .workspace-suggestions { flex-wrap: wrap; } +} diff --git a/src/torq_cli/data/fleet/chat.js b/src/torq_cli/data/fleet/chat.js index 841af97..9a4720a 100644 --- a/src/torq_cli/data/fleet/chat.js +++ b/src/torq_cli/data/fleet/chat.js @@ -5,16 +5,22 @@ const MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024; const POLL_INTERVAL_MS = 2500; const STREAM_RETRY_MS = 10000; + const VIEW_KEY = "torq.workspace.view.v1"; + const DRAFT_KEY_PREFIX = "torq.workspace.draft.v1."; const ALLOWED_TYPES = new Map([ ["image/png", { extensions: [".png"], signature: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] }], ["image/jpeg", { extensions: [".jpg", ".jpeg"], signature: [0xff, 0xd8, 0xff] }], ["application/pdf", { extensions: [".pdf"], signature: [0x25, 0x50, 0x44, 0x46, 0x2d] }], + ["application/json", { extensions: [".json"], signature: null }], + ["image/gif", { extensions: [".gif"], signature: [0x47, 0x49, 0x46] }], + ["image/webp", { extensions: [".webp"], signature: null }], ["text/plain", { extensions: [".txt"], signature: null }], ["text/markdown", { extensions: [".md", ".markdown"], signature: null }], ]); const TERMINAL_STATES = new Set(["completed", "cancelled", "failed", "cancellation_uncertain"]); const byId = (id) => global.document?.getElementById(id) || null; + const friendly = (value) => String(value ?? "unknown").replaceAll("_", " "); const createNode = (tag, className, text) => { const element = global.document.createElement(tag); if (className) element.className = className; @@ -125,6 +131,23 @@ send: byId("chat-send"), stop: byId("chat-stop"), status: byId("chat-status"), + help: byId("chat-help"), + clear: byId("clear-draft"), + draftState: byId("draft-state"), + workspace: byId("workspace-view"), + fleetBoard: byId("fleet-board"), + workspaceButton: byId("workspace-view-button"), + fleetButton: byId("fleet-view-button"), + composerSlot: byId("workspace-composer-slot"), + transcriptSlot: byId("workspace-transcript-slot"), + fleetComposerSlot: byId("fleet-composer-slot"), + fleetTranscriptSlot: byId("fleet-transcript-slot"), + transcriptSection: byId("chat-workspace-section"), + refresh: byId("workspace-refresh"), + setup: byId("workspace-setup"), + details: byId("workspace-details"), + detailsSummary: byId("workspace-details-summary"), + suggestions: byId("workspace-suggestions"), }; this.gate = new EventGate(); this.activeTurnId = null; @@ -138,6 +161,13 @@ this.running = false; this.runtimeAvailable = false; this.snapshotInitialized = false; + this.workspace = null; + this.workspaceId = null; + this.draftRevision = 0; + this.draftKey = null; + this.storageAvailable = true; + this.view = "fleet"; + this.submissionPending = false; } completeDom() { @@ -151,33 +181,208 @@ updateControls() { const active = Boolean(this.activeTurnId); - this.elements.send.disabled = active || !this.runtimeAvailable; - this.elements.stop.disabled = !active; - this.elements.input.disabled = active || !this.runtimeAvailable; - this.elements.attachments.disabled = active || !this.runtimeAvailable; + const capabilities = this.workspace?.capabilities || {}; + const canDiscuss = Boolean(capabilities.can_discuss_run && this.runtimeAvailable && !active && !this.submissionPending); + const canCancel = Boolean(active && (capabilities.can_cancel || capabilities.can_discuss_run)); + const attachmentTypes = Array.isArray(capabilities.attachment_types) ? capabilities.attachment_types : []; + this.elements.send.disabled = !canDiscuss; + this.elements.stop.disabled = !canCancel; + this.elements.input.disabled = false; + this.elements.attachments.disabled = active || !canDiscuss || !attachmentTypes.length; + this.elements.attachments.hidden = !attachmentTypes.length; this.elements.composer.dataset.active = String(active); } + setView(view, persist = true) { + this.view = view === "workspace" ? "workspace" : "fleet"; + const composerTarget = this.view === "workspace" ? this.elements.composerSlot : this.elements.fleetComposerSlot; + const transcriptTarget = this.view === "workspace" ? this.elements.transcriptSlot : this.elements.fleetTranscriptSlot; + composerTarget.append(this.elements.composer); + transcriptTarget.append(this.elements.transcriptSection); + this.elements.workspace.hidden = this.view !== "workspace"; + this.elements.workspaceButton.setAttribute("aria-pressed", String(this.view === "workspace")); + this.elements.fleetButton.setAttribute("aria-pressed", String(this.view === "fleet")); + if (global.document.body?.dataset) global.document.body.dataset.view = this.view; + const skip = byId("skip-link"); + if (skip) { + skip.setAttribute("href", this.view === "workspace" ? "#workspace-view" : "#fleet-board"); + skip.textContent = this.view === "workspace" ? "Skip to Workspace" : "Skip to Fleet board"; + } + byId("chat-kicker").textContent = this.view === "workspace" ? "Discussion" : "OWNED PROVIDER SESSION"; + byId("chat-title").textContent = this.view === "workspace" ? "Conversation" : "Governed conversation"; + byId("chat-evidence-note").textContent = this.view === "workspace" + ? "Accepted messages become signed evidence" + : "SIGNED TERMINAL EVIDENCE"; + if (persist) { + try { global.localStorage?.setItem(VIEW_KEY, this.view); } catch (_error) { /* preference applies in this tab */ } + } + } + + configureView() { + let selected = "fleet"; + try { + const stored = global.localStorage?.getItem(VIEW_KEY); + if (stored === "workspace" || stored === "fleet") selected = stored; + } catch (_error) { /* Fleet remains the compatibility default */ } + this.setView(selected, false); + this.elements.workspaceButton.addEventListener("click", () => { + this.setView("workspace"); + this.elements.workspace.focus?.(); + }); + this.elements.fleetButton.addEventListener("click", () => { + this.setView("fleet"); + this.elements.fleetBoard.focus?.(); + }); + } + + setDraftState(text, error = false) { + this.elements.draftState.textContent = text; + this.elements.draftState.dataset.error = String(error); + } + + persistDraft() { + if (!this.draftKey) { + this.setDraftState("Held in this tab"); + return; + } + try { + global.sessionStorage.setItem(this.draftKey, this.elements.input.value); + this.storageAvailable = true; + this.setDraftState(this.elements.input.value ? "Saved for this tab" : "No draft saved"); + } catch (_error) { + this.storageAvailable = false; + this.setDraftState("Held in this tab only", true); + } + } + + loadDraft(workspaceId) { + if (typeof workspaceId !== "string" || !/^workspace_[a-f0-9]{32}$/.test(workspaceId)) return; + if (this.workspaceId === workspaceId) return; + if (this.workspaceId && this.workspaceId !== workspaceId) { + this.persistDraft(); + this.elements.input.value = ""; + this.draftRevision += 1; + } + this.workspaceId = workspaceId; + this.draftKey = `${DRAFT_KEY_PREFIX}${workspaceId}`; + if (this.elements.input.value) { + this.persistDraft(); + return; + } + try { + const saved = global.sessionStorage.getItem(this.draftKey); + if (typeof saved === "string") this.elements.input.value = saved; + this.storageAvailable = true; + this.setDraftState(saved ? "Restored for this tab" : "No draft saved"); + } catch (_error) { + this.storageAvailable = false; + this.setDraftState("Held in this tab only", true); + } + } + + clearDraft() { + this.elements.input.value = ""; + this.draftRevision += 1; + this.persistDraft(); + this.elements.input.focus(); + } + + renderWorkspace(metadata) { + this.workspace = metadata; + this.loadDraft(metadata?.workspace_id); + const root = metadata?.root || {}; + const capabilities = metadata?.capabilities || {}; + const guidance = metadata?.guidance || {}; + const runId = metadata?.selected_run_id || null; + const mode = root.run_mode === "dry_run" ? "Verified dry-run" : friendly(root.run_mode); + const title = runId ? "Discuss this run" : "Welcome to TORQ"; + const context = runId ? runId : root.kind === "collection" ? "Run collection" : "Local workspace"; + byId("workspace-title").textContent = title; + byId("workspace-context").textContent = context; + byId("workspace-summary").textContent = guidance.message || "Review this workspace and choose the next action."; + byId("next-action-title").textContent = capabilities.can_discuss_run + ? "Ask about this run" + : capabilities.can_cancel + ? "TORQ is responding" + : root.kind === "collection" + ? "Choose a run" + : "Setup needed"; + byId("next-action-message").textContent = guidance.message || "Discussion is unavailable."; + byId("next-action-remediation").textContent = guidance.remediation || guidance.consequence || ""; + byId("workspace-root-kind").textContent = friendly(root.kind); + byId("workspace-run-id").textContent = runId || "None selected"; + byId("workspace-trust").textContent = root.trusted ? friendly(root.verification_state) : "Not verified"; + byId("workspace-mode").textContent = mode; + byId("workspace-provider").textContent = metadata?.provider?.name || friendly(metadata?.provider?.configuration); + byId("composer-purpose").textContent = runId ? "Discuss this run" : "Draft"; + + const picker = byId("run-picker"); + const list = byId("run-picker-list"); + list.replaceChildren(); + const runs = Array.isArray(metadata?.runs) ? metadata.runs : []; + picker.hidden = root.kind !== "collection" || !runs.length; + runs.forEach((candidate) => { + const row = createNode("div", "run-picker-row"); + row.append( + createNode("strong", "", candidate), + createNode("code", "", `torq fleet --run-root .\\${candidate} --serve`), + ); + list.append(row); + }); + + const allowed = Array.isArray(capabilities.attachment_types) ? capabilities.attachment_types : []; + this.elements.attachments.setAttribute("accept", allowed.join(",")); + this.elements.attachments.setAttribute("multiple", ""); + this.elements.help.textContent = allowed.length + ? "Supported files: text, Markdown, JSON, images, or PDF. Up to 6 files, 5 MB each. Ctrl or Cmd+Enter sends." + : "Attachments are unavailable for this provider. Your draft stays in this browser tab."; + this.updateControls(); + } + bind() { + this.configureView(); this.elements.transcript.setAttribute("role", "log"); this.elements.transcript.setAttribute("aria-live", "off"); this.elements.status.setAttribute("role", "status"); this.elements.status.setAttribute("aria-live", "polite"); - this.elements.input.setAttribute("aria-keyshortcuts", "Control+Enter"); - this.elements.attachments.setAttribute("accept", [...ALLOWED_TYPES.keys()].join(",")); - this.elements.attachments.setAttribute("multiple", ""); + this.elements.input.setAttribute("aria-keyshortcuts", "Control+Enter Meta+Enter"); this.elements.composer.addEventListener("submit", (event) => { event.preventDefault(); void this.submit(); }); this.elements.stop.addEventListener("click", () => void this.cancel()); + this.elements.clear.addEventListener("click", () => this.clearDraft()); + this.elements.refresh.addEventListener("click", () => void this.refreshWorkspace(true)); + this.elements.setup.addEventListener("click", () => { + this.elements.details.open = true; + this.elements.detailsSummary.focus(); + }); + this.elements.input.addEventListener("input", () => { + this.draftRevision += 1; + this.persistDraft(); + }); this.elements.input.addEventListener("keydown", (event) => { - if (event.key === "Enter" && event.ctrlKey) { + if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) { event.preventDefault(); void this.submit(); } }); this.elements.attachments.addEventListener("change", () => void this.stageFiles()); + if (typeof this.elements.suggestions.querySelectorAll === "function") { + this.elements.suggestions.querySelectorAll("[data-prompt]").forEach((button) => { + button.addEventListener("click", () => { + if (this.elements.input.value) { + this.setStatus("Your current draft was kept. Clear it before inserting a suggestion.", "ready"); + this.elements.input.focus(); + return; + } + this.elements.input.value = button.dataset.prompt || ""; + this.draftRevision += 1; + this.persistDraft(); + this.elements.input.focus(); + }); + }); + } this.updateControls(); } @@ -236,14 +441,21 @@ } async submit() { - if (this.activeTurnId) return; + if (this.activeTurnId || this.submissionPending) return; + if (!this.workspace?.capabilities?.can_discuss_run || !this.runtimeAvailable) { + this.setStatus(this.workspace?.guidance?.message || "Discussion is unavailable. Your draft is preserved.", "error"); + return; + } const text = this.elements.input.value.trim(); if (!text && !this.pendingFiles.length) { this.setStatus("Enter a request or attach a file.", "error"); this.elements.input.focus(); return; } + const submittedRevision = this.draftRevision; + const submittedValue = this.elements.input.value; const turnId = global.crypto?.randomUUID?.() || `turn-${Date.now()}-${Math.random().toString(16).slice(2)}`; + this.submissionPending = true; this.activeTurnId = turnId; this.updateControls(); this.setStatus("Dispatching governed turn…", "active"); @@ -253,16 +465,24 @@ method: "POST", body: JSON.stringify({ turn_id: turnId, text, attachments }), }); - this.elements.input.value = ""; + this.submissionPending = false; + this.activeTurnId = turnId; + if (this.draftRevision === submittedRevision && this.elements.input.value === submittedValue) { + this.elements.input.value = ""; + this.draftRevision += 1; + this.persistDraft(); + } this.elements.attachments.value = ""; this.pendingFiles = []; this.renderPendingFiles(); this.setStatus("Running · Stop terminates the owned provider process.", "active"); this.elements.stop.focus(); } catch (error) { + this.submissionPending = false; this.activeTurnId = null; this.updateControls(); - this.setStatus(`Turn refused: ${error.message || error}`, "error"); + this.persistDraft(); + this.setStatus(`Turn refused: ${error.message || error}. Your draft is preserved.`, "error"); this.elements.input.focus(); } } @@ -288,6 +508,7 @@ const identity = String(message?.message_id || `${message?.sequence || "pending"}:${message?.role || "system"}`); if (this.renderedMessages.has(identity)) return; this.renderedMessages.add(identity); + byId("chat-empty")?.remove?.(); renderMessage(this.elements.transcript, message); this.elements.transcript.scrollTop = this.elements.transcript.scrollHeight; if (announce) { @@ -318,13 +539,16 @@ } const wasActive = Boolean(this.activeTurnId); const serverActive = snapshot?.active_turn_id || null; - this.activeTurnId = serverActive; + if (!this.submissionPending) this.activeTurnId = serverActive; this.updateControls(); if (!this.runtimeAvailable) this.setStatus(`Chat unavailable · ${snapshot?.finding || "runtime not enabled"}.`, "error"); else if (serverActive) this.setStatus("Running · live state restored.", "active"); else if (snapshot?.status === "cancellation_uncertain") this.setStatus("Cancellation uncertain · recovery required.", "error"); else this.setStatus("Ready", "ready"); - if (wasActive && !serverActive && this.runtimeAvailable) this.elements.input.focus(); + if (wasActive && !serverActive && !this.submissionPending && this.runtimeAvailable) { + this.elements.input.focus(); + void this.refreshWorkspace(); + } } applyEvent(event) { @@ -358,12 +582,39 @@ status === "cancellation_uncertain" ? "Cancellation uncertain · recovery required." : status.replaceAll("_", " "), status === "failed" || status === "cancellation_uncertain" ? "error" : "ready", ); + void this.refreshWorkspace(); } this.updateControls(); if (TERMINAL_STATES.has(status) && this.runtimeAvailable) this.elements.input.focus(); return true; } + async refreshWorkspace(manual = false) { + try { + const metadata = await this.request("/api/v1/workspace"); + this.renderWorkspace(metadata); + if (metadata?.capabilities?.chat_stream_available) { + await this.refresh(); + if (manual && metadata?.capabilities?.can_discuss_run) { + this.setStatus("Workspace checked. Discussion is ready.", "ready"); + } + } else { + this.runtimeAvailable = false; + this.updateControls(); + this.setStatus(metadata?.guidance?.message || "Discussion is unavailable. Your draft is preserved.", "error"); + this.stream?.close(); + this.stream = null; + this.endPolling(); + } + return metadata; + } catch (_error) { + this.runtimeAvailable = false; + this.updateControls(); + this.setStatus("Workspace is disconnected. Your draft is preserved; use Check again to reconnect.", "error"); + return null; + } + } + async refresh() { try { this.applySnapshot(await this.request("/api/v1/chat")); @@ -375,6 +626,7 @@ } beginPolling() { + if (!this.workspace?.capabilities?.chat_stream_available) return; if (this.pollTimer) return; const poll = async () => { await this.refresh(); @@ -389,6 +641,7 @@ } connectEvents() { + if (!this.workspace?.capabilities?.chat_stream_available) return; if (!("EventSource" in global)) { this.beginPolling(); return; @@ -420,8 +673,8 @@ if (!this.completeDom() || this.running) return false; this.running = true; this.bind(); - await this.refresh(); - this.connectEvents(); + const metadata = await this.refreshWorkspace(); + if (metadata?.capabilities?.chat_stream_available) this.connectEvents(); return true; } diff --git a/src/torq_cli/data/fleet/index.html b/src/torq_cli/data/fleet/index.html index 6489aa9..f25eac9 100644 --- a/src/torq_cli/data/fleet/index.html +++ b/src/torq_cli/data/fleet/index.html @@ -4,22 +4,29 @@ - TORQ Fleet + TORQ Workspace + + - +

-
+
- TORQGOVERNED FLEET + TORQLOCAL GOVERNED WORKSPACE
+
+ + + +
@@ -127,17 +229,26 @@
-
+
+ +
+
DraftWhat would you like to understand?
+ Held in this tab +
- +
- - -

Text, PNG, JPEG, GIF, WebP or PDF · up to 6 files · 5 MB each · Ctrl+Enter to send

+
+ + + +
+

Your draft stays in this browser tab. Ctrl or Cmd+Enter sends when discussion is available.

Connecting to governed runtime... +
diff --git a/src/torq_cli/data/fleet/task.css b/src/torq_cli/data/fleet/task.css new file mode 100644 index 0000000..b80a490 --- /dev/null +++ b/src/torq_cli/data/fleet/task.css @@ -0,0 +1,39 @@ +.task-view { max-width: 1180px; margin: 0 auto; padding: 42px 24px 140px; } +.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; } +.task-grid { display: grid; grid-template-columns: minmax(0, 1.45fr) minmax(280px, .85fr); gap: 16px; align-items: start; } +.task-card { border: 1px solid var(--line); background: var(--panel); border-radius: 18px; padding: 22px; box-shadow: var(--shadow); min-width: 0; } +.task-card h2 { margin: 7px 0 16px; font-size: 1.15rem; } +.task-editor { grid-row: span 2; display: grid; gap: 10px; } +.task-step { color: var(--accent); font: 700 .72rem/1.2 var(--mono); letter-spacing: .08em; text-transform: uppercase; } +.task-editor > label, .task-two-col label { color: var(--muted); font-size: .82rem; font-weight: 700; display: grid; gap: 7px; } +.task-editor select, .task-editor textarea { width: 100%; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--surface); color: var(--text); padding: 11px 12px; font: inherit; resize: vertical; box-sizing: border-box; } +.task-editor textarea:focus, .task-editor select:focus { outline: 3px solid color-mix(in srgb, var(--accent) 28%, transparent); border-color: var(--accent); } +.task-two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } +.task-hint, .task-status, .task-empty { color: var(--muted); font-size: .84rem; line-height: 1.5; } +.task-actions { display: flex; justify-content: space-between; gap: 10px; margin-top: 4px; } +.task-plan dl, .task-current-list { display: grid; gap: 9px; margin: 0 0 18px; } +.task-plan dl div { display: flex; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--line); padding-bottom: 8px; } +.task-plan dt { color: var(--muted); } +.task-plan dd { margin: 0; text-align: right; overflow-wrap: anywhere; } +.task-file-list { margin: 10px 0 18px; padding-left: 20px; font-family: var(--mono); font-size: .78rem; } +.task-state { display: inline-flex; border-radius: 999px; padding: 5px 9px; background: color-mix(in srgb, var(--accent) 12%, var(--surface)); color: var(--accent); font: 700 .72rem var(--mono); text-transform: uppercase; } +.task-result { margin-top: 14px; padding: 12px; border-radius: 10px; background: color-mix(in srgb, var(--ok) 10%, var(--surface)); line-height: 1.5; } +.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; } +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; } +@media (max-width: 760px) { + .task-view { padding: 26px 12px 80px; } + .task-grid, .task-two-col { grid-template-columns: 1fr; } + .task-editor { grid-row: auto; } + .task-history { grid-column: auto; } + .task-card { padding: 16px; border-radius: 14px; } + .task-actions { align-items: stretch; flex-direction: column-reverse; } +} diff --git a/src/torq_cli/data/fleet/task.js b/src/torq_cli/data/fleet/task.js new file mode 100644 index 0000000..066167a --- /dev/null +++ b/src/torq_cli/data/fleet/task.js @@ -0,0 +1,268 @@ +(() => { + "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; + 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; }); +})(); diff --git a/src/torq_cli/domain/run_evidence.py b/src/torq_cli/domain/run_evidence.py index f26802a..6953402 100644 --- a/src/torq_cli/domain/run_evidence.py +++ b/src/torq_cli/domain/run_evidence.py @@ -13,6 +13,10 @@ plan_hash, revision_body, ) +from torq_cli.domain.task_evidence import ( + validate_task_audit_payload, + validate_task_receipt_contract, +) ATTEMPT_TRANSITIONS = frozenset( { @@ -395,6 +399,10 @@ def validate_receipt_payload( # floor catches the rest, including the writer-only lifecycle transitions. if not legacy and _oversized_value(dict(payload)): return "receipt_value_oversized" + if transition == "audit": + task_finding = validate_task_audit_payload(payload) + if task_finding is not None: + return task_finding if transition in ATTEMPT_TRANSITIONS: if not isinstance(payload.get("role"), str): return "attempt_role_invalid" @@ -799,6 +807,9 @@ def validate_v2_receipt_contract( legacy: bool = False, ) -> str | None: """Validate cross-receipt lifecycle invariants after crypto verification.""" + task_finding = validate_task_receipt_contract(receipts, sealed=sealed) + if task_finding is not None: + return task_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_evidence.py b/src/torq_cli/domain/task_evidence.py new file mode 100644 index 0000000..5e3ac9b --- /dev/null +++ b/src/torq_cli/domain/task_evidence.py @@ -0,0 +1,376 @@ +"""Closed semantic contract for bounded goal-to-candidate task evidence.""" + +from __future__ import annotations + +import re +from collections.abc import Mapping, Sequence +from typing import Any + +TASK_CONTRACT = "torq-candidate-task-v1" +TASK_EVENTS = frozenset( + { + "task_start_accepted", + "candidate_generated", + "candidate_check_completed", + "candidate_ready", + "task_failed", + "task_interrupted", + "task_cancelled", + } +) +TERMINAL_TASK_EVENTS = frozenset( + {"candidate_ready", "task_failed", "task_interrupted", "task_cancelled"} +) + +_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}") +_SHA256 = re.compile(r"sha256:[0-9a-f]{64}") +_ARTIFACT = re.compile(r"[A-Za-z0-9][A-Za-z0-9/\\._-]{0,255}") +_PHASES = frozenset({"reserved", "preparing", "generating", "checking"}) +_TERMINATIONS = frozenset({"not_started", "confirmed_empty", "unknown"}) + +_COMMON = frozenset({"task_contract", "event", "task_id", "provider_dispatch"}) +_EVENT_KEYS: Mapping[str, frozenset[str]] = { + "task_start_accepted": _COMMON + | frozenset( + { + "request_digest", + "plan_hash", + "base_manifest_hash", + "input_hash", + "artifact", + "artifact_hash", + "artifact_content_hash", + "provider", + "model", + } + ), + "candidate_generated": _COMMON + | frozenset( + { + "start_sequence", + "plan_hash", + "input_hash", + "candidate_manifest_hash", + "raw_response_hash", + "artifact", + "artifact_hash", + "artifact_content_hash", + "provider", + "model", + "termination", + } + ), + "candidate_check_completed": _COMMON + | frozenset( + { + "generated_sequence", + "candidate_manifest_hash", + "check_profile_id", + "check_profile_version", + "helper_hash", + "argv_hash", + "exit_code", + "output_hash", + "output_complete", + "termination", + "artifact", + "artifact_hash", + "artifact_content_hash", + } + ), + "candidate_ready": _COMMON + | frozenset( + { + "start_sequence", + "generated_sequence", + "check_sequence", + "plan_hash", + "base_manifest_hash", + "input_hash", + "candidate_manifest_hash", + "source_recheck_hash", + } + ), + "task_failed": _COMMON + | frozenset({"phase", "reason_code", "caused_by_sequence", "termination"}), + "task_interrupted": _COMMON + | frozenset({"phase", "reason_code", "caused_by_sequence", "termination"}), + "task_cancelled": _COMMON + | frozenset({"phase", "reason_code", "caused_by_sequence", "termination"}), +} + + +def _digest(value: object) -> bool: + return isinstance(value, str) and _SHA256.fullmatch(value) is not None + + +def _identifier(value: object) -> bool: + return isinstance(value, str) and _ID.fullmatch(value) is not None + + +def _artifact(value: object) -> bool: + return ( + isinstance(value, str) + and _ARTIFACT.fullmatch(value) is not None + and ".." not in value.replace("\\", "/").split("/") + ) + + +def _positive_sequence(value: object) -> bool: + return isinstance(value, int) and not isinstance(value, bool) and value > 0 + + +def validate_task_audit_payload(payload: Mapping[str, Any]) -> str | None: + """Validate one discriminated audit body without upgrading generic audit.""" + + if payload.get("task_contract") != TASK_CONTRACT: + return None + event = payload.get("event") + if not isinstance(event, str) or event not in TASK_EVENTS: + return "task_event_invalid" + if set(payload) != _EVENT_KEYS[event]: + return "task_payload_keys_invalid" + if not _identifier(payload.get("task_id")): + return "task_id_invalid" + if not isinstance(payload.get("provider_dispatch"), bool): + return "task_provider_dispatch_invalid" + + if event == "task_start_accepted": + if payload["provider_dispatch"] is not False: + return "task_provider_dispatch_invalid" + if not all( + _digest(payload.get(field)) + for field in ( + "request_digest", + "plan_hash", + "base_manifest_hash", + "input_hash", + "artifact_hash", + "artifact_content_hash", + ) + ): + return "task_hash_invalid" + if not _artifact(payload.get("artifact")): + return "task_artifact_invalid" + if not _identifier(payload.get("provider")) or not _identifier(payload.get("model")): + return "task_provider_invalid" + elif event == "candidate_generated": + if payload["provider_dispatch"] is not True: + return "task_provider_dispatch_invalid" + if not _positive_sequence(payload.get("start_sequence")): + return "task_sequence_link_invalid" + if not all( + _digest(payload.get(field)) + for field in ( + "plan_hash", + "input_hash", + "candidate_manifest_hash", + "raw_response_hash", + "artifact_hash", + "artifact_content_hash", + ) + ): + return "task_hash_invalid" + if not _artifact(payload.get("artifact")): + return "task_artifact_invalid" + if not _identifier(payload.get("provider")) or not _identifier(payload.get("model")): + return "task_provider_invalid" + if payload.get("termination") != "confirmed_empty": + return "task_termination_invalid" + elif event == "candidate_check_completed": + if payload["provider_dispatch"] is not False: + return "task_provider_dispatch_invalid" + if not _positive_sequence(payload.get("generated_sequence")): + return "task_sequence_link_invalid" + if not all( + _digest(payload.get(field)) + for field in ( + "candidate_manifest_hash", + "helper_hash", + "argv_hash", + "output_hash", + "artifact_hash", + "artifact_content_hash", + ) + ): + return "task_hash_invalid" + if not _artifact(payload.get("artifact")): + return "task_artifact_invalid" + if payload.get("check_profile_id") != "structural-v1": + return "task_check_profile_invalid" + if payload.get("check_profile_version") != "1.0.0": + return "task_check_profile_invalid" + exit_code = payload.get("exit_code") + if not isinstance(exit_code, int) or isinstance(exit_code, bool): + return "task_check_exit_invalid" + if not isinstance(payload.get("output_complete"), bool): + return "task_check_output_invalid" + if payload.get("termination") != "confirmed_empty": + return "task_termination_invalid" + elif event == "candidate_ready": + if payload["provider_dispatch"] is not False: + return "task_provider_dispatch_invalid" + if not all( + _positive_sequence(payload.get(field)) + for field in ("start_sequence", "generated_sequence", "check_sequence") + ): + return "task_sequence_link_invalid" + if not all( + _digest(payload.get(field)) + for field in ( + "plan_hash", + "base_manifest_hash", + "input_hash", + "candidate_manifest_hash", + "source_recheck_hash", + ) + ): + return "task_hash_invalid" + else: + if payload.get("phase") not in _PHASES: + return "task_phase_invalid" + reason = payload.get("reason_code") + if not isinstance(reason, str) or _CODE.fullmatch(reason) is None: + return "task_reason_invalid" + caused = payload.get("caused_by_sequence") + if caused is not None and not _positive_sequence(caused): + return "task_sequence_link_invalid" + termination = payload.get("termination") + if termination not in _TERMINATIONS: + return "task_termination_invalid" + if event == "task_cancelled" and not ( + termination == "confirmed_empty" + or termination == "not_started" and payload["provider_dispatch"] is False + ): + return "task_cancel_termination_invalid" + return None + + +def validate_task_receipt_contract( + receipts: Sequence[Mapping[str, Any]], *, sealed: bool +) -> str | None: + """Validate the ordered inner task state machine across signed receipts.""" + + task_rows: list[tuple[int, Mapping[str, Any]]] = [] + terminal_sequence: int | None = None + for receipt in receipts: + payload = receipt.get("payload") + sequence = receipt.get("sequence") + if terminal_sequence is not None: + return "task_receipt_after_terminal" + if not isinstance(payload, Mapping) or payload.get("task_contract") != TASK_CONTRACT: + continue + if receipt.get("transition") != "audit": + return "task_transition_invalid" + if receipt.get("run_id") != payload.get("task_id"): + return "task_run_id_mismatch" + if not _positive_sequence(sequence): + return "task_sequence_link_invalid" + finding = validate_task_audit_payload(payload) + if finding is not None: + return finding + assert isinstance(sequence, int) and not isinstance(sequence, bool) + task_rows.append((sequence, payload)) + if payload.get("event") in TERMINAL_TASK_EVENTS: + terminal_sequence = sequence + + if not task_rows: + return None + task_id = task_rows[0][1].get("task_id") + if any(payload.get("task_id") != task_id for _, payload in task_rows): + return "task_id_mismatch" + events = [str(payload["event"]) for _, payload in task_rows] + if len(task_rows) == 1 and events[0] in { + "task_failed", + "task_interrupted", + "task_cancelled", + }: + early_terminal = task_rows[0][1] + if ( + early_terminal.get("caused_by_sequence") is not None + or early_terminal.get("phase") != "reserved" + or early_terminal.get("provider_dispatch") is not False + or early_terminal.get("termination") != "not_started" + ): + return "task_terminal_link_invalid" + if sealed is False: + return None + return None + if events[0] != "task_start_accepted" or events.count("task_start_accepted") != 1: + return "task_start_order_invalid" + if sum(event in TERMINAL_TASK_EVENTS for event in events) > 1: + return "task_terminal_duplicate" + + start_sequence, start = task_rows[0] + generated_row = next( + ((sequence, body) for sequence, body in task_rows if body["event"] == "candidate_generated"), + None, + ) + check_row = next( + ( + (sequence, body) + for sequence, body in task_rows + if body["event"] == "candidate_check_completed" + ), + None, + ) + if events.count("candidate_generated") > 1 or events.count("candidate_check_completed") > 1: + return "task_event_duplicate" + if generated_row is not None: + generated_sequence, generated = generated_row + if ( + generated_sequence <= start_sequence + or generated.get("start_sequence") != start_sequence + or generated.get("plan_hash") != start.get("plan_hash") + or generated.get("input_hash") != start.get("input_hash") + or generated.get("provider") != start.get("provider") + or generated.get("model") != start.get("model") + ): + return "task_generated_link_invalid" + if check_row is not None: + check_sequence, check = check_row + if ( + generated_row is None + or check_sequence <= generated_row[0] + or check.get("generated_sequence") != generated_row[0] + or check.get("candidate_manifest_hash") + != generated_row[1].get("candidate_manifest_hash") + ): + return "task_check_link_invalid" + + terminal = task_rows[-1][1] if task_rows[-1][1]["event"] in TERMINAL_TASK_EVENTS else None + if terminal is not None and terminal["event"] == "candidate_ready": + if generated_row is None or check_row is None: + return "task_ready_prerequisite_missing" + if ( + check_row[1].get("exit_code") != 0 + or check_row[1].get("output_complete") is not True + or check_row[1].get("termination") != "confirmed_empty" + or terminal.get("start_sequence") != start_sequence + or terminal.get("generated_sequence") != generated_row[0] + or terminal.get("check_sequence") != check_row[0] + or terminal.get("plan_hash") != start.get("plan_hash") + or terminal.get("base_manifest_hash") != start.get("base_manifest_hash") + or terminal.get("input_hash") != start.get("input_hash") + or terminal.get("candidate_manifest_hash") + != generated_row[1].get("candidate_manifest_hash") + or terminal.get("source_recheck_hash") != start.get("base_manifest_hash") + ): + return "task_ready_link_invalid" + if terminal is not None and terminal["event"] != "candidate_ready": + preceding = task_rows[-2][0] if len(task_rows) > 1 else None + if terminal.get("caused_by_sequence") != preceding: + return "task_terminal_link_invalid" + if sealed and terminal is None: + return "task_terminal_missing" + return None + + +__all__ = [ + "TASK_CONTRACT", + "TASK_EVENTS", + "TERMINAL_TASK_EVENTS", + "validate_task_audit_payload", + "validate_task_receipt_contract", +] diff --git a/src/torq_cli/interfaces/cli.py b/src/torq_cli/interfaces/cli.py index 4c2a116..cd8e250 100644 --- a/src/torq_cli/interfaces/cli.py +++ b/src/torq_cli/interfaces/cli.py @@ -5,7 +5,9 @@ import argparse import getpass import json +import shutil import sys +import tempfile from pathlib import Path from typing import Any from collections.abc import Mapping, Sequence @@ -14,10 +16,13 @@ from torq_cli import __version__ from torq_cli.adapters.chat_provider import ChatProviderCommandFactory, current_environment +from torq_cli.adapters.candidate_provider import CandidateProviderCommandFactory from torq_cli.adapters.linux_containment import linux_containment_capability from torq_cli.application import import_v5_config, import_v5_console 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.workspace import classify_workspace_root from torq_cli.application.fleet import FleetProjector from torq_cli.application.live_runtime import build_live_runtime from torq_cli.application.resolve import envelope_to_dict, resolve_path @@ -42,6 +47,8 @@ from torq_cli.safety.chat_evidence import ChatEvidenceJournal, verify_chat_evidence from torq_cli.safety.production_trust import evaluate_production_trust from torq_cli.safety.receipts import FileRunKeyStore, verify_receipt_store +from torq_cli.safety.receipts import restrict_owner_only_directory +from torq_cli.safety.task_workspace import validate_disjoint_roots def exit_code_for(status: str, require_effective: bool, findings: Sequence[object]) -> int: @@ -147,7 +154,7 @@ def _parser() -> argparse.ArgumentParser: verify.add_argument("--run-root", required=True) verify.add_argument("--trusted-public-key") fleet = sub.add_parser("fleet") - fleet.add_argument("--run-root", required=True) + fleet.add_argument("--run-root") fleet.add_argument("--trusted-public-key") fleet.add_argument("--serve", action="store_true") fleet.add_argument("--host", default="127.0.0.1") @@ -159,6 +166,12 @@ def _parser() -> argparse.ArgumentParser: fleet.add_argument("--chat-model") fleet.add_argument("--credential-file") fleet.add_argument("--claude-bin", default="claude") + fleet.add_argument("--task-project", action="append", default=[], metavar="ID=PATH") + fleet.add_argument("--task-state-root") + fleet.add_argument("--task-work-root") + fleet.add_argument("--task-provider", choices=("claude", "deepseek", "kimi", "qwen", "zai")) + fleet.add_argument("--task-model") + fleet.add_argument("--task-claude-bin") demo = sub.add_parser( "demo", help="Scaffold a zero-config dry-run demo (no providers contacted)", @@ -371,15 +384,34 @@ def main(argv: Sequence[str] | None = None) -> int: ) return 3 if args.command == "fleet": + if args.run_root is None and not args.task_project: + print(json.dumps({"status": "blocked", "finding": "fleet_run_root_required"}, sort_keys=True)) + return 3 + environment = current_environment() + app_base = environment.get("LOCALAPPDATA") or environment.get("XDG_STATE_HOME") + if app_base is None: + home = environment.get("HOME") or environment.get("USERPROFILE") + if home is None: + print(json.dumps({"status": "blocked", "finding": "task_state_root_required"}, sort_keys=True)) + return 3 + app_base = str(Path(home) / ".local" / "state") + task_parent = Path(app_base) / "TorqCLI" + task_state_root = Path(args.task_state_root) if args.task_state_root else task_parent / "candidate-state" + task_work_root = Path(args.task_work_root) if args.task_work_root else task_parent / "candidate-work" + selected_run_root = Path(args.run_root) if args.run_root is not None else task_parent / "no-run-selected" projector = FleetProjector( - Path(args.run_root), + selected_run_root, trusted_public_key=trusted_public_key, ) if args.serve: + task_service = None + task_runtime_root = None try: chat_controller = None chat_snapshot_provider = None if args.chat_provider is not None: + if args.run_root is None: + raise ValueError("chat_run_root_required") if args.chat_model is None: raise ValueError("chat_model_required") if sys.platform.startswith("linux"): @@ -388,6 +420,19 @@ def main(argv: Sequence[str] | None = None) -> int: raise ValueError(capability.reason) elif sys.platform != "win32": raise ValueError("chat_strong_containment_unavailable") + selected_root = selected_run_root + workspace_root = classify_workspace_root(selected_root) + if workspace_root["root_kind"] != "individual_run": + finding = str(workspace_root["reason_code"]) + if workspace_root["root_kind"] == "collection": + finding += ":" + ",".join(workspace_root["runs"]) + raise ValueError(finding) + workspace_root = classify_workspace_root( + selected_root, + projector.snapshot(), + ) + if workspace_root["trusted"] is not True: + raise ValueError(str(workspace_root["reason_code"])) vault = None if args.chat_provider != "claude": if args.credential_file is None: @@ -442,14 +487,71 @@ def chat_snapshot_provider() -> Mapping[str, Any]: verification_finding=str(exc), ) + if args.task_project: + if not all( + isinstance(value, str) and value + for value in ( + args.task_provider, + args.task_model, + ) + ): + raise ValueError("task_launch_configuration_required") + projects = [] + for specification in args.task_project: + project_id, separator, raw_path = specification.partition("=") + if not separator or not project_id or not Path(raw_path).is_absolute(): + raise ValueError("task_project_configuration_invalid") + projects.append(TaskProject(project_id, project_id, Path(raw_path))) + validate_disjoint_roots( + [*(project.root for project in projects), task_state_root, task_work_root] + ) + task_vault = None + if args.task_provider != "claude": + if args.credential_file is None: + raise ValueError("task_credential_source_required") + task_vault = ExplicitEnvVault(Path(args.credential_file).resolve()) + task_runtime_root = Path(tempfile.mkdtemp(prefix="torq-task-provider-")) + restrict_owner_only_directory(task_runtime_root) + claude_binary = None + if args.task_provider == "claude": + if args.task_claude_bin is not None: + claude_binary = Path(args.task_claude_bin) + else: + home = current_environment().get("USERPROFILE") + if not home: + raise ValueError("task_claude_binary_required") + claude_binary = Path(home) / ".local" / "bin" / "claude.exe" + task_factory = CandidateProviderCommandFactory( + provider=args.task_provider, + model=args.task_model, + runtime_root=task_runtime_root, + base_environment=current_environment(), + vault=task_vault, + claude_binary=claude_binary, + ) + task_service = CandidateTaskService( + projects=projects, + state_root=task_state_root, + work_root=task_work_root, + provider_factory=task_factory, + provider=args.task_provider, + model=args.task_model, + ) + server = create_fleet_server( projector, host=args.host, port=args.port, chat_controller=chat_controller, chat_snapshot_provider=chat_snapshot_provider, + workspace_chat_provider=args.chat_provider, + task_service=task_service, ) except (OSError, ValueError) as exc: + if task_service is not None: + task_service.close() + if task_runtime_root is not None: + shutil.rmtree(task_runtime_root, ignore_errors=True) print(json.dumps({"status": "blocked", "finding": str(exc)}, sort_keys=True)) return 3 host, port = server.server_address[:2] @@ -459,7 +561,10 @@ def chat_snapshot_provider() -> Mapping[str, Any]: json.dumps( { "status": "serving", - "url": (f"http://{host_text}:{port}/bootstrap?nonce={bootstrap_nonce}"), + "url": ( + f"http://{host_text}:{port}/bootstrap?nonce={bootstrap_nonce}" + + ("&view=task" if args.task_project else "") + ), }, sort_keys=True, ), @@ -474,7 +579,13 @@ def chat_snapshot_provider() -> Mapping[str, Any]: if chat_controller is not None: chat_controller.shutdown(timeout=5.0) finally: - server.server_close() + try: + if task_service is not None: + task_service.close() + finally: + server.server_close() + if task_runtime_root is not None: + shutil.rmtree(task_runtime_root, ignore_errors=True) return 0 snapshot = projector.snapshot() print(json.dumps(snapshot, sort_keys=True)) diff --git a/src/torq_cli/interfaces/fleet_http.py b/src/torq_cli/interfaces/fleet_http.py index ea0d7b6..31f8c3e 100644 --- a/src/torq_cli/interfaces/fleet_http.py +++ b/src/torq_cli/interfaces/fleet_http.py @@ -27,6 +27,7 @@ from torq_cli.application.fleet import FleetProjector from torq_cli.application.fleet_controls import FleetControlService from torq_cli.application.orchestrator import OrchestrationBlocked +from torq_cli.application.workspace import classify_workspace_root from torq_cli.core.redaction import RedactionBlocked _FLEET_ASSETS = { @@ -35,6 +36,8 @@ "/assets/fleet.js": ("fleet.js", "text/javascript; charset=utf-8"), "/assets/chat.css": ("chat.css", "text/css; charset=utf-8"), "/assets/chat.js": ("chat.js", "text/javascript; charset=utf-8"), + "/assets/task.css": ("task.css", "text/css; charset=utf-8"), + "/assets/task.js": ("task.js", "text/javascript; charset=utf-8"), } @@ -171,6 +174,7 @@ def __init__( self.bootstrap_nonce = secrets.token_urlsafe(32) self._nonce_spent = False self._sessions: dict[str, _Session] = {} + self._read_recovery: dict[str, str] = {} self._lock = RLock() def exchange(self, nonce: str) -> str: @@ -239,6 +243,11 @@ def expires_at(self, session: _Session) -> str: def rotate(self, session: _Session) -> str: with self._lock: self._sessions.pop(session.token, None) + self._read_recovery = { + old: target + for old, target in self._read_recovery.items() + if target != session.token + } now = self._clock() token = secrets.token_urlsafe(48) self._sessions[token] = _Session( @@ -247,8 +256,33 @@ def rotate(self, session: _Session) -> str: now, read_only=session.read_only, ) + self._read_recovery[session.token] = token return token + def recover_rotated_session(self, cookie_header: str | None) -> tuple[_Session, str] | None: + """Resolve a prior token only for the handler's idempotent task replay path.""" + if not cookie_header: + return None + cookie = SimpleCookie() + try: + cookie.load(cookie_header) + except ValueError: + return None + morsel = cookie.get("torq_fleet_session") + if morsel is None: + return None + with self._lock: + current = self._read_recovery.get(morsel.value) + session = self._sessions.get(current or "") + if session is None: + return None + now = self._clock() + if now - session.last_seen >= self._idle_seconds or now - session.issued_at >= self._absolute_seconds: + self._read_recovery.pop(morsel.value, None) + return None + session.last_seen = now + return session, session.token + def claim_mutation(self, cookie_header: str | None) -> _Session | None: """Atomically consume a write session so concurrent POSTs cannot fork it.""" if not cookie_header: @@ -298,6 +332,19 @@ def _reject_json_constant(value: str) -> object: raise ValueError("context_request_non_finite") +class TaskHTTPService(Protocol): + def capabilities(self) -> dict[str, Any]: ... + def draft(self, project_id: str) -> dict[str, Any] | None: ... + def save_draft(self, project_id: str, *, goal: str, input_paths: list[str], output_paths: list[str], expected_revision: int) -> dict[str, Any]: ... + def delete_draft(self, project_id: str, *, expected_revision: int) -> None: ... + def review_plan(self, *, project_id: str, draft_revision: int, input_paths: list[str], output_paths: list[str]) -> dict[str, Any]: ... + def start(self, *, request_id: str, plan_hash: str) -> dict[str, Any]: ... + def replay_start(self, *, request_id: str, plan_hash: str) -> dict[str, Any]: ... + def stop(self, task_id: str) -> dict[str, Any]: ... + def task(self, task_id: str) -> dict[str, Any]: ... + def history(self) -> list[dict[str, Any]]: ... + + def create_fleet_server( projector: FleetProjector, *, @@ -311,6 +358,8 @@ def create_fleet_server( operational_state_provider: Callable[[], Mapping[str, Any]] | None = None, chat_controller: ChatController | None = None, chat_snapshot_provider: Callable[[], Mapping[str, Any]] | None = None, + workspace_chat_provider: str | None = None, + task_service: TaskHTTPService | None = None, ) -> ThreadingHTTPServer: if not _loopback_host(host): raise ValueError("fleet_loopback_required") @@ -439,6 +488,139 @@ def fleet_envelope(session: _Session) -> dict[str, Any]: read_only_reason=("session_read_only" if session.read_only else None), ) + def workspace_metadata(session: _Session) -> dict[str, Any]: + root = classify_workspace_root(projector.run_root) + if root["root_kind"] == "individual_run": + envelope = fleet_envelope(session) + snapshot = envelope["snapshot"] + root = classify_workspace_root(projector.run_root, snapshot) + write_capable = bool(envelope["session"].get("write_capable")) + else: + snapshot = {} + write_capable = not session.read_only + chat = chat_snapshot() + runtime_present = chat_controller is not None and chat_snapshot_provider is not None + chat_available = runtime_present and chat.get("data_status") == "available" + active_turn_id = chat.get("active_turn_id") + active = isinstance(active_turn_id, str) and bool(active_turn_id) + configured_provider = workspace_chat_provider.casefold() if workspace_chat_provider else None + supported_provider = configured_provider in {"claude", "deepseek", "kimi", "qwen", "zai"} + provider = configured_provider if supported_provider else None + attachment_types = ( + [] + if provider in {None, "claude"} + else [ + "application/json", + "application/pdf", + "image/gif", + "image/jpeg", + "image/png", + "image/webp", + "text/markdown", + "text/plain", + ] + ) + root_ready = root["root_kind"] == "individual_run" and root["trusted"] is True + can_discuss = bool(root_ready and provider and chat_available and write_capable and not active) + can_cancel = bool(root_ready and runtime_present and write_capable and active) + if not root_ready: + reason_code = root["reason_code"] + message = root["message"] + remediation = root["remediation"] + elif provider is None: + reason_code = "workspace_chat_provider_missing" + message = "Discussion is not enabled for this session." + remediation = "Relaunch with --chat-provider and --chat-model to discuss this run." + elif not write_capable: + run = snapshot.get("run") if isinstance(snapshot, Mapping) else None + closed = isinstance(run, Mapping) and run.get("workflow_state") in {"closed", "abandoned"} + reason_code = "workspace_run_closed" if closed else "fleet_session_read_only" + message = ( + "This completed run is available for review." + if closed + else "This session is open read-only." + ) + remediation = ( + "Use Fleet to inspect its verified evidence. Discussion cannot be added to a closed run." + if closed + else "Relaunch this individual run to obtain a new session." + ) + elif not chat_available: + reason_code = "chat_runtime_unavailable" + message = "Discussion history is not available." + remediation = "Inspect Details, then relaunch the configured individual run." + elif active: + reason_code = "chat_turn_active" + message = "TORQ is responding. You can write the next draft now." + remediation = "Send the draft manually after this response finishes, or stop the active turn." + else: + reason_code = None + message = "Ask about this verified run." + remediation = None + return { + "schema": "torq-workspace-v1", + "workspace_id": root["workspace_id"], + "root": { + "kind": root["root_kind"], + "trusted": root["trusted"], + "verification_state": root["verification_state"], + "run_mode": root["run_mode"], + }, + "selected_run_id": root["selected_run_id"], + "runs": root["runs"], + "provider": { + "name": provider, + "configuration": ( + "configured" + if provider + else "unsupported" + if configured_provider + else "not_configured" + ), + "authentication": "not_checked", + }, + "capabilities": { + "can_discuss_run": can_discuss, + "can_cancel": can_cancel, + "can_start_task": False, + "execution_supported": False, + "chat_stream_available": bool(runtime_present and chat_available), + "draft_storage": "browser_session", + "attachment_types": attachment_types, + "limits": { + "attachments": 0 if not attachment_types else 6, + "attachment_bytes": 0 if not attachment_types else 5 * 1024 * 1024, + }, + }, + "active_turn_id": active_turn_id if active else None, + "guidance": { + "reason_code": reason_code, + "message": message, + "remediation": remediation, + "consequence": "Drafts are never sent automatically.", + }, + } + + def preflight_chat_submit(session: _Session) -> None: + root = classify_workspace_root(projector.run_root) + if root["root_kind"] != "individual_run": + raise ValueError(str(root["reason_code"])) + snapshot = projector.snapshot() + root = classify_workspace_root(projector.run_root, snapshot) + if root["trusted"] is not True: + raise ValueError("workspace_run_untrusted") + run = snapshot.get("run") + if isinstance(run, Mapping) and run.get("workflow_state") in {"closed", "abandoned"}: + session_manager.downgrade(session) + if session.read_only: + raise ValueError("fleet_session_read_only") + chat = chat_snapshot() + if chat.get("data_status") != "available": + raise ValueError("chat_runtime_unavailable") + active_turn_id = chat.get("active_turn_id") + if isinstance(active_turn_id, str) and active_turn_id: + raise ValueError("chat_turn_active") + class Handler(BaseHTTPRequestHandler): server_version = "TORQFleet/1" @@ -466,7 +648,9 @@ def do_GET(self) -> None: # noqa: N802 self._json(403, {"status": "blocked", "finding": str(exc)}) return self.send_response(303) - self.send_header("Location", "/") + requested_view = values.get("view", []) + location = "/?view=task" if requested_view == ["task"] else "/" + self.send_header("Location", location) self.send_header( "Set-Cookie", "torq_fleet_session=" + token + "; HttpOnly; SameSite=Strict; Path=/", @@ -488,6 +672,35 @@ def do_GET(self) -> None: # noqa: N802 if parsed.path == "/api/v1/fleet": self._json(200, fleet_envelope(session)) return + if parsed.path == "/api/v1/workspace": + self._json(200, workspace_metadata(session)) + return + if parsed.path == "/api/v1/tasks/capabilities" and task_service is not None: + try: + self._json(200, task_service.capabilities()) + except (OSError, ValueError): + self._json(409, {"status": "blocked", "finding": "task_state_unavailable"}) + return + if parsed.path == "/api/v1/tasks" and task_service is not None: + try: + self._json(200, {"schema": "torq-task-history-v1", "tasks": task_service.history()}) + except (OSError, ValueError): + self._json(409, {"status": "blocked", "finding": "task_state_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: + self._json(200, {"draft": task_service.draft(draft_match.group(1))}) + except ValueError: + self._json(404, {"status": "not_found"}) + return + task_match = re.fullmatch(r"/api/v1/tasks/(run-task-[a-f0-9]{24})", parsed.path) + if task_match is not None and task_service is not None: + try: + self._json(200, {"task": task_service.task(task_match.group(1))}) + except ValueError: + self._json(404, {"status": "not_found"}) + return if parsed.path == "/api/v1/chat": self._json(200, chat_snapshot()) return @@ -643,12 +856,34 @@ def do_POST(self) -> None: # noqa: N802 r"/api/v1/chat/turns/([A-Za-z0-9][A-Za-z0-9:._-]{0,127})/cancel", path, ) + task_draft_match = re.fullmatch( + r"/api/v1/tasks/drafts/([A-Za-z0-9][A-Za-z0-9._-]{0,63})", path + ) + task_draft_delete_match = re.fullmatch( + 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) if path == "/api/v1/chat/turns": operation = "chat_submit" service_present = chat_controller is not None elif chat_cancel_match is not None: operation = "chat_cancel" service_present = chat_controller is not None + elif task_draft_delete_match is not None: + operation = "task_draft_delete" + service_present = task_service is not None + elif task_draft_match is not None: + operation = "task_draft" + service_present = task_service is not None + elif path == "/api/v1/tasks/plans": + operation = "task_plan" + service_present = task_service is not None + elif path == "/api/v1/tasks": + operation = "task_start" + service_present = task_service is not None + elif task_stop_match is not None: + operation = "task_stop" + service_present = task_service is not None elif path in {"/api/v1/context", "/api/v1/fleet/context"}: operation = "context" service_present = context_injector is not None @@ -667,7 +902,13 @@ def do_POST(self) -> None: # noqa: N802 if not service_present: self._json(405, {"status": "read_only"}) return + replay_only = False session = session_manager.claim_mutation(self.headers.get("Cookie")) + if session is None and operation == "task_start": + recovered = session_manager.recover_rotated_session(self.headers.get("Cookie")) + if recovered is not None: + session, _ = recovered + replay_only = True if session is None: self._json(401, {"status": "blocked", "finding": "fleet_session_required"}) return @@ -701,6 +942,15 @@ def do_POST(self) -> None: # noqa: N802 if operation in {"chat_submit", "chat_cancel"}: self._chat_post(operation, chat_cancel_match, session) return + if operation.startswith("task_"): + self._task_post( + operation, + task_draft_delete_match or task_draft_match, + task_stop_match, + session, + replay_only=replay_only, + ) + return snapshot = projector.snapshot() envelope = controls.envelope( snapshot, @@ -901,6 +1151,8 @@ def _chat_post( ) -> None: assert chat_controller is not None try: + if operation == "chat_submit": + preflight_chat_submit(session) payload = self._read_chat_payload() if operation == "chat_cancel": if payload or cancel_match is None: @@ -921,6 +1173,12 @@ def _chat_post( ): raise ValueError("chat_turn_request_invalid") attachments = [cast(Mapping[str, str], item) for item in attachments_value] + if ( + isinstance(workspace_chat_provider, str) + and workspace_chat_provider.casefold() == "claude" + and attachments + ): + raise ValueError("chat_subscription_attachments_unsupported") result = chat_controller.submit( turn_id=turn_id, text=text_value, @@ -964,6 +1222,111 @@ def _read_chat_payload(self) -> Mapping[str, Any]: raise ValueError("chat_request_invalid") return payload + def _read_task_payload(self, *, allow_empty: bool = False) -> Mapping[str, Any]: + content_types = self.headers.get_all("Content-Type", failobj=[]) + if len(content_types) != 1 or content_types[0].casefold() not in { + "application/json", "application/json; charset=utf-8" + }: + raise ValueError("task_content_type_invalid") + if self.headers.get_all("Transfer-Encoding", failobj=[]): + raise ValueError("task_transfer_encoding_denied") + lengths = self.headers.get_all("Content-Length", failobj=[]) + if len(lengths) != 1 or not lengths[0].isdigit(): + raise ValueError("task_size_invalid") + length = int(lengths[0]) + if length > 65_536 or length == 0 and not allow_empty: + raise ValueError("task_size_invalid") + if length == 0: + return {} + payload = json.loads( + self.rfile.read(length), + object_pairs_hook=_unique_json_object, + parse_constant=_reject_json_constant, + ) + if not isinstance(payload, Mapping): + raise ValueError("task_request_invalid") + return payload + + def _task_post( + self, + operation: str, + draft_match: re.Match[str] | None, + stop_match: re.Match[str] | None, + session: _Session, + *, + replay_only: bool, + ) -> None: + assert task_service is not None + try: + payload = self._read_task_payload(allow_empty=operation == "task_stop") + if operation == "task_draft": + if set(payload) != {"goal", "input_paths", "output_paths", "expected_revision"} or draft_match is None: + raise ValueError("task_draft_request_invalid") + goal = payload["goal"] + revision = payload["expected_revision"] + input_paths = payload["input_paths"] + output_paths = payload["output_paths"] + if ( + not isinstance(goal, str) + or not isinstance(revision, int) + or isinstance(revision, bool) + or not isinstance(input_paths, list) + or not isinstance(output_paths, list) + or not all(isinstance(item, str) for item in input_paths + output_paths) + ): + raise ValueError("task_draft_request_invalid") + result: object = task_service.save_draft( + draft_match.group(1), goal=goal, input_paths=input_paths, + output_paths=output_paths, expected_revision=revision, + ) + elif operation == "task_draft_delete": + if set(payload) != {"expected_revision"} or draft_match is None: + raise ValueError("task_draft_delete_request_invalid") + revision = payload["expected_revision"] + if not isinstance(revision, int) or isinstance(revision, bool): + raise ValueError("task_draft_delete_request_invalid") + task_service.delete_draft(draft_match.group(1), expected_revision=revision) + result = {"deleted": True, "revision": revision + 1} + elif operation == "task_plan": + if set(payload) != {"project_id", "draft_revision", "input_paths", "output_paths"}: + raise ValueError("task_plan_request_invalid") + project_id = payload["project_id"] + draft_revision = payload["draft_revision"] + input_paths = payload["input_paths"] + output_paths = payload["output_paths"] + if ( + not isinstance(project_id, str) + or not isinstance(draft_revision, int) + or isinstance(draft_revision, bool) + or not isinstance(input_paths, list) + or not isinstance(output_paths, list) + or not all(isinstance(item, str) for item in input_paths + output_paths) + ): + raise ValueError("task_plan_request_invalid") + result = task_service.review_plan(project_id=project_id, draft_revision=draft_revision, input_paths=input_paths, output_paths=output_paths) + elif operation == "task_start": + if set(payload) != {"request_id", "plan_hash"} or not all(isinstance(payload.get(key), str) for key in ("request_id", "plan_hash")): + raise ValueError("task_start_request_invalid") + method = task_service.replay_start if replay_only else task_service.start + result = method(request_id=payload["request_id"], plan_hash=payload["plan_hash"]) + else: + if payload or stop_match is None: + raise ValueError("task_stop_request_invalid") + result = task_service.stop(stop_match.group(1)) + rotated = session_manager.rotate(session) + self._json(202 if operation in {"task_start", "task_stop"} else 200, {"status": "accepted", "result": result}, session_token=rotated) + except ConnectionError: + return + except (OSError, RuntimeError, ValueError) as exc: + finding = str(exc).split(":", 1)[0] + if not finding.startswith("task_"): + finding = "task_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/receipts.py b/src/torq_cli/safety/receipts.py index a65b5f4..1dc7aba 100644 --- a/src/torq_cli/safety/receipts.py +++ b/src/torq_cli/safety/receipts.py @@ -621,6 +621,16 @@ def restrict_owner_only_directory(path: Path) -> None: _restrict_signing_directory(path, "runtime_directory_permissions_unsafe") +def restrict_owner_only_file(path: Path) -> None: + """Restrict a sensitive non-key file to the current OS identity.""" + _restrict_signing_file(path, "runtime_file_permissions_unsafe") + + +def fsync_directory(path: Path) -> None: + """Flush one directory entry using the receipt store's platform policy.""" + _fsync_directory(path) + + def _restrict_private_key(path: Path) -> None: _restrict_signing_file(path, "receipt_signing_key_permissions_unsafe") @@ -788,7 +798,12 @@ def __init__(self, evidence_root: Path) -> None: @staticmethod def _read_regular_key(path: Path) -> bytes: metadata = path.stat(follow_symlinks=False) - if not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1: + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_nlink != 1 + or path.is_symlink() + or not signing_file_permissions_are_restricted(path) + ): raise ValueError("receipt_signing_key_unsafe") encoded = path.read_bytes().strip() if len(encoded) != 64: @@ -883,6 +898,28 @@ def get_or_create_run_keys(self, run_id: str) -> RunKeys: artifact=self._get_or_create_secret(directory / "artifact.key"), ) + def load_run_keys(self, run_id: str) -> RunKeys: + """Load an existing run identity without creating or chmod-ing anything.""" + if not _valid_run_id(run_id): + raise ValueError("run_id_invalid") + identity = hashlib.sha256(run_id.encode("utf-8")).hexdigest() + directory = self.run_identities_path / identity + metadata = directory.stat(follow_symlinks=False) + if ( + not stat.S_ISDIR(metadata.st_mode) + or directory.is_symlink() + or not signing_file_permissions_are_restricted(directory) + ): + raise ValueError("receipt_run_identity_unsafe") + return RunKeys( + manifest=self._read_regular_key(directory / "manifest.key"), + orchestrator=self._read_regular_key(directory / "orchestrator.key"), + supervisor=self._read_regular_key(directory / "supervisor.key"), + operator_gateway=self._read_regular_key(directory / "operator-gateway.key"), + recovery=self._read_regular_key(directory / "recovery.key"), + artifact=self._read_regular_key(directory / "artifact.key"), + ) + @dataclass(frozen=True) class Verification: @@ -2018,3 +2055,37 @@ def verify_receipt_store( return StoreVerification("tampered", "manifest_signature_invalid") except (OSError, KeyError, ValueError, TypeError, json.JSONDecodeError): return StoreVerification("incomplete", "evidence_unreadable") + + +def read_verified_artifact( + evidence_root: Path, + run_id: str, + artifact_relative: str, +) -> bytes: + """Read one exact artifact only from a sealed, verified existing task store.""" + 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 True: + raise ValueError("artifact_store_not_sealed") + 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) + plain = AESGCM(keys.artifact).decrypt( + payload[offset : offset + 12], + payload[offset + 12 :], + run_id.encode("utf-8"), + ) + return plain diff --git a/src/torq_cli/safety/state_lock.py b/src/torq_cli/safety/state_lock.py new file mode 100644 index 0000000..ffe3245 --- /dev/null +++ b/src/torq_cli/safety/state_lock.py @@ -0,0 +1,68 @@ +"""Kernel-held installation lock for the task state authority.""" + +from __future__ import annotations + +import os +from pathlib import Path +from types import TracebackType + +from torq_cli.safety.receipts import restrict_owner_only_directory, restrict_owner_only_file + + +class InstallationStateLock: + def __init__(self, state_root: Path) -> None: + state_root.mkdir(parents=True, exist_ok=True) + restrict_owner_only_directory(state_root) + self.path = state_root / "task-owner.lock" + self._stream = self.path.open("a+b") + restrict_owner_only_file(self.path) + try: + if os.name == "nt": + import msvcrt + + self._stream.seek(0) + if self._stream.tell() == 0 and self.path.stat().st_size == 0: + self._stream.write(b"\0") + self._stream.flush() + self._stream.seek(0) + msvcrt.locking(self._stream.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl + + flock = getattr(fcntl, "flock") + flock(self._stream.fileno(), getattr(fcntl, "LOCK_EX") | getattr(fcntl, "LOCK_NB")) + except (OSError, BlockingIOError) as exc: + self._stream.close() + raise RuntimeError("task_state_already_owned") from exc + + def close(self) -> None: + if self._stream.closed: + return + try: + if os.name == "nt": + import msvcrt + + self._stream.seek(0) + msvcrt.locking(self._stream.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + + flock = getattr(fcntl, "flock") + flock(self._stream.fileno(), getattr(fcntl, "LOCK_UN")) + finally: + self._stream.close() + + def __enter__(self) -> InstallationStateLock: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + traceback: TracebackType | None, + ) -> None: + del exc_type, exc, traceback + self.close() + + +__all__ = ["InstallationStateLock"] diff --git a/src/torq_cli/safety/task_workspace.py b/src/torq_cli/safety/task_workspace.py new file mode 100644 index 0000000..bdbc076 --- /dev/null +++ b/src/torq_cli/safety/task_workspace.py @@ -0,0 +1,364 @@ +"""Bounded, link-intolerant source snapshots for candidate tasks.""" + +from __future__ import annotations + +import hashlib +import json +import os +import stat +import unicodedata +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path, PurePosixPath + +from torq_cli.core.redaction import PatternRegistry +from torq_cli.domain.hermetic import ( + LegacyConfigTooLarge, + LegacyConfigUnreadable, + ProtectedPathError, + read_bounded_legacy_config, +) +from torq_cli.safety.receipts import restrict_owner_only_directory, restrict_owner_only_file + +MAX_TASK_FILES = 32 +MAX_TASK_FILE_BYTES = 65_536 +MAX_TASK_TOTAL_BYTES = 2_097_152 +SUPPORTED_SUFFIXES = frozenset({".py", ".json", ".md", ".txt"}) +PROTECTED_PARTS = frozenset( + { + ".git", ".hg", ".svn", ".ssh", ".aws", ".azure", ".config", + "keys", "secrets", "evidence", "credentials", "node_modules", "__pycache__", + } +) +_WINDOWS_DEVICES = frozenset( + {"con", "prn", "aux", "nul", *(f"com{i}" for i in range(1, 10)), *(f"lpt{i}" for i in range(1, 10))} +) + + +def canonical_json(value: object) -> str: + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False) + + +def digest_bytes(value: bytes) -> str: + return "sha256:" + hashlib.sha256(value).hexdigest() + + +def digest_json(value: object) -> str: + return digest_bytes(canonical_json(value).encode("utf-8")) + + +def validate_relative_path(value: str) -> str: + if not value or len(value) > 240 or "\\" in value or "\x00" in value: + raise ValueError("task_path_invalid") + normalized = unicodedata.normalize("NFC", value) + if normalized != value: + raise ValueError("task_path_noncanonical") + path = PurePosixPath(value) + if value != path.as_posix() or path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts): + raise ValueError("task_path_invalid") + for part in path.parts: + stem = part.split(".", 1)[0].casefold().rstrip(" .") + folded = part.casefold() + if ":" in part or stem in _WINDOWS_DEVICES or folded in PROTECTED_PARTS or folded.startswith(".env."): + raise ValueError("task_path_protected") + if part.endswith((" ", ".")): + raise ValueError("task_path_invalid") + if path.suffix.casefold() not in SUPPORTED_SUFFIXES: + raise ValueError("task_path_extension_unsupported") + return path.as_posix() + + +def _is_reparse(metadata: os.stat_result) -> bool: + reparse = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)) + return bool(int(getattr(metadata, "st_file_attributes", 0)) & reparse) + + +def _assert_regular_unlinked(path: Path) -> os.stat_result: + metadata = path.stat(follow_symlinks=False) + if not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1 or path.is_symlink() or _is_reparse(metadata): + raise ValueError("task_source_file_unsafe") + if metadata.st_size > MAX_TASK_FILE_BYTES: + raise ValueError("task_source_file_too_large") + return metadata + + +def _assert_no_linked_ancestor(root: Path, path: Path) -> None: + current = path + while True: + metadata = current.stat(follow_symlinks=False) + if stat.S_ISLNK(metadata.st_mode) or current.is_symlink() or _is_reparse(metadata): + raise ValueError("task_source_linked") + if current == root: + return + if root not in current.parents: + raise ValueError("task_path_escape") + current = current.parent + + +def _assert_root_ancestry_safe(path: Path) -> None: + current = path.absolute() + while not os.path.lexists(current): + parent = current.parent + if parent == current: + return + current = parent + while True: + metadata = current.stat(follow_symlinks=False) + if stat.S_ISLNK(metadata.st_mode) or current.is_symlink() or _is_reparse(metadata): + raise ValueError("task_root_linked") + parent = current.parent + if parent == current: + return + current = parent + + +def _read_bounded_regular(path: Path, expected: os.stat_result) -> bytes: + try: + raw = read_bounded_legacy_config(str(path.absolute())) + except LegacyConfigTooLarge as exc: + raise ValueError("task_source_file_too_large") from exc + except (LegacyConfigUnreadable, ProtectedPathError) as exc: + raise ValueError("task_source_file_unsafe") from exc + after = path.stat(follow_symlinks=False) + _assert_root_ancestry_safe(path) + if ( + len(raw) > MAX_TASK_FILE_BYTES + or after.st_size != expected.st_size + or after.st_mtime_ns != expected.st_mtime_ns + or after.st_ino != expected.st_ino + or after.st_dev != expected.st_dev + ): + raise ValueError("task_source_changed") + return raw + + +def snapshot_candidate_exact(candidate_root: Path, expected_paths: Sequence[str]) -> SourceSnapshot: + expected = {validate_relative_path(item) for item in expected_paths} + found: set[str] = set() + allowed_directories = { + PurePosixPath(*PurePosixPath(path).parts[:index]).as_posix() + for path in expected + for index in range(1, len(PurePosixPath(path).parts)) + } + pending: list[tuple[Path, str]] = [(candidate_root, "")] + visited = 0 + while pending: + directory, prefix = pending.pop() + _assert_root_ancestry_safe(directory) + with os.scandir(directory) as entries: + for entry in entries: + visited += 1 + if visited > MAX_TASK_FILES * 4: + raise ValueError("task_candidate_inventory_too_large") + relative = f"{prefix}/{entry.name}".lstrip("/").replace("\\", "/") + metadata = entry.stat(follow_symlinks=False) + if entry.is_symlink() or _is_reparse(metadata): + raise ValueError("task_candidate_inventory_unsafe") + if stat.S_ISDIR(metadata.st_mode): + if relative not in allowed_directories: + raise ValueError("task_candidate_inventory_extra") + pending.append((Path(entry.path), relative)) + elif stat.S_ISREG(metadata.st_mode): + found.add(validate_relative_path(relative)) + else: + raise ValueError("task_candidate_inventory_unsafe") + if found != expected: + raise ValueError("task_candidate_inventory_mismatch") + return snapshot_source(candidate_root, sorted(found)) + + +def validate_disjoint_roots(roots: Sequence[Path]) -> tuple[Path, ...]: + for root in roots: + _assert_root_ancestry_safe(root) + resolved = tuple(root.resolve(strict=False) for root in roots) + folded = [os.path.normcase(str(root)) for root in resolved] + if len(folded) != len(set(folded)): + raise ValueError("task_root_overlap") + for index, left in enumerate(resolved): + for right in resolved[index + 1 :]: + if left in right.parents or right in left.parents: + raise ValueError("task_root_overlap") + return resolved + + +def verify_output_scope( + project_root: Path, + input_paths: Sequence[str], + output_paths: Sequence[str], + *, + expected_absent: Sequence[str] | None = None, +) -> tuple[str, ...]: + inputs = {validate_relative_path(item) for item in input_paths} + outputs = {validate_relative_path(item) for item in output_paths} + absent: list[str] = [] + for relative in sorted(outputs): + target = project_root.joinpath(*PurePosixPath(relative).parts) + if os.path.lexists(target): + if relative not in inputs: + raise ValueError("task_output_context_required") + _assert_no_linked_ancestor(project_root.absolute(), target.absolute()) + _assert_regular_unlinked(target) + else: + current = target.parent + while not os.path.lexists(current): + current = current.parent + _assert_root_ancestry_safe(current) + absent.append(relative) + result = tuple(absent) + if expected_absent is not None and result != tuple(sorted(expected_absent)): + raise ValueError("task_output_scope_changed") + return result + + +@dataclass(frozen=True, slots=True) +class SourceEntry: + path: str + content: str + content_bytes: int + content_hash: str + + +@dataclass(frozen=True, slots=True) +class SourceSnapshot: + entries: tuple[SourceEntry, ...] + manifest_hash: str + + def bundle(self) -> list[dict[str, object]]: + return [ + { + "path": item.path, + "content": item.content, + "content_bytes": item.content_bytes, + "content_hash": item.content_hash, + } + for item in self.entries + ] + + +def snapshot_source(project_root: Path, paths: Sequence[str]) -> SourceSnapshot: + root = project_root.absolute() + if not root.exists() or not root.is_dir(): + raise ValueError("task_project_missing") + _assert_root_ancestry_safe(root) + if len(paths) > MAX_TASK_FILES: + raise ValueError("task_scope_count_invalid") + safe_paths = [validate_relative_path(item) for item in paths] + if len({item.casefold() for item in safe_paths}) != len(safe_paths): + raise ValueError("task_scope_path_collision") + registry = PatternRegistry.default() + entries: list[SourceEntry] = [] + total = 0 + for relative in sorted(safe_paths, key=str.casefold): + target = root.joinpath(*PurePosixPath(relative).parts) + _assert_no_linked_ancestor(root, target) + metadata = _assert_regular_unlinked(target) + raw = _read_bounded_regular(target, metadata) + if len(raw) != metadata.st_size: + raise ValueError("task_source_changed") + try: + content = raw.decode("utf-8") + except UnicodeDecodeError as exc: + raise ValueError("task_source_not_utf8") from exc + scanned, findings = registry.scan(content) + if findings or scanned != content: + raise ValueError("task_source_sensitive") + total += len(raw) + if total > MAX_TASK_TOTAL_BYTES: + raise ValueError("task_scope_too_large") + entries.append(SourceEntry(relative, content, len(raw), digest_bytes(raw))) + manifest = [{"path": row.path, "content_bytes": row.content_bytes, "content_hash": row.content_hash} for row in entries] + return SourceSnapshot(tuple(entries), digest_json(manifest)) + + +def materialize_candidate( + candidate_root: Path, + base: SourceSnapshot, + operations: Sequence[Mapping[str, object]], + *, + allowed_output_paths: Sequence[str], +) -> SourceSnapshot: + if candidate_root.exists(): + raise ValueError("task_candidate_exists") + allowed = {validate_relative_path(item) for item in allowed_output_paths} + base_by_path = {item.path: item for item in base.entries} + if not operations or len(operations) > MAX_TASK_FILES: + raise ValueError("task_operation_count_invalid") + seen: set[str] = set() + final = dict(base_by_path) + registry = PatternRegistry.default() + for operation in operations: + if set(operation) != {"operation", "path", "base_hash", "content"}: + raise ValueError("task_operation_schema_invalid") + path_value = operation["path"] + if not isinstance(path_value, str): + raise ValueError("task_operation_path_invalid") + relative = validate_relative_path(path_value) + folded = relative.casefold() + if folded in seen or relative not in allowed: + raise ValueError("task_operation_path_invalid") + seen.add(folded) + action = operation["operation"] + current = base_by_path.get(relative) + base_hash = operation["base_hash"] + if action == "replace": + if current is None or base_hash != current.content_hash: + raise ValueError("task_operation_base_stale") + elif action == "create": + if current is not None or base_hash is not None: + raise ValueError("task_operation_create_invalid") + else: + raise ValueError("task_operation_unsupported") + content = operation["content"] + if not isinstance(content, str): + raise ValueError("task_operation_content_invalid") + raw = content.encode("utf-8") + if len(raw) > MAX_TASK_FILE_BYTES: + raise ValueError("task_operation_content_too_large") + scanned, findings = registry.scan(content) + if findings or scanned != content: + raise ValueError("task_candidate_sensitive") + hashed = digest_bytes(raw) + if current is not None and hashed == current.content_hash: + raise ValueError("task_operation_unchanged") + final[relative] = SourceEntry(relative, content, len(raw), hashed) + if not seen.issubset({item.casefold() for item in allowed}): + raise ValueError("task_operation_scope_invalid") + if len(final) > MAX_TASK_FILES or sum(row.content_bytes for row in final.values()) > MAX_TASK_TOTAL_BYTES: + raise ValueError("task_candidate_too_large") + candidate_root.mkdir(parents=True, mode=0o700) + restrict_owner_only_directory(candidate_root) + for relative, row in sorted(final.items()): + target = candidate_root.joinpath(*PurePosixPath(relative).parts) + target.parent.mkdir(parents=True, exist_ok=True) + restrict_owner_only_directory(target.parent) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) + descriptor = os.open(target, flags, 0o600) + try: + raw = row.content.encode("utf-8") + if os.write(descriptor, raw) != len(raw): + raise OSError("task_candidate_short_write") + os.fsync(descriptor) + finally: + os.close(descriptor) + restrict_owner_only_file(target) + manifest = [{"path": row.path, "content_bytes": row.content_bytes, "content_hash": row.content_hash} for row in sorted(final.values(), key=lambda item: item.path.casefold())] + return SourceSnapshot(tuple(sorted(final.values(), key=lambda item: item.path.casefold())), digest_json(manifest)) + + +__all__ = [ + "MAX_TASK_FILES", + "MAX_TASK_FILE_BYTES", + "MAX_TASK_TOTAL_BYTES", + "SUPPORTED_SUFFIXES", + "SourceEntry", + "SourceSnapshot", + "canonical_json", + "digest_bytes", + "digest_json", + "materialize_candidate", + "snapshot_source", + "snapshot_candidate_exact", + "validate_disjoint_roots", + "validate_relative_path", + "verify_output_scope", +] diff --git a/tests/fixtures/candidate_provider.py b/tests/fixtures/candidate_provider.py new file mode 100644 index 0000000..edf60d2 --- /dev/null +++ b/tests/fixtures/candidate_provider.py @@ -0,0 +1,25 @@ +import json +import sys + +request = json.loads(sys.stdin.read().rsplit("\n", 1)[-1]) +sources = {entry["path"]: entry for entry in request["input"]["files"]} +path = request["allowed_output_paths"][0] +base = sources.get(path) +print( + json.dumps( + { + "contract": "torq-candidate-output-v1", + "plan_hash": request["plan_hash"], + "input_hash": request["input_hash"], + "operations": [ + { + "operation": "replace" if base else "create", + "path": path, + "base_hash": base["content_hash"] if base else None, + "content": "def add(left, right):\n return left + right\n", + } + ], + }, + separators=(",", ":"), + ) +) diff --git a/tests/js/chat_runtime.test.cjs b/tests/js/chat_runtime.test.cjs index f05789f..b23f4d9 100644 --- a/tests/js/chat_runtime.test.cjs +++ b/tests/js/chat_runtime.test.cjs @@ -34,16 +34,20 @@ class Element { replaceChildren(...children) { this.children = [...children]; } setAttribute(name, value) { this.attributes[name] = String(value); } addEventListener(name, callback) { this.listeners[name] = callback; } + querySelectorAll() { return []; } focus() { if (!this.disabled) this.focused = true; } } const elements = new Map(); const document = { readyState: "loading", + body: { dataset: {} }, getElementById: (id) => elements.get(id) || null, createElement: (tag) => new Element(tag), addEventListener: () => {}, }; +const sessionValues = new Map(); +const localValues = new Map(); const context = { console, document, @@ -51,6 +55,15 @@ const context = { Uint8Array, Map, Set, + crypto: { randomUUID: () => "turn-runtime" }, + localStorage: { + getItem: (key) => localValues.get(key) || null, + setItem: (key, value) => localValues.set(key, value), + }, + sessionStorage: { + getItem: (key) => sessionValues.get(key) || null, + setItem: (key, value) => sessionValues.set(key, value), + }, }; vm.createContext(context); vm.runInContext(source, context, { filename: "chat.js" }); @@ -108,10 +121,32 @@ function fakeFile(name, type, bytes) { for (const id of [ "chat-transcript", "chat-announcer", "chat-composer", "chat-input", "chat-attachments", "chat-attachment-list", "chat-send", "chat-stop", "chat-status", + "chat-help", "clear-draft", "draft-state", "workspace-view", "fleet-board", + "workspace-view-button", "fleet-view-button", "workspace-composer-slot", + "workspace-transcript-slot", "fleet-composer-slot", "fleet-transcript-slot", + "chat-workspace-section", "workspace-refresh", "workspace-suggestions", "skip-link", + "workspace-setup", "workspace-details", "workspace-details-summary", "chat-kicker", + "chat-title", "chat-evidence-note", "composer-purpose", + "workspace-title", "workspace-context", "workspace-summary", "next-action-title", + "next-action-message", "next-action-remediation", "workspace-root-kind", + "workspace-run-id", "workspace-trust", "workspace-mode", "workspace-provider", + "run-picker", "run-picker-list", ]) elements.set(id, new Element(id)); const runtime = new ChatRuntime(); runtime.bind(); - assert.equal(elements.get("chat-input").disabled, true, "chat starts unavailable and fail closed"); + assert.equal(elements.get("chat-input").disabled, false, "draft remains editable while unavailable"); + assert.equal(elements.get("chat-send").disabled, true, "submission starts fail closed"); + assert.equal(elements.get("workspace-view").hidden, true, "Fleet remains the default view"); + elements.get("workspace-view-button").listeners.click(); + assert.equal(elements.get("workspace-view").hidden, false); + assert.equal(localValues.get("torq.workspace.view.v1"), "workspace"); + runtime.workspace = { + capabilities: { + can_discuss_run: true, + can_cancel: false, + attachment_types: ["image/png"], + }, + }; runtime.applySnapshot({ data_status: "available", active_turn_id: "turn-1", @@ -133,6 +168,32 @@ function fakeFile(name, type, bytes) { assert.equal(elements.get("chat-input").disabled, false); assert.equal(elements.get("chat-input").focused, true, "terminal snapshot restores composer focus"); + const workspaceA = `workspace_${"a".repeat(32)}`; + const workspaceB = `workspace_${"b".repeat(32)}`; + runtime.loadDraft(workspaceA); + elements.get("chat-input").value = "draft A"; + elements.get("chat-input").listeners.input(); + runtime.loadDraft(workspaceB); + assert.equal(elements.get("chat-input").value, "", "draft does not migrate across roots"); + elements.get("chat-input").value = "draft B"; + elements.get("chat-input").listeners.input(); + runtime.loadDraft(workspaceA); + assert.equal(elements.get("chat-input").value, "draft A", "draft restores only in its root scope"); + + runtime.runtimeAvailable = true; + runtime.workspace.capabilities.can_discuss_run = true; + let acceptRequest; + runtime.request = () => new Promise((resolve) => { acceptRequest = resolve; }); + const pendingSubmit = runtime.submit(); + elements.get("chat-input").value = "follow-up written during acceptance"; + elements.get("chat-input").listeners.input(); + runtime.applySnapshot({ data_status: "available", active_turn_id: null, messages: [], status: "ready" }); + assert.equal(elements.get("chat-send").disabled, true, "stale snapshot cannot enable a duplicate submit"); + await Promise.resolve(); + acceptRequest({ status: "accepted" }); + await pendingSubmit; + assert.equal(elements.get("chat-input").value, "follow-up written during acceptance", "in-flight edits survive acceptance"); + runtime.runtimeAvailable = true; runtime.request = async () => { throw new Error("offline"); }; await runtime.refresh(); diff --git a/tests/js/task_resume.test.cjs b/tests/js/task_resume.test.cjs new file mode 100644 index 0000000..1f713b9 --- /dev/null +++ b/tests/js/task_resume.test.cjs @@ -0,0 +1,71 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const vm = require("node:vm"); + +const source = fs.readFileSync(process.argv[2], "utf8"); +class Element { + constructor(id) { + this.id = id; this.hidden = false; this.disabled = id.startsWith("task-"); + this.value = ""; this.innerHTML = ""; this.textContent = ""; this.listeners = {}; this.dataset = {}; + } + 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 []; } +} +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" +]; +const elements = Object.fromEntries(ids.map((id) => [id, new Element(id)])); +const document = {body:new Element("body"), getElementById:(id) => elements[id] || null}; +const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); +let capabilityCalls = 0; +async function fetch(path, options = {}) { + const method = options.method || "GET"; + if (path === "/api/v1/tasks/capabilities") { + capabilityCalls += 1; + return {ok:true, json:async () => ({ + projects:[{id:"project", label:"Project"}], + can_start_task:capabilityCalls >= 3, + active_task_id:capabilityCalls === 2 ? "active-1" : null + })}; + } + if (path === "/api/v1/tasks/drafts/project" && method === "GET") { + return {ok:true, json:async () => ({draft:{goal:"", input_paths:[], output_paths:[], revision:2}})}; + } + if (path === "/api/v1/tasks/drafts/project" && method === "POST") { + 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/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}}})}; + } + if (path === "/api/v1/tasks/plans" && method === "POST") { + return {ok:true, json:async () => ({result:{plan_hash:`sha256:${"1".repeat(64)}`, provider:"claude", model:"sonnet", output_paths:["next.py"]}})}; + } + throw new Error(`unexpected ${method} ${path}`); +} +const context = { + console, document, fetch, Promise, setTimeout, clearTimeout, location:{search:""}, + localStorage:{getItem:() => null, setItem:() => {}}, crypto:{randomUUID:() => "id"}, URLSearchParams +}; +context.globalThis = context; +vm.createContext(context); +vm.runInContext(source, context, {filename:"task.js"}); + +(async () => { + await delay(0); + await elements["task-view-button"].dispatch("click"); + await delay(25); + assert.equal(capabilityCalls, 3, "terminal resumed task refreshes start capability"); + elements["task-goal"].value = "next"; + elements["task-output-paths"].value = "next.py"; + await elements["task-goal"].dispatch("input"); + await elements["task-form"].dispatch("submit"); + assert.equal(elements["task-start"].disabled, false, "a reviewed second task can start after resumed task becomes terminal"); + console.log("resumed task capability refresh checks passed"); +})().catch((error) => { console.error(error); process.exitCode = 1; }); diff --git a/tests/js/task_runtime.test.cjs b/tests/js/task_runtime.test.cjs new file mode 100644 index 0000000..26a26f9 --- /dev/null +++ b/tests/js/task_runtime.test.cjs @@ -0,0 +1,48 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const vm = require("node:vm"); + +const source = fs.readFileSync(process.argv[2], "utf8"); +const context = { + console, + globalThis: null, + document: { getElementById: () => null }, + Promise, +}; +context.globalThis = context; +vm.createContext(context); +vm.runInContext(source, context, {filename:"task.js"}); +const {MutationQueue, EditGate, requestIdForPlan} = context.TorqTask; + +(async () => { + const queue = new MutationQueue(); + const order = []; + let release; + const promiseGate = new Promise((resolve) => { release = resolve; }); + const first = queue.enqueue(async () => { await promiseGate; order.push("save"); }); + const second = queue.enqueue(() => { order.push("start"); }); + await Promise.resolve(); + assert.deepEqual(order, [], "later mutation must not overtake pending save"); + release(); + await Promise.all([first, second]); + assert.deepEqual(order, ["save", "start"]); + + const gate = new EditGate(); + const ticket = gate.capture("project-a", "draft-a"); + assert.equal(gate.accepts(ticket, "project-a", "draft-a"), true); + gate.edited(); + assert.equal(gate.accepts(ticket, "project-a", "draft-a"), false, "editing rejects stale plan response"); + const switchTicket = gate.capture("project-a", "draft-a2"); + assert.equal(gate.accepts(switchTicket, "project-b", "draft-a2"), false, "project switch rejects stale load"); + + const values = new Map(); + const storage = {getItem:(key) => values.get(key) || null, setItem:(key, value) => values.set(key, value)}; + 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)}`); + console.log("task runtime contract checks passed"); +})().catch((error) => { console.error(error); process.exitCode = 1; }); diff --git a/tests/test_candidate_task_integration.py b/tests/test_candidate_task_integration.py new file mode 100644 index 0000000..7eb3a50 --- /dev/null +++ b/tests/test_candidate_task_integration.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import hashlib +import os +import sys +import time +import json +from pathlib import Path + +import pytest + +from torq_cli.adapters.candidate_provider import CandidateProviderCommand +from torq_cli.adapters.process import ContainmentState, ExitObservation, OwnedProcess +from torq_cli.application.candidate_tasks import CandidateTaskService, TaskProject + + +pytestmark = pytest.mark.skipif(os.name != "nt", reason="strong OwnedProcess fixture is Windows") + + +def _wait(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", "stop_requested"}: + return result + time.sleep(0.02) + raise AssertionError("candidate task did not terminate") + + +def test_real_owned_fixture_builds_verified_candidate_without_changing_source(tmp_path: Path) -> None: + source = tmp_path / "source" + runtime = tmp_path / "runtime" + source.mkdir() + runtime.mkdir() + target = source / "calculator.py" + target.write_text("def add(left, right):\n return left - right\n", encoding="utf-8") + original = hashlib.sha256(target.read_bytes()).digest() + launches: list[list[str]] = [] + fixture = 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(fixture)), + 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, + ) + try: + draft = service.save_draft( + "calculator", goal="Fix addition", input_paths=["calculator.py"], + output_paths=["calculator.py"], expected_revision=0, + ) + plan = service.review_plan( + project_id="calculator", draft_revision=draft["revision"], + input_paths=["calculator.py"], output_paths=["calculator.py"], + ) + started = service.start(request_id="request-one", plan_hash=plan["plan_hash"]) + result = _wait(service, started["task_id"]) + candidate = tmp_path / "work" / started["task_id"] / "candidate" / "calculator.py" + assert result["state"] == "candidate_ready" + assert result["verified"] is True + assert result["check"] == {"profile": "structural-v1", "exit_code": 0} + assert "return left + right" in candidate.read_text(encoding="utf-8") + assert hashlib.sha256(target.read_bytes()).digest() == original + assert len(launches) == 2 + + replay = service.start(request_id="request-one", plan_hash=plan["plan_hash"]) + assert replay["task_id"] == started["task_id"] and len(launches) == 2 + candidate.with_name("extra.txt").write_text("extra", encoding="utf-8") + assert service.task(started["task_id"])["state"] == "untrusted" + finally: + service.close() + + +def test_durable_unknown_termination_blocks_new_reservation_and_allows_read_replay(tmp_path: Path) -> None: + source = tmp_path / "source" + runtime = tmp_path / "runtime" + source.mkdir() + runtime.mkdir() + service = CandidateTaskService( + projects=[TaskProject("calculator", "Calculator", source)], + state_root=tmp_path / "state", work_root=tmp_path / "work", + provider_factory=lambda prompt: pytest.fail("provider must not dispatch"), + provider="fixture", model="local-fixture", acquire_lock=False, + ) + try: + task, _ = service.store.reserve("old", {"plan_hash": "old-plan", "project_id": "calculator"}) + service.store.update_task(task["task_id"], state="termination_unknown") + assert service.capabilities()["can_start_task"] is False + with pytest.raises(ValueError, match="task_termination_unknown"): + service.start(request_id="new", plan_hash="missing") + assert service.store.snapshot()["requests"].get("new") is None + assert service.start(request_id="old", plan_hash="old-plan")["task_id"] == task["task_id"] + finally: + service.close() + + +class _UnknownOwner: + pid = 4242 + + def __init__(self) -> None: + self.output_closed = False + self.stopped = False + + def poll(self) -> int | None: + return 1 if self.stopped else None + + def next_event(self, *, timeout: float) -> None: + time.sleep(min(timeout, 0.01)) + return None + + def _observation(self) -> ExitObservation: + return ExitObservation(1 if self.stopped else None, False, None, True, False, ContainmentState.UNKNOWN) + + def wait(self, *, timeout: float = 5.0) -> ExitObservation: + del timeout + return self._observation() + + def force_stop(self, *, timeout: float = 5.0) -> ExitObservation: + del timeout + self.stopped = True + self.output_closed = True + return self._observation() + + def close(self) -> ExitObservation: + self.stopped = True + self.output_closed = True + return self._observation() + + +def test_unconfirmed_stop_terminalizes_interrupted_and_blocks_late_ready(tmp_path: Path) -> None: + source = tmp_path / "source" + runtime = tmp_path / "runtime" + source.mkdir() + runtime.mkdir() + target = source / "a.py" + target.write_text("x = 1\n", encoding="utf-8") + owner = _UnknownOwner() + service = CandidateTaskService( + projects=[TaskProject("project", "Project", source)], + state_root=tmp_path / "state", work_root=tmp_path / "work", + provider_factory=lambda prompt: CandidateProviderCommand( + (sys.executable, "-c", "pass"), str(runtime), {}, prompt.encode(), "fixture", "model" + ), + provider="fixture", model="model", owner_factory=lambda *args, **kwargs: owner, + ) + try: + draft = service.save_draft( + "project", goal="change", input_paths=["a.py"], output_paths=["a.py"], expected_revision=0 + ) + plan = service.review_plan( + project_id="project", draft_revision=draft["revision"], input_paths=["a.py"], output_paths=["a.py"] + ) + started = service.start(request_id="one", plan_hash=plan["plan_hash"]) + deadline = time.monotonic() + 5 + while service.task(started["task_id"])["state"] != "generating" and time.monotonic() < deadline: + time.sleep(0.01) + assert service.stop(started["task_id"])["state"] == "termination_unknown" + result = _wait(service, started["task_id"]) + assert result["state"] == "termination_unknown" + receipt_path = tmp_path / "state" / "evidence" / started["task_id"] / "receipts.jsonl" + rows = [] + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + rows = [json.loads(line) for line in receipt_path.read_text(encoding="utf-8").splitlines()] + if rows[-1]["payload"]["event"] == "task_interrupted": + break + time.sleep(0.01) + assert rows[-1]["payload"]["event"] == "task_interrupted" + assert rows[-1]["payload"]["termination"] == "unknown" + with pytest.raises(ValueError, match="task_termination_unknown"): + service.start(request_id="two", plan_hash=plan["plan_hash"]) + finally: + service.close() diff --git a/tests/test_candidate_tasks.py b/tests/test_candidate_tasks.py new file mode 100644 index 0000000..a344084 --- /dev/null +++ b/tests/test_candidate_tasks.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import json +import os +from pathlib import Path + +import pytest + +from torq_cli.adapters.candidate_provider import ( + CandidateProviderCommandFactory, + OUTPUT_CONTRACT, + parse_candidate_output, +) +from torq_cli.application.task_store import TaskStore +from torq_cli.safety.task_workspace import ( + digest_bytes, + materialize_candidate, + snapshot_candidate_exact, + snapshot_source, + validate_relative_path, +) + + +def test_candidate_output_is_duplicate_free_finite_and_plan_bound() -> None: + digest = "sha256:" + "1" * 64 + raw = json.dumps( + { + "contract": OUTPUT_CONTRACT, + "plan_hash": digest, + "input_hash": digest, + "operations": [ + {"operation": "create", "path": "answer.py", "base_hash": None, "content": "x = 1\n"} + ], + }, + separators=(",", ":"), + ).encode() + operations, raw_hash = parse_candidate_output(raw, plan_hash=digest, input_hash=digest) + assert operations[0]["path"] == "answer.py" + assert raw_hash == digest_bytes(raw) + with pytest.raises(ValueError, match="task_provider_output_invalid"): + parse_candidate_output(b'{"contract":"x","contract":"y"}', plan_hash=digest, input_hash=digest) + invalid = raw.replace(b'"x = 1\\n"', b'NaN') + with pytest.raises(ValueError): + parse_candidate_output(invalid, plan_hash=digest, input_hash=digest) + + +@pytest.mark.parametrize( + "value", + ("../a.py", "./a.py", "a//b.py", ".ssh/key.py", "keys/a.py", ".env.local/a.py", "a.py:stream"), +) +def test_task_paths_reject_escape_alias_and_protected_values(value: str) -> None: + with pytest.raises(ValueError): + validate_relative_path(value) + + +def test_empty_source_can_create_candidate_and_extra_inventory_downgrades(tmp_path: Path) -> None: + project = tmp_path / "project" + project.mkdir() + base = snapshot_source(project, ()) + candidate = tmp_path / "work" / "candidate" + result = materialize_candidate( + candidate, + base, + ({"operation": "create", "path": "answer.py", "base_hash": None, "content": "x = 1\n"},), + allowed_output_paths=("answer.py", "notes.md"), + ) + assert snapshot_candidate_exact(candidate, ("answer.py",)).manifest_hash == result.manifest_hash + (candidate / "extra.txt").write_text("unrecorded", encoding="utf-8") + with pytest.raises(ValueError, match="task_candidate_inventory"): + snapshot_candidate_exact(candidate, ("answer.py",)) + + +def test_task_store_draft_delete_is_monotonic_and_request_body_is_closed(tmp_path: Path) -> None: + store = TaskStore(tmp_path / "state") + first = store.put_draft( + "project", goal="Build it", input_paths=["a.py"], output_paths=["a.py"], expected_revision=0 + ) + store.delete_draft("project", expected_revision=first["revision"]) + with pytest.raises(ValueError, match="task_draft_revision_conflict"): + store.put_draft( + "project", goal="stale", input_paths=["a.py"], output_paths=["a.py"], expected_revision=0 + ) + recreated = store.put_draft( + "project", goal="new", input_paths=["a.py"], output_paths=["a.py"], expected_revision=2 + ) + assert recreated["revision"] == 3 + with pytest.raises(ValueError, match="task_request_body_invalid"): + store.reserve("request", {"plan_hash": "p", "project_id": "project", "state": "candidate_ready"}) + + +def test_task_store_idempotency_conflicts_on_changed_body(tmp_path: Path) -> None: + store = TaskStore(tmp_path / "state") + task, created = store.reserve("request", {"plan_hash": "p1", "project_id": "project"}) + replay, created_again = store.reserve("request", {"plan_hash": "p1", "project_id": "project"}) + assert created is True and created_again is False and replay["task_id"] == task["task_id"] + with pytest.raises(ValueError, match="task_request_replay_conflict"): + store.reserve("request", {"plan_hash": "p2", "project_id": "project"}) + + +@pytest.mark.skipif(os.name != "nt", reason="Windows wrapper safety") +def test_claude_batch_wrapper_is_not_treated_as_native_owned_executable(tmp_path: Path) -> None: + wrapper = tmp_path / "claude.BAT" + wrapper.write_text("@echo off\n", encoding="ascii") + runtime = tmp_path / "runtime" + runtime.mkdir() + factory = CandidateProviderCommandFactory( + provider="claude", model="sonnet", runtime_root=runtime, + base_environment={}, claude_binary=wrapper, + ) + with pytest.raises(ValueError, match="task_provider_binary_not_native"): + factory.preflight() diff --git a/tests/test_chat_cli.py b/tests/test_chat_cli.py index 29f9d4d..a38dc37 100644 --- a/tests/test_chat_cli.py +++ b/tests/test_chat_cli.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import os from pathlib import Path from typing import Any @@ -129,3 +130,66 @@ def forbidden(*args: object, **kwargs: object) -> None: "status": "blocked", } assert not run_root.exists() + + +@pytest.mark.parametrize( + ("root_case", "expected_finding"), + [ + ("missing", "workspace_root_missing"), + ("collection", "workspace_run_selection_required:run-select-me"), + ("linked", "workspace_root_link_denied"), + ("untrusted", "workspace_run_untrusted"), + ], +) +def test_fleet_chat_cli_preflights_root_before_identity_mutation( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + root_case: str, + expected_finding: str, +) -> None: + run_root = tmp_path / "selected" + if root_case == "collection": + run_root.mkdir() + selected = run_root / "run-select-me" + selected.mkdir() + for name in ("receipts.jsonl", "terminal-manifest.json", "run-certificate.json"): + (selected / name).write_text("{}", encoding="utf-8") + elif root_case == "untrusted": + run_root.mkdir() + for name in ("receipts.jsonl", "terminal-manifest.json", "run-certificate.json"): + (run_root / name).write_text("{}", encoding="utf-8") + elif root_case == "linked": + target = tmp_path / "actual" + target.mkdir() + try: + os.symlink(target, run_root, target_is_directory=True) + except (NotImplementedError, OSError): + pytest.skip("directory_symlink_unavailable") + + def forbidden(*args: object, **kwargs: object) -> None: + del args, kwargs + raise AssertionError("root preflight must precede identity or provider construction") + + monkeypatch.setattr(cli.sys, "platform", "win32") + monkeypatch.setattr(cli, "FileRunKeyStore", forbidden) + monkeypatch.setattr(cli, "ChatEvidenceJournal", forbidden) + monkeypatch.setattr(cli, "ChatProviderCommandFactory", forbidden) + + result = cli.main( + [ + "fleet", + "--run-root", + str(run_root), + "--serve", + "--chat-provider", + "claude", + "--chat-model", + "claude-opus-4-8", + ] + ) + assert result == 3 + assert json.loads(capsys.readouterr().out) == { + "finding": expected_finding, + "status": "blocked", + } diff --git a/tests/test_chat_http.py b/tests/test_chat_http.py index c2d7c42..9d4e3bf 100644 --- a/tests/test_chat_http.py +++ b/tests/test_chat_http.py @@ -77,6 +77,11 @@ def shutdown(self, *, timeout: float = 5.0) -> Mapping[str, Any] | None: return None +def _add_trusted_evidence_shape(root: Path) -> None: + for name in ("receipts.jsonl", "terminal-manifest.json", "run-certificate.json"): + (root / name).write_text("{}", encoding="utf-8") + + def _request( server: Any, method: str, @@ -155,6 +160,7 @@ def test_chat_routes_are_session_and_same_origin_gated(tmp_path: Path) -> None: def test_chat_submit_and_cancel_are_forwarded_to_single_owner(tmp_path: Path) -> None: projector = _Projector(tmp_path / "run-chat-control") projector.run_root.mkdir() + _add_trusted_evidence_shape(projector.run_root) chat = _Chat(projector.run_root) sessions = FleetSessionManager() cookie = f"torq_fleet_session={sessions.exchange(sessions.bootstrap_nonce)}" diff --git a/tests/test_fleet_ui.py b/tests/test_fleet_ui.py index 5c2a866..f0cfbe3 100644 --- a/tests/test_fleet_ui.py +++ b/tests/test_fleet_ui.py @@ -90,6 +90,16 @@ def test_fleet_ui_shell_is_public_but_contains_no_run_data(tmp_path: Path) -> No "context-submit", "chat-send", "chat-stop", + "clear-draft", + "workspace-view-button", + "fleet-view-button", + "workspace-setup", + "workspace-refresh", + "task-view-button", + "task-clear", + "task-review", + "task-start", + "task-stop", } assert 'href="#fleet-board"' in markup assert 'aria-live="polite"' in markup @@ -129,6 +139,27 @@ def test_fleet_ui_assets_are_local_no_store_and_host_guarded(tmp_path: Path) -> assert b"fleet_host_denied" in rebound_body +def test_task_ui_is_bundled_and_names_bounded_candidate_behavior() -> None: + html = Path("src/torq_cli/data/fleet/index.html").read_text(encoding="utf-8") + javascript = Path("src/torq_cli/data/fleet/task.js").read_text(encoding="utf-8") + css = Path("src/torq_cli/data/fleet/task.css").read_text(encoding="utf-8") + assert 'id="task-view-button"' in html + assert 'id="task-goal"' in html + assert 'id="task-goal" rows="5" maxlength="16384"' in html + assert 'placeholder="For example: add input validation to calculator.py" disabled' in html + assert 'id="task-review" type="submit" class="workspace-primary" disabled' in html + assert "if (!state.draftReady) return Promise.reject" in javascript + assert "await loadDraft(state.project, initialEpoch);\n setDraftReady(true);" in javascript + assert "Start building" in html + assert "Your project stays unchanged" in html + assert "It does not run unit tests or change your project" in javascript + assert "torq.task.request.${planHash}" in javascript + assert "MutationQueue" in javascript + assert "caps.active_task_id" in javascript + assert "data-task-id" in javascript + assert '@media (max-width: 760px)' in css + + def _contrast(first: str, second: str) -> float: def luminance(value: str) -> float: channels = [int(value[index:index + 2], 16) / 255 for index in (1, 3, 5)] @@ -253,6 +284,31 @@ def test_chat_composer_is_accessible_contrasted_and_non_clipping() -> None: assert 'setAttribute("aria-live", "off")' in javascript +def test_workspace_is_opt_in_truthful_and_draft_safe() -> None: + html = Path("src/torq_cli/data/fleet/index.html").read_text(encoding="utf-8") + javascript = Path("src/torq_cli/data/fleet/chat.js").read_text(encoding="utf-8") + css = Path("src/torq_cli/data/fleet/chat.css").read_text(encoding="utf-8") + + assert 'id="workspace-view"' in html + assert 'id="workspace-view-button"' in html + assert 'id="fleet-view-button"' in html + assert 'id="workspace-setup"' in html + assert 'id="clear-draft"' in html + assert "Starting builds is not available here yet" in html + assert "/api/v1/workspace" in javascript + assert 'VIEW_KEY = "torq.workspace.view.v1"' in javascript + assert 'DRAFT_KEY_PREFIX = "torq.workspace.draft.v1."' in javascript + assert "global.sessionStorage.setItem(this.draftKey, this.elements.input.value)" in javascript + assert "this.elements.input.disabled = false" in javascript + assert "this.draftRevision === submittedRevision" in javascript + assert "event.ctrlKey || event.metaKey" in javascript + assert "chat_stream_available" in javascript + assert "innerHTML" not in javascript + assert 'body[data-view="workspace"] .topbar-facts' in css + assert "@media (max-width: 40rem)" in css + assert ".workspace-suggestions { flex-wrap: wrap; }" in css + + def test_fleet_bootstrap_lands_on_ui_without_exposing_session_in_url( tmp_path: Path, ) -> None: diff --git a/tests/test_hermetic.py b/tests/test_hermetic.py index 0b0e227..721797a 100644 --- a/tests/test_hermetic.py +++ b/tests/test_hermetic.py @@ -55,6 +55,14 @@ def test_production_imports_forbid_subprocess() -> None: elif source_path.as_posix().endswith("torq_cli/adapters/chat_provider.py"): # Reads explicit runtime facts only to build a scrubbed child. local_allow = {"os", "sys"} + elif source_path.as_posix().endswith("torq_cli/adapters/candidate_provider.py"): + # Resolves the fixed provider/bridge executable and constructs a + # scrubbed child environment; process creation stays in OwnedProcess. + local_allow = {"os", "sys"} + elif source_path.as_posix().endswith("torq_cli/application/workspace.py"): + # Read-only workspace classification inspects link/reparse metadata + # before projecting trust and never launches a process or reads env. + local_allow = {"os"} elif source_path.as_posix().endswith("torq_cli/interfaces/fleet_http.py"): # The local Fleet transport is isolated to this loopback-only, # bounded interface; the application projector remains hermetic. @@ -67,6 +75,8 @@ def test_production_imports_forbid_subprocess() -> None: "torq_cli/safety/evidence_broker.py", "torq_cli/safety/accounting_registry.py", "torq_cli/safety/chat_evidence.py", + "torq_cli/safety/task_workspace.py", + "torq_cli/safety/state_lock.py", ) ): # The evidence broker owns the authenticated local-only IPC @@ -76,6 +86,9 @@ def test_production_imports_forbid_subprocess() -> None: if source_path.name == "evidence_broker.py" else {"os"} ) + elif source_path.as_posix().endswith("torq_cli/application/task_store.py"): + # Durable task 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; # this adapter never enumerates credential-bearing environment keys. diff --git a/tests/test_task_cli.py b/tests/test_task_cli.py new file mode 100644 index 0000000..3f8f5f7 --- /dev/null +++ b/tests/test_task_cli.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from pathlib import Path + +from torq_cli.interfaces import cli + + +class _Server: + server_address = ("127.0.0.1", 8765) + fleet_bootstrap_nonce = "nonce" + + def serve_forever(self) -> None: + return None + + def server_close(self) -> None: + return None + + +def test_task_only_fleet_launch_derives_state_roots_without_run_root( + tmp_path: Path, monkeypatch, capsys +) -> None: + project = tmp_path / "project" + project.mkdir() + native = tmp_path / "claude.exe" + native.write_bytes(b"native-placeholder") + captured = {} + + def server(projector, **kwargs): + del projector + captured.update(kwargs) + return _Server() + + monkeypatch.setattr(cli, "create_fleet_server", server) + monkeypatch.setattr( + cli, + "current_environment", + lambda: {"LOCALAPPDATA": str(tmp_path / "appdata"), "USERPROFILE": str(tmp_path)}, + ) + result = cli.main( + [ + "fleet", "--serve", "--task-project", f"project={project}", + "--task-provider", "claude", "--task-model", "sonnet", + "--task-claude-bin", str(native), + ] + ) + output = capsys.readouterr().out + assert result == 0 + assert '"status": "serving"' in output and "view=task" in output + assert captured["task_service"] is not None + + +def test_ordinary_fleet_still_requires_run_root(capsys) -> None: + assert cli.main(["fleet", "--serve"]) == 3 + assert "fleet_run_root_required" in capsys.readouterr().out diff --git a/tests/test_task_evidence.py b/tests/test_task_evidence.py new file mode 100644 index 0000000..87487ec --- /dev/null +++ b/tests/test_task_evidence.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +from copy import deepcopy + +from torq_cli.domain.run_evidence import validate_v2_receipt_contract +from torq_cli.domain.task_evidence import TASK_CONTRACT, validate_task_audit_payload + + +HASH = "sha256:" + "1" * 64 + + +def _body(event: str) -> dict[str, object]: + common: dict[str, object] = { + "task_contract": TASK_CONTRACT, + "event": event, + "task_id": "run-task-1", + "provider_dispatch": False, + } + if event == "task_start_accepted": + return common | { + "request_digest": HASH, + "plan_hash": HASH, + "base_manifest_hash": HASH, + "input_hash": HASH, + "artifact": "artifacts/start.enc", + "artifact_hash": HASH, + "artifact_content_hash": HASH, + "provider": "claude", + "model": "sonnet", + } + if event == "candidate_generated": + return common | { + "provider_dispatch": True, + "start_sequence": 1, + "plan_hash": HASH, + "input_hash": HASH, + "candidate_manifest_hash": HASH, + "raw_response_hash": HASH, + "artifact": "artifacts/candidate.enc", + "artifact_hash": HASH, + "artifact_content_hash": HASH, + "provider": "claude", + "model": "sonnet", + "termination": "confirmed_empty", + } + if event == "candidate_check_completed": + return common | { + "generated_sequence": 2, + "candidate_manifest_hash": HASH, + "check_profile_id": "structural-v1", + "check_profile_version": "1.0.0", + "helper_hash": HASH, + "argv_hash": HASH, + "exit_code": 0, + "output_hash": HASH, + "output_complete": True, + "termination": "confirmed_empty", + "artifact": "artifacts/check.enc", + "artifact_hash": HASH, + "artifact_content_hash": HASH, + } + return common | { + "start_sequence": 1, + "generated_sequence": 2, + "check_sequence": 3, + "plan_hash": HASH, + "base_manifest_hash": HASH, + "input_hash": HASH, + "candidate_manifest_hash": HASH, + "source_recheck_hash": HASH, + } + + +def _receipt(sequence: int, body: dict[str, object]) -> dict[str, object]: + return { + "run_id": "run-task-1", + "sequence": sequence, + "transition": "audit", + "payload": body, + } + + +def test_task_semantic_contract_accepts_linked_ready_lifecycle() -> None: + rows = [ + _receipt(index, _body(event)) + for index, event in enumerate( + ( + "task_start_accepted", + "candidate_generated", + "candidate_check_completed", + "candidate_ready", + ), + 1, + ) + ] + assert validate_v2_receipt_contract(rows, sealed=True) is None + + +def test_generic_audit_cannot_upgrade_to_task_evidence() -> None: + row = _receipt(1, {"status": "candidate_ready", "provider_dispatch": False}) + assert validate_task_audit_payload(row["payload"]) is None # type: ignore[arg-type] + + +def test_task_payload_is_closed_and_bound_to_signed_run() -> None: + body = _body("task_start_accepted") + body["extra"] = "smuggled" + assert validate_task_audit_payload(body) == "task_payload_keys_invalid" + row = _receipt(1, _body("task_start_accepted")) + row["run_id"] = "run-other" + assert validate_v2_receipt_contract([row], sealed=False) == "task_run_id_mismatch" + + +def test_task_provider_and_model_cannot_change_after_start() -> None: + rows = [ + _receipt(1, _body("task_start_accepted")), + _receipt(2, _body("candidate_generated")), + ] + changed = deepcopy(rows) + changed[1]["payload"]["model"] = "other" # type: ignore[index] + assert validate_v2_receipt_contract(changed, sealed=False) == "task_generated_link_invalid" + + +def test_task_ready_rejects_failed_check_and_post_terminal_receipt() -> None: + rows = [ + _receipt(1, _body("task_start_accepted")), + _receipt(2, _body("candidate_generated")), + _receipt(3, _body("candidate_check_completed")), + _receipt(4, _body("candidate_ready")), + ] + failed = deepcopy(rows) + failed[2]["payload"]["exit_code"] = 1 # type: ignore[index] + assert validate_v2_receipt_contract(failed, sealed=True) == "task_ready_link_invalid" + rows.append(_receipt(5, {"status": "later", "provider_dispatch": False})) + assert validate_v2_receipt_contract(rows, sealed=True) == "task_receipt_after_terminal" + + +def test_task_cannot_seal_without_exact_terminal() -> None: + rows = [_receipt(1, _body("task_start_accepted"))] + assert validate_v2_receipt_contract(rows, sealed=True) == "task_terminal_missing" + + +def test_pre_dispatch_interruption_can_be_the_only_terminal_receipt() -> None: + body = { + "task_contract": TASK_CONTRACT, + "event": "task_interrupted", + "task_id": "run-task-1", + "phase": "reserved", + "reason_code": "task_coordinator_restarted", + "caused_by_sequence": None, + "provider_dispatch": False, + "termination": "not_started", + } + assert validate_v2_receipt_contract([_receipt(1, body)], sealed=True) is None diff --git a/tests/test_task_http.py b/tests/test_task_http.py new file mode 100644 index 0000000..67dfe36 --- /dev/null +++ b/tests/test_task_http.py @@ -0,0 +1,110 @@ +from __future__ import annotations + +import http.client +import json +import threading +from pathlib import Path +from typing import Any + +from torq_cli.application.fleet import FleetProjector +from torq_cli.interfaces.fleet_http import create_fleet_server + + +class _Tasks: + def __init__(self) -> None: + self.saved = 0 + self.started: tuple[str, str] | None = None + + def capabilities(self) -> dict[str, Any]: + return {"schema": "torq-task-capabilities-v1", "projects": [{"id": "project", "label": "Project"}], "can_start_task": True, "active_task_id": None} + + def draft(self, project_id: str) -> dict[str, Any] | None: + if project_id != "project": + raise ValueError("task_project_unknown") + return None + + def save_draft(self, project_id: str, *, goal: str, input_paths: list[str], output_paths: list[str], expected_revision: int) -> dict[str, Any]: + self.saved += 1 + return {"project_id": project_id, "goal": goal, "input_paths": input_paths, "output_paths": output_paths, "revision": expected_revision + 1} + + def delete_draft(self, project_id: str, *, expected_revision: int) -> None: + del project_id, expected_revision + + def review_plan(self, *, project_id: str, draft_revision: int, input_paths: list[str], output_paths: list[str]) -> dict[str, Any]: + return {"project_id": project_id, "draft_revision": draft_revision, "input_paths": input_paths, "output_paths": output_paths, "plan_hash": "sha256:" + "1" * 64} + + def start(self, *, request_id: str, plan_hash: str) -> dict[str, Any]: + self.started = (request_id, plan_hash) + return {"task_id": "run-task-" + "1" * 24, "state": "reserved"} + + def replay_start(self, *, request_id: str, plan_hash: str) -> dict[str, Any]: + if self.started != (request_id, plan_hash): + raise ValueError("task_request_replay_missing") + return self.start(request_id=request_id, plan_hash=plan_hash) + + def stop(self, task_id: str) -> dict[str, Any]: + return {"task_id": task_id, "state": "stop_requested"} + + def task(self, task_id: str) -> dict[str, Any]: + return {"task_id": task_id, "state": "candidate_ready", "verified": True} + + def history(self) -> list[dict[str, Any]]: + return [] + + +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) + headers: dict[str, str] = {} + encoded = None + if cookie: + headers["Cookie"] = cookie + if origin: + headers["Origin"] = origin + if body is not None: + encoded = json.dumps(body) + headers["Content-Type"] = "application/json" + connection.request(method, path, body=encoded, headers=headers) + response = connection.getresponse() + raw = response.read() + result = response.status, dict(response.getheaders()), json.loads(raw) if raw else {} + connection.close() + return result + + +def test_task_http_requires_session_origin_and_closed_request_body(tmp_path: Path) -> None: + tasks = _Tasks() + server = create_fleet_server(FleetProjector(tmp_path / "no-run"), port=0, task_service=tasks) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + host, port = server.server_address[:2] + origin = f"http://{host}:{port}" + try: + assert _request(server, "GET", "/api/v1/tasks/capabilities")[0] == 401 + bootstrap = _request(server, "GET", f"/bootstrap?nonce={server.fleet_bootstrap_nonce}&view=task") + assert bootstrap[0] == 303 and bootstrap[1]["Location"] == "/?view=task" + cookie = bootstrap[1]["Set-Cookie"].split(";", 1)[0] + status, _, caps = _request(server, "GET", "/api/v1/tasks/capabilities", cookie=cookie) + assert status == 200 and caps["projects"][0]["id"] == "project" + payload = {"goal": "Build", "input_paths": [], "output_paths": ["a.py"], "expected_revision": 0} + denied = _request(server, "POST", "/api/v1/tasks/drafts/project", cookie=cookie, origin="http://attacker", body=payload) + assert denied[0] == 403 + cookie = denied[1]["Set-Cookie"].split(";", 1)[0] + status, headers, body = _request(server, "POST", "/api/v1/tasks/drafts/project", cookie=cookie, origin=origin, body=payload | {"unknown": True}) + assert status == 409 and body["finding"] == "task_draft_request_invalid" and tasks.saved == 0 + cookie = headers["Set-Cookie"].split(";", 1)[0] + status, headers, body = _request(server, "POST", "/api/v1/tasks/drafts/project", cookie=cookie, origin=origin, body=payload) + assert status == 200 and body["result"]["revision"] == 1 and tasks.saved == 1 + cookie = headers["Set-Cookie"].split(";", 1)[0] + start_body = {"request_id": "stable-request", "plan_hash": "sha256:" + "1" * 64} + first = _request(server, "POST", "/api/v1/tasks", cookie=cookie, origin=origin, body=start_body) + assert first[0] == 202 + # Keep the old cookie to simulate losing the response (and its rotated cookie). + denied_replay = _request(server, "POST", "/api/v1/tasks", cookie=cookie, origin=origin, body=start_body | {"request_id": "different"}) + assert denied_replay[0] == 409 and "Set-Cookie" not in denied_replay[1] + replay = _request(server, "POST", "/api/v1/tasks", cookie=cookie, origin=origin, body=start_body) + assert replay[0] == 202 and "Set-Cookie" in replay[1] + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) diff --git a/tests/test_task_ui_runtime.py b/tests/test_task_ui_runtime.py new file mode 100644 index 0000000..5b06e5f --- /dev/null +++ b/tests/test_task_ui_runtime.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import shutil +import subprocess +from pathlib import Path + +import pytest + + +def test_task_javascript_runtime_contract() -> None: + node = shutil.which("node") + if node is None: + pytest.skip("node_runtime_unavailable") + result = subprocess.run( + [ + node, + str(Path("tests/js/task_runtime.test.cjs").resolve()), + str(Path("src/torq_cli/data/fleet/task.js").resolve()), + ], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr or result.stdout + assert "task runtime contract checks passed" in result.stdout + + +def test_resumed_task_refreshes_capability_for_next_plan() -> None: + node = shutil.which("node") + if node is None: + pytest.skip("node_runtime_unavailable") + result = subprocess.run( + [ + node, + str(Path("tests/js/task_resume.test.cjs").resolve()), + str(Path("src/torq_cli/data/fleet/task.js").resolve()), + ], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr or result.stdout + assert "resumed task capability refresh checks passed" in result.stdout diff --git a/tests/test_workspace.py b/tests/test_workspace.py new file mode 100644 index 0000000..18a4ec6 --- /dev/null +++ b/tests/test_workspace.py @@ -0,0 +1,306 @@ +from __future__ import annotations + +import http.client +import json +import os +import threading +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +import pytest + +from torq_cli.application.workspace import classify_workspace_root +from torq_cli.interfaces.fleet_http import FleetSessionManager, create_fleet_server + + +class _Projector: + def __init__(self, root: Path, *, closed: bool = False) -> None: + self.run_root = root + self.closed = closed + self.operational_state: Mapping[str, Any] = {} + + def snapshot(self) -> dict[str, Any]: + return { + "schema": "torq-fleet-snapshot-v3", + "verification": { + "state": "sealed_verified" if self.closed else "live_verified", + "finding": None, + "covered_sequence": 1, + "manifest_generation": 1, + }, + "data_status": "available", + "run": { + "run_id": self.run_root.name, + "workflow_state": "closed" if self.closed else "open", + "mode": "dry_run", + }, + "summary": {"open_actions": 0}, + "lanes": [], + "actions": [], + "settlement": None, + } + + +class _TamperedProjector(_Projector): + def snapshot(self) -> dict[str, Any]: + return { + "schema": "torq-fleet-snapshot-v3", + "verification": { + "state": "tampered", + "finding": "receipt_hash_mismatch", + "covered_sequence": None, + "manifest_generation": None, + }, + "data_status": "unavailable", + "run": None, + "summary": None, + "lanes": [], + "actions": [], + "settlement": None, + } + + +class _Chat: + def __init__(self, root: Path, active: str | None = None) -> None: + self.root = root + self.active = active + + def snapshot(self) -> Mapping[str, Any]: + return {"active_turn_id": self.active, "stream_sequence": 0} + + def subscribe(self, *, capacity: int = 256) -> Any: + raise AssertionError(capacity) + + def unsubscribe(self, channel: Any) -> None: + raise AssertionError(channel) + + def submit(self, **kwargs: Any) -> Mapping[str, Any]: + raise AssertionError(kwargs) + + def cancel(self, turn_id: str, *, timeout: float = 5.0) -> Mapping[str, Any]: + raise AssertionError((turn_id, timeout)) + + def shutdown(self, *, timeout: float = 5.0) -> Mapping[str, Any] | None: + return None + + +def _evidence_shape(root: Path) -> None: + root.mkdir() + for name in ("receipts.jsonl", "terminal-manifest.json", "run-certificate.json"): + (root / name).write_text("{}", encoding="utf-8") + + +def _get(server: Any, path: str, cookie: str | None = None) -> tuple[int, dict[str, Any]]: + host, port = server.server_address[:2] + connection = http.client.HTTPConnection(host, port, timeout=5) + headers = {"Host": f"127.0.0.1:{port}"} + if cookie: + headers["Cookie"] = cookie + connection.request("GET", path, headers=headers) + response = connection.getresponse() + body = json.loads(response.read()) + connection.close() + return response.status, body + + +def _post_chat(server: Any, cookie: str) -> tuple[int, dict[str, Any]]: + host, port = server.server_address[:2] + connection = http.client.HTTPConnection(host, port, timeout=5) + payload = json.dumps({"turn_id": "turn-direct", "text": "hello", "attachments": []}) + connection.request( + "POST", + "/api/v1/chat/turns", + body=payload, + headers={ + "Host": f"127.0.0.1:{port}", + "Origin": f"http://127.0.0.1:{port}", + "Cookie": cookie, + "Content-Type": "application/json", + "Content-Length": str(len(payload.encode("utf-8"))), + }, + ) + response = connection.getresponse() + body = json.loads(response.read()) + connection.close() + return response.status, body + + +def test_workspace_root_classification_is_bounded_stable_and_separate(tmp_path: Path) -> None: + missing = tmp_path / "missing" + empty = tmp_path / "empty" + empty.mkdir() + collection = tmp_path / "collection" + collection.mkdir() + for index in range(80): + (collection / f"notes-{index:03d}").mkdir() + _evidence_shape(collection / "run-second") + + missing_first = classify_workspace_root(missing) + missing_second = classify_workspace_root(missing) + assert missing_first["root_kind"] == "missing" + assert missing_first["workspace_id"] == missing_second["workspace_id"] + assert missing_first["workspace_id"] != classify_workspace_root(empty)["workspace_id"] + assert classify_workspace_root(empty)["root_kind"] == "empty" + classified_collection = classify_workspace_root(collection) + assert classified_collection["root_kind"] == "collection" + assert classified_collection["runs"] == ["run-second"] + + +def test_workspace_classifies_verified_and_untrusted_individual_runs(tmp_path: Path) -> None: + root = tmp_path / "run-selected" + _evidence_shape(root) + verified = classify_workspace_root(root, _Projector(root).snapshot()) + assert verified["root_kind"] == "individual_run" + assert verified["trusted"] is True + assert verified["selected_run_id"] == "run-selected" + assert verified["run_mode"] == "dry_run" + + custom_root = tmp_path / "historical.custom-id" + _evidence_shape(custom_root) + custom = classify_workspace_root(custom_root, _Projector(custom_root).snapshot()) + assert custom["trusted"] is True + assert custom["selected_run_id"] == "historical.custom-id" + + tampered = classify_workspace_root( + root, + { + "data_status": "unavailable", + "verification": {"state": "tampered", "finding": "receipt_hash_mismatch"}, + "run": None, + }, + ) + assert tampered["root_kind"] == "individual_run" + assert tampered["trusted"] is False + assert tampered["reason_code"] == "workspace_run_untrusted" + + +def test_workspace_rejects_linked_root_or_ancestor(tmp_path: Path) -> None: + target = tmp_path / "actual" + target.mkdir() + link = tmp_path / "linked" + try: + os.symlink(target, link, target_is_directory=True) + except (NotImplementedError, OSError): + pytest.skip("directory_symlink_unavailable") + assert classify_workspace_root(link)["reason_code"] == "workspace_root_link_denied" + assert classify_workspace_root(link / "missing")["reason_code"] == "workspace_root_link_denied" + + +@pytest.mark.parametrize( + ("provider", "attachment_count"), + [("claude", 0), ("deepseek", 8), ("invented", 0)], +) +def test_workspace_metadata_is_authenticated_redacted_and_provider_driven( + tmp_path: Path, + provider: str, + attachment_count: int, +) -> None: + root = tmp_path / "run-metadata" + _evidence_shape(root) + sessions = FleetSessionManager() + cookie = f"torq_fleet_session={sessions.exchange(sessions.bootstrap_nonce)}" + server = create_fleet_server( + _Projector(root), # type: ignore[arg-type] + port=0, + sessions=sessions, + chat_controller=_Chat(root), # type: ignore[arg-type] + chat_snapshot_provider=lambda: { + "data_status": "available", + "messages": [], + "status": "ready", + }, + workspace_chat_provider=provider, + ) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + before = sorted(str(item.relative_to(tmp_path)) for item in tmp_path.rglob("*")) + try: + status, denied = _get(server, "/api/v1/workspace") + assert status == 401 + assert denied["finding"] == "fleet_session_required" + status, body = _get(server, "/api/v1/workspace", cookie) + assert status == 200 + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + after = sorted(str(item.relative_to(tmp_path)) for item in tmp_path.rglob("*")) + + assert before == after + assert body["workspace_id"].startswith("workspace_") + assert str(tmp_path) not in json.dumps(body) + assert body["capabilities"]["can_start_task"] is False + assert body["capabilities"]["execution_supported"] is False + assert len(body["capabilities"]["attachment_types"]) == attachment_count + assert body["provider"]["authentication"] == "not_checked" + + +def test_workspace_stop_capability_is_independent_of_send(tmp_path: Path) -> None: + root = tmp_path / "run-active" + _evidence_shape(root) + sessions = FleetSessionManager() + cookie = f"torq_fleet_session={sessions.exchange(sessions.bootstrap_nonce)}" + server = create_fleet_server( + _Projector(root), # type: ignore[arg-type] + port=0, + sessions=sessions, + chat_controller=_Chat(root, "turn-active"), # type: ignore[arg-type] + chat_snapshot_provider=lambda: {"data_status": "available", "messages": []}, + workspace_chat_provider="deepseek", + ) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + status, body = _get(server, "/api/v1/workspace", cookie) + assert status == 200 + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + assert body["capabilities"]["can_discuss_run"] is False + assert body["capabilities"]["can_cancel"] is True + assert body["guidance"]["reason_code"] == "chat_turn_active" + + +@pytest.mark.parametrize( + ("projector_factory", "chat_data_status", "active_turn", "finding"), + [ + (lambda root: _Projector(root, closed=True), "available", None, "fleet_session_read_only"), + (lambda root: _TamperedProjector(root), "available", None, "workspace_run_untrusted"), + (lambda root: _Projector(root), "unavailable", None, "chat_runtime_unavailable"), + (lambda root: _Projector(root), "available", "turn-active", "chat_turn_active"), + ], +) +def test_direct_chat_submit_rechecks_fresh_workspace_eligibility_before_get( + tmp_path: Path, + projector_factory: Any, + chat_data_status: str, + active_turn: str | None, + finding: str, +) -> None: + root = tmp_path / "run-submit-gate" + _evidence_shape(root) + sessions = FleetSessionManager() + cookie = f"torq_fleet_session={sessions.exchange(sessions.bootstrap_nonce)}" + server = create_fleet_server( + projector_factory(root), + port=0, + sessions=sessions, + chat_controller=_Chat(root, active_turn), # type: ignore[arg-type] + chat_snapshot_provider=lambda: { + "data_status": chat_data_status, + "messages": [], + }, + workspace_chat_provider="claude", + ) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + status, body = _post_chat(server, cookie) + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) + assert status == 409 + assert body["finding"] == finding From 5e9bbf37a2e158f4ed51f2885d81eb6abbcaaf94 Mon Sep 17 00:00:00 2001 From: King Flowers Date: Wed, 16 Sep 2026 21:36:27 -0500 Subject: [PATCH 4/6] fix: type-check platform-specific task locks across CI hosts --- src/torq_cli/safety/state_lock.py | 6 +++--- tests/test_hermetic.py | 13 ++++++++----- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/torq_cli/safety/state_lock.py b/src/torq_cli/safety/state_lock.py index ffe3245..5e5fcb5 100644 --- a/src/torq_cli/safety/state_lock.py +++ b/src/torq_cli/safety/state_lock.py @@ -2,7 +2,7 @@ from __future__ import annotations -import os +import sys from pathlib import Path from types import TracebackType @@ -17,7 +17,7 @@ def __init__(self, state_root: Path) -> None: self._stream = self.path.open("a+b") restrict_owner_only_file(self.path) try: - if os.name == "nt": + if sys.platform == "win32": import msvcrt self._stream.seek(0) @@ -39,7 +39,7 @@ def close(self) -> None: if self._stream.closed: return try: - if os.name == "nt": + if sys.platform == "win32": import msvcrt self._stream.seek(0) diff --git a/tests/test_hermetic.py b/tests/test_hermetic.py index 721797a..6e71694 100644 --- a/tests/test_hermetic.py +++ b/tests/test_hermetic.py @@ -81,11 +81,14 @@ def test_production_imports_forbid_subprocess() -> None: ): # The evidence broker owns the authenticated local-only IPC # boundary (AF_PIPE on Windows, AF_UNIX on POSIX). - local_allow = ( - {"os", "socket"} - if source_path.name == "evidence_broker.py" - else {"os"} - ) + if source_path.name == "evidence_broker.py": + local_allow = {"os", "socket"} + elif source_path.name == "state_lock.py": + # sys.platform is the static type-checkable discriminator for + # the mutually exclusive msvcrt/fcntl kernel lock backends. + 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. local_allow = {"os"} From e3f38989c6fb950744b2d742adc48b9bd560fb93 Mon Sep 17 00:00:00 2001 From: King Flowers Date: Wed, 16 Sep 2026 21:39:03 -0500 Subject: [PATCH 5/6] test: mark task CLI fixture executable on POSIX --- tests/test_task_cli.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_task_cli.py b/tests/test_task_cli.py index 3f8f5f7..ac7cb1a 100644 --- a/tests/test_task_cli.py +++ b/tests/test_task_cli.py @@ -23,6 +23,7 @@ def test_task_only_fleet_launch_derives_state_roots_without_run_root( project.mkdir() native = tmp_path / "claude.exe" native.write_bytes(b"native-placeholder") + native.chmod(0o700) captured = {} def server(projector, **kwargs): @@ -44,7 +45,7 @@ def server(projector, **kwargs): ] ) output = capsys.readouterr().out - assert result == 0 + assert result == 0, output assert '"status": "serving"' in output and "view=task" in output assert captured["task_service"] is not None From fe087a50dadd5035180bf0a46819a041206eee3b Mon Sep 17 00:00:00 2001 From: King Flowers Date: Wed, 16 Sep 2026 21:43:24 -0500 Subject: [PATCH 6/6] fix: resolve the running interpreter before native task checks --- src/torq_cli/adapters/candidate_provider.py | 10 ++++++---- tests/test_candidate_tasks.py | 6 ++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/torq_cli/adapters/candidate_provider.py b/src/torq_cli/adapters/candidate_provider.py index a79c68e..2faa36e 100644 --- a/src/torq_cli/adapters/candidate_provider.py +++ b/src/torq_cli/adapters/candidate_provider.py @@ -77,7 +77,7 @@ def preflight(self) -> dict[str, object]: binary = _native_executable(self.claude_binary) elif self.provider in {"deepseek", "kimi", "qwen", "zai"}: bridge = Path(__file__).with_name("chat_bridge.py") - _native_executable(Path(sys.executable)) + binary = trusted_python_executable() if bridge.is_symlink() or not bridge.is_file(): raise ValueError("task_provider_bridge_unsafe") if self.vault is None: @@ -85,7 +85,6 @@ def preflight(self) -> dict[str, object]: # Resolve the credential now without disclosing it. Authentication is # still unknown until the provider accepts an actual request. claude_compatible_environment(self.provider, self.vault, self.base_environment) - binary = str(Path(sys.executable).resolve()) else: raise ValueError("task_provider_unsupported") return {"provider": self.provider, "model": self.model, "binary": binary, "authentication": "not_checked"} @@ -118,7 +117,7 @@ def __call__(self, prompt: str) -> CandidateProviderCommand: if self.vault is None: raise ValueError("task_credential_source_required") bridge = Path(__file__).with_name("chat_bridge.py").resolve() - argv = (_native_executable(Path(sys.executable)), "-I", "-S", str(bridge)) + argv = (trusted_python_executable(), "-I", "-S", str(bridge)) environment = claude_compatible_environment( self.provider, self.vault, self.base_environment ) @@ -196,7 +195,10 @@ def parse_candidate_output( def trusted_python_executable() -> str: """Return the interpreter identity only at the audited adapter boundary.""" - return _native_executable(Path(sys.executable)) + # Virtual environments and hosted CI commonly expose the already-running + # interpreter through a symlink. Resolve that trusted process identity + # before applying the native-target checks used for child execution. + return _native_executable(Path(sys.executable).resolve(strict=True)) __all__ = [ diff --git a/tests/test_candidate_tasks.py b/tests/test_candidate_tasks.py index a344084..a318fd0 100644 --- a/tests/test_candidate_tasks.py +++ b/tests/test_candidate_tasks.py @@ -2,6 +2,7 @@ import json import os +import sys from pathlib import Path import pytest @@ -10,6 +11,7 @@ CandidateProviderCommandFactory, OUTPUT_CONTRACT, parse_candidate_output, + trusted_python_executable, ) from torq_cli.application.task_store import TaskStore from torq_cli.safety.task_workspace import ( @@ -21,6 +23,10 @@ ) +def test_trusted_running_interpreter_resolves_alias_before_native_validation() -> None: + assert trusted_python_executable() == str(Path(sys.executable).resolve(strict=True)) + + def test_candidate_output_is_duplicate_free_finite_and_plan_bound() -> None: digest = "sha256:" + "1" * 64 raw = json.dumps(