test: verify the coordinator conversation acceptance flow
24 files changed,
+1,177
−50
docs/plan-3-acceptance.md+58 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+242 −0docs/superpowers/plans/LIVE-GATE-plan-3.md+142 −0internal/equipo/conversation/coordinator_refusal.go+1 −1internal/equipo/conversation/handlers.go+3 −3internal/equipo/conversation/preferences.go+3 −3internal/equipo/conversation/settings.go+1 −1internal/equipo/conversation/store.go+5 −0internal/equipo/personapi/auth.go+5 −0internal/equipo/personapi/list_order.go+57 −0internal/equipo/personapi/reads.go+18 −3internal/equipo/personapi/requests.go+14 −7internal/equipo/planning/handlers.go+1 −1internal/equipo/task_views.go+4 −1internal/plan3test/coordinator_acceptance_http_test.go+313 −0internal/plan3test/coordinator_acceptance_test.go+257 −0internal/plan3test/coordinator_refusal3_test.go+2 −20internal/plan3test/coordinator_release_test.go+43 −0internal/plan3test/person_api_fixes_test.go+4 −0internal/release/policy_inventory.go+3 −0internal/runner/checks/render_test.go+1 −1internal/runner/coordinator_recovery.go+0 −3internal/runner/runtime_direct.go+0 −4internal/runner/turn_prompt.go+0 −2
CI failed — run details
Intent
diff --git a/docs/plan-3-acceptance.md b/docs/plan-3-acceptance.md| new file mode 100644 |
| index 00000000..cd6d09b8 |
| --- /dev/null |
| +++ b/docs/plan-3-acceptance.md |
| @@ -0,0 +1,58 @@ |
| +# Draft: pending copy review |
| + |
| +Plan 3a adds a private coordinator conversation, shared task threads, editable |
| +plans, sourced recommendations and personal preferences. Tasks 1–11 are the |
| +offline usable stop. Production use still needs reviewed copy and certification |
| +with Paul's dedicated provider accounts. |
| + |
| +For the offline gate, run these commands from the `plan-3` checkout with on-disk |
| +`TMPDIR` and the default Go caches: |
| + |
| +```bash |
| +CGO_ENABLED=0 go test ./internal/plan3test \ |
| + -run '^TestCoordinator(Acceptance3A|Release)' -count=1 |
| +CGO_ENABLED=0 go build ./cmd/equipo ./cmd/equipo-runner |
| +make migration-check |
| +make budget |
| +staticcheck ./... |
| +go vet ./... |
| +``` |
| + |
| +Use the pinned `go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./...` invocation |
| +if staticcheck is not installed. The controller runs `make ci` once before final |
| +review. Individual task runs use targeted tests. |
| + |
| +The acceptance test uses two fixture browser identities, loopback HTTP, the |
| +runner service, durable capture and journal, and fake provider frames. It covers |
| +bug, feature and recommendation proposals, editing, approval, project correction, |
| +questions, routed replies, preference privacy, cancellation and interrupted-turn |
| +recovery. The companion runner graph tests use local Git, fake providers and the |
| +fake forge to check exact-candidate evidence, independent-family review, |
| +publication readback and the wait for a person. These fixtures establish offline |
| +behavior only. |
| + |
| +The browser-session person API uses `/api/v1`. Fetch the current revision before |
| +editing. Send it as `If-Match` and use an `Idempotency-Key` for a mutation. Retry |
| +an identical request with the same key after a lost response. A different edit |
| +needs a new key and the current revision. Device bearer credentials are reserved |
| +for Plan 3b. See [the API schema](api/equipo-v1.openapi.json). |
| + |
| +List cursors are opaque and scoped to the person and stream. They expire after |
| +24 hours. Tasks, journey, actionable work, cards and preferences use the latest |
| +stored resource audit time, newest first, then ID to break ties. People use |
| +address order. Conversation and thread messages use their stored sequence. |
| +Changes can move an item ahead of an existing cursor; start again to see the |
| +latest order. Lists read current authorized data and never carry stored copies |
| +of private content in a cursor. |
| + |
| +A contained uncertain coordinator turn waits for your choice. Retrying creates |
| +new admitted work; resetting advances the coordinator generation. A refused |
| +recovery does not make that choice for you. Cancellation and reset still need |
| +containment before they can release a running account. |
| + |
| +Before live use, review every pending entry in the controller report's |
| +`3a copy inventory`, then follow |
| +[the 3a live script and checklist](superpowers/plans/LIVE-GATE-plan-3.md#3a). |
| +Record the offline result, copy-review result and live certification separately. |
| +Keep release eligibility off until all three are complete. Equipo publishes |
| +review branches and waits for the decision owner; you merge manually. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 9809365e..e389399a 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -3285,3 +3285,245 @@ The unrequested review nits (acknowledgement revision calculation, null native i |
| - `internal/runnerproto/question_answer_json.go` |
| The tracked controller report and this ignored coordinator report were appended, preserving earlier entries. Work is saved on plan-3. Temporary worktrees and task scratch are removed before handoff; no task process remains running. |
| + |
| + |
| +## Task 11 |
| + |
| +Status: DONE_WITH_CONCERNS. Offline acceptance and required integration gates pass. Copy review and live certification remain pending. Release eligibility stays off. No live provider session, sign-in, enrolment, push, merge, deployment, other agent or copy-review server was used. |
| + |
| +### Implementation |
| + |
| +Added `TestCoordinatorAcceptance3A` and `TestCoordinatorReleaseNeedsPolicyCertification`, with a loopback HTTP fixture using both browser sessions, the real runner HTTP client, coordinator service, capture, journal, tool broker and application transactions. Only provider I/O and containment are simulated. The fake adapter writes through the durable capture input before emitting recorded normalized frames; it does not edit journal tables to fabricate a dispatch. The test proposes bug, feature and recommendation plans from messages, edits a future step, corrects an unstarted project's selection, approves, routes a reply, corrects a private preference and restarts after a durable input without completion. It checks exactly-once proposal and delivery, retained uncertainty, no repeated provider start, separate private histories and preference access. Companion subtests cover questions through HTTP, active cancellation through the real claimed-assignment and containment operations, one-family sourced recommendation delivery, claim/account scope, atomic delivery and decision-owner merge acknowledgement. |
| + |
| +Acceptance is layered. The named integration test covers HTTP, application, coordinator and journal behavior. Existing runner graph tests separately exercise local Git, fake provider processes, trusted checks and the fake forge, including bug/feature/recommendation workflows, independent review families, exact candidate identity, branch/description readback and the human wait. The provider adapter continuity tests exercise recorded Claude and Codex streams. This is not a single uninterrupted browser-to-forge test or production certification. |
| + |
| +Fixed the carried integration issues: |
| + |
| +- API task, journey, needs-you, card and preference cursors now contain the actual recency position and ID tie-breaker. These records do not have universal created/updated columns, so recency comes from their latest persisted resource audit timestamp. Newest is first; equal timestamps use ascending ID. People retain address order; message streams retain sequence order. No-history resources sort last, deterministically. A query failure remains an error. Tests deliberately reverse ID order against timestamps and page tasks, journey, cards and preferences at limit 1. The existing insertion/deletion test now uses equal audit timestamps to test the ID tie-breaker intentionally. Prior unreleased generic cursor shapes return 410 and require a fresh fetch. |
| +- API read transactions recheck active membership and the authenticated session epoch. A deterministic callback advances the member epoch after HTTP authentication but before the data transaction; the read now returns 403. Existing current-member checks still deny removed members and failed lookups. |
| +- Conversation and thread cursor tests reject another person, the private/shared stream swap, and another shared task stream through the actual API handler. Tokens remain encrypted, authenticated and scoped, with no stored resource contents. |
| +- Fresh HTML conversation page reads delete expired legacy cursor rows in the same transaction. The old cursor table contains positions, not copied message bodies. Pagination still uses those rows for HTML; the API remains read-only and sealed. No background sweeper was introduced. |
| +- An uncertain coordinator turn in its current generation remains uncertain after a refused recovery, even after containment. It continues to block the queue until the person retries or resets. An explicit reset can still return the definitive fenced response and release the next generation. Replaced the earlier Task 7 test that incorrectly expected a same-generation uncertain turn to release automatically. |
| +- `Manifest.ActionCertified` now rejects pending live-gate copy even with an otherwise matching certificate. It also retains the pending-action inventory and exact tuple checks. |
| + |
| +Fixed every staticcheck finding from `./...`: the four numeric HTTP statuses and the shadowed error in conversation, one numeric status in planning, one test conversion, and three unused runner helpers/constants. The shadowed error was a real failure path: inserting the deletion tombstone for an inferred preference could fail while the operation continued to audit and report success. Its regression test now requires rollback and an error. No runtime copy changed. No schema or budget exception changed. The root package stays within its existing 10,800-line ceiling; all 31 directories pass the size gate. |
| + |
| +### Red and green evidence |
| + |
| +Initial tests were written before the integration fixes. The required command |
| + |
| +`CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinator(Acceptance3A|Release)' -count=1` |
| + |
| +first exited 1 with automatic uncertain-turn fencing, ID-based preference order, HTTP 200 after an epoch advance and retained expired HTML cursor rows. The initial release fixture used `coordinator` instead of the executable action `coordinate`; that fixture error was corrected before evaluating the release guard. The HTTP fixture also needed the wire serializer, the target project's decision owner/budget, and real durable capture input before it represented valid operations. |
| + |
| +To verify the corrected regression fixtures against the starting implementation, restored the seven changed behavior files temporarily to HEAD `8e3ee5d`, ran the same required command, then restored every file in a Python `finally` block. Exit 1, package time 4.885s. The final fixtures failed on uncertain fencing, preference/task/journey/card recency, the read epoch, HTML cursor expiry retention and pending-copy release eligibility. The stream-scope tests passed before the fix, confirming that boundary was already enforced. This baseline run occurred before adding the separate active-cancellation subtest; that subtest exercises existing behavior. |
| + |
| +Final checks: |
| + |
| +| Command | Exit | Result | |
| +| --- | --- | --- | |
| +| `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinator(Acceptance3A|Release)' -count=1` | 0 | 9.463s | |
| +| `CGO_ENABLED=0 go test ./internal/plan3test -run '^Test(Coordinator|PersonAPI|ConversationCursor|PlanWorkflow|PreferencesCorrection|PreferencesInferredDelete)' -count=1` | 0 | 33.677s, below the 300s integration budget; earlier broader run was 53.656s | |
| +| `CGO_ENABLED=0 go test ./internal/runner -run '^Test(DirectBugWorkflow|PlanWorkflowFeature|PlanWorkflowCandidateOrder|PlanWorkflowRecommendation|CoordinatorCrashRecordedBoundaries|CoordinatorSessionService|CoordinatorUsageOnce|CoordinatorRefusalMatrix)$' -count=1` | 0 | 299.025s; local Git, fake forge/provider, real namespace/check paths and runner recovery | |
| +| `CGO_ENABLED=0 go test ./internal/release ./internal/directlive ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/codex -run '^Test(Coordinator|MergedPlanPolicyInventory|PlanWorkflowRelease|DirectLiveGate)' -count=1` | 0 | release 0.003s; directlive 52.470s; provider 0.049s; Claude 7.326s; Codex 9.292s; recorded fixtures only | |
| +| `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPreferencesInferredDeleteFailure$' -count=1` | 0 | 0.662s | |
| +| `CGO_ENABLED=0 go build ./cmd/equipo ./cmd/equipo-runner` | 0 | Both binaries build | |
| +| `make migration-check` | 0 | Targeted `TestMigrationModels`, 0.318s | |
| +| `make budget` | 0 | 31 directories within existing limits | |
| +| `staticcheck ./...` | 127 | Executable absent from PATH; used the pinned equivalent below | |
| +| `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./...` | 0 | All findings fixed; final run has no output | |
| +| `go vet ./...` | 0 | No findings | |
| +| `gofmt -l` on every changed/new Go file; `git diff --check` | 0 | No output | |
| +| `EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$' -count=1` | 1, expected | `COPY REVIEW REQUIRED: runtime inventory has unreviewed entries` | |
| +| `python3 scripts/runner-release-check.py` | 1, expected | Current release manifest remains uncertified | |
| + |
| +No `make ci`, full test suite, live-tag test or provider login was run. `.amadan/ci`, `.amadan/ci.d/` and the Makefile remain unchanged. The controller retains the single final `make ci` run. |
| + |
| +### Guard mutations |
| + |
| +Applied each mutation alone, observed an assertion failure, restored the file byte-for-byte in a `finally` block, and ran the final green checks after restoration. These commands use only `internal/plan3test` and `CGO_ENABLED=0`. |
| + |
| +| Guard disabled | Command | Exit | Failure | Restoration | |
| +| --- | --- | --- | --- | --- | |
| +| uncertain-person-choice | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorAcceptance3A/uncertain_requires_person$ -count=1` | 1 | coordinator_acceptance_test.go:47: uncertain turn fenced without person's choice coordinator.fenced | Restored byte-for-byte | |
| +| read-session-epoch | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIReadEpochTransaction$ -count=1` | 1 | coordinator_acceptance_test.go:119: HTTP 200, want 403: {"messages":[],"cards":[],"next_cursor":"","revision":1} | Restored byte-for-byte | |
| +| recency-key | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIRecencyAcrossPages$ -count=1` | 1 | coordinator_acceptance_test.go:92: recency order: got [{ID:a-old Text:a-old Status:confirmed SourceMessageID: Revision:1}] want b-tie | Restored byte-for-byte | |
| +| cursor-principal | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIStreamCursorIsolation$ -count=1` | 1 | HTTP 200 instead of 410 for the other person on a shared thread | Restored byte-for-byte | |
| +| cursor-stream | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIStreamCursorIsolation$ -count=1` | 1 | HTTP 200 instead of 410 for a different stream | Restored byte-for-byte | |
| +| html-cursor-sweep | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestConversationCursorRetention$ -count=1` | 1 | coordinator_acceptance_test.go:165: expired HTML cursors retained | Restored byte-for-byte | |
| +| duplicate-delivery | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorTurnDeliveryAtomic$ -count=1` | 1 | coordinator_test.go:144: team: evidence | Restored byte-for-byte | |
| +| early-success | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorSessionTrustedReceipt$ -count=1` | 1 | coordinator_continuity_test.go:140: delivery accepted before receipt | Restored byte-for-byte | |
| +| release-inventory | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorReleaseNeedsPolicyCertification$ -count=1` | 1 | coordinator_release_test.go:25: old certificate authorized pending coordinator inventory | Restored byte-for-byte | |
| +| release-copy | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorReleaseNeedsPolicyCertification$ -count=1` | 1 | coordinator_release_test.go:39: pending copy authorized release | Restored byte-for-byte | |
| +| inferred-delete-error | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPreferencesInferredDeleteFailure$ -count=1` | 1 | coordinator_acceptance_test.go:222: failed inferred deletion reported success | Restored byte-for-byte | |
| + |
| +### Release and live gate |
| + |
| +Task 11 changes no policy constructor or inventory hash. The merged Plan 2b baseline is `ff73f89`; offline Plan 2b-derived graph, provider and directlive guards pass as recorded above. This run does not assert a Plan 2b live pass. The shared manifest still has zero direct policies, verified isolation tuples, certifications and binary entries, `live_gate_copy_reviewed=false`, and 18 pending action/provider inventory entries. Its coordinator constructor identities remain: |
| + |
| +| Provider/action | Inventory hash | State | |
| +| --- | --- | --- | |
| +| Claude/coordinate | `3289121ba15a78e4ab32bb85828b3518631214be4649de85de46e3d31354de62` | Uncertified | |
| +| Codex/coordinate | `57d95c9e08193d417a63e3e3e045965759d6a0ae27e3a4d7ffeebc65893cde80` | Uncertified | |
| + |
| +These portable inventory hashes are not exact live policy certificates. The driver includes both coordinator profiles. Its current manifest-candidate path deliberately excludes coordinator-only evidence, so the controller must review that promotion path and the full evidence before authorizing coordinator release eligibility. Nothing in this task removes pending policy entries or fills certificates. |
| + |
| +Created `docs/superpowers/plans/LIVE-GATE-plan-3.md`, section `3a`, with the exact later command covering Contract, Isolation, Recovery, Calibration and Coordinator, explicit bounded config checks, all executable profiles, dedicated homes, a disposable repository, three request kinds, cancellation, manual merge and expected evidence. It records the Amadan discussion 7 ruling: Codex coordinator permits the three inert MCP resource tools; the Equipo server has no resources. Created `docs/plan-3-acceptance.md` headed `Draft: pending copy review`. Both documents remain drafts. |
| + |
| +### 3a copy inventory |
| + |
| +All 122 runtime entries below remain individually marked `COPY REVIEW REQUIRED` in `internal/equipo/copy.go`. Compared the pending entries against merged Plan 2b baseline `ff73f89` and attributed their text with git blame. The existing `trial.label` and `task.cancel` annotations were moved beside their unchanged values in Task 9; they are inherited Plan 2b copy, not new Plan 3 entries. Other inherited pending copy is still covered by the global release-copy gate. No entry was marked reviewed and Task 11 adds no runtime string. |
| + |
| +| Key | Draft text | Owning task | |
| +| --- | --- | --- | |
| +| `plan.connection` | Connection | 9 | |
| +| `plan.current_selection` | Current selection | 9 | |
| +| `plan.unselected` | Choose later | 9 | |
| +| `plan.action.scope` | Define scope | 9 | |
| +| `conversation.title` | Conversation | 9 | |
| +| `conversation.empty` | Start a conversation with your coordinator. | 9 | |
| +| `conversation.composer` | Message your coordinator | 9 | |
| +| `conversation.send` | Send message | 9 | |
| +| `conversation.queued` | Message queued | 9 | |
| +| `conversation.offline` | Live updates are paused. Reload to see changes. | 9 | |
| +| `conversation.thread_link` | About this task | 9 | |
| +| `conversation.thread_reply` | Reply about this task | 9 | |
| +| `conversation.route_confirmation` | Add this reply to a task | 9 | |
| +| `conversation.private` | Only you can read this conversation. | 9 | |
| +| `conversation.shared_thread` | Everyone on the team can read this discussion. | 9 | |
| +| `conversation.coordinator` | Coordinator | 9 | |
| +| `conversation.more` | More messages | 9 | |
| +| `coordinator.settings` | Your coordinator | 9 | |
| +| `coordinator.limits` | Coordinator limits | 9 | |
| +| `coordinator.waiting_label` | Waiting for | 9 | |
| +| `plan.revision` | Revision | 9 | |
| +| `plan.approved` | Approved | 9 | |
| +| `plan.required_step` | Required step | 9 | |
| +| `plan.position` | Order | 9 | |
| +| `plan.instructions` | Instructions | 9 | |
| +| `plan.model` | Model | 9 | |
| +| `plan.reason` | Reason for this choice | 9 | |
| +| `plan.remove_step` | Remove step | 9 | |
| +| `plan.add_step` | Add a step | 9 | |
| +| `plan.step_key` | Step name | 9 | |
| +| `plan.specialist` | Specialist | 9 | |
| +| `plan.action` | Action | 9 | |
| +| `plan.approval_settings` | Plan approval | 9 | |
| +| `plan.personal_override` | Your approval setting | 9 | |
| +| `plan.custom` | Custom plan | 9 | |
| +| `question.choose` | Choose an answer | 9 | |
| +| `question.reply` | Your reply | 9 | |
| +| `question.superseded` | Replaced by a newer question | 9 | |
| +| `question.cancelled` | Cancelled | 9 | |
| +| `settings.landing` | Open this page when you sign in | 9 | |
| +| `plan.action.reproduce` | Reproduce | 9 | |
| +| `plan.action.implement` | Implement | 9 | |
| +| `plan.action.review` | Independent review | 9 | |
| +| `plan.action.checks` | Run checks | 9 | |
| +| `plan.action.publish` | Publish review branch | 9 | |
| +| `plan.action.person` | Person approval | 9 | |
| +| `plan.action.investigate` | Investigate | 9 | |
| +| `plan.action.recommend` | Recommend | 9 | |
| +| `plan.action.copy` | Write copy | 9 | |
| +| `plan.action.design` | Design | 9 | |
| +| `preferences.title` | Preferences | 8 | |
| +| `preferences.confirmed` | Confirmed | 8 | |
| +| `preferences.inferred` | Inferred | 8 | |
| +| `preferences.source` | Source message | 8 | |
| +| `preferences.confirm` | Confirm | 8 | |
| +| `preferences.correct` | Correct | 8 | |
| +| `preferences.delete` | Delete | 8 | |
| +| `preferences.team_rule` | Team rules take precedence. Preferences guide instructions but cannot grant approval, spending or account access. | 8 | |
| +| `preferences.source_unavailable` | Source message unavailable | 8 | |
| +| `coordinator.tool.read_project` | Read the project material this connection may use. | 6 | |
| +| `coordinator.tool.read_task` | Read a task in an allowed project. | 6 | |
| +| `coordinator.tool.propose_plan` | Propose a plan for the current message. Ask which project if it is unclear. | 6 | |
| +| `coordinator.tool.ask_person` | Ask your person a question for a later turn. | 6 | |
| +| `coordinator.tool.route_to_task` | Link the current message to a task requested by your person. | 6 | |
| +| `coordinator.tool.post_message` | Post a message with references to its sources. | 6 | |
| +| `coordinator.tool.suggest_preference` | Suggest a preference for your person to review. | 6 | |
| +| `coordinator.tool.suggest_specialist` | Suggest a specialist for your person to review. | 6 | |
| +| `coordinator.tool.suggest_playbook` | Suggest a playbook for your person to review. | 6 | |
| +| `coordinator.project_question` | Which project is this for? | 6 | |
| +| `conversation.routed` | Reply added to the task thread. | 1 | |
| +| `coordinator.connection` | Coordinator connection | 5 | |
| +| `coordinator.unavailable` | Your coordinator is unavailable. | 5 | |
| +| `coordinator.budget_needed` | Ask a team owner to set coordinator limits. | 5 | |
| +| `coordinator.queued` | Waiting for your coordinator | 5 | |
| +| `coordinator.uncertain` | This turn was interrupted. Its result is unknown. | 5 | |
| +| `coordinator.retry` | Try this turn again | 5 | |
| +| `coordinator.reset` | Reset coordinator | 5 | |
| +| `coordinator.waiting_connection` | Waiting for your connection | 5 | |
| +| `coordinator.waiting_task` | Waiting for %s | 7 | |
| +| `coordinator.context_unavailable` | Your coordinator can no longer use a source for this request. Reset your coordinator or retry after access is restored. | 7 | |
| +| `coordinator.context_limit` | The required context is too long for this turn. Reset your coordinator or retry. | 7 | |
| +| `tool.acceptance` | Submit acceptance tests for the requested behaviour. Encode file bytes as base64. Reuse the request ID only for an identical retry. | 4 | |
| +| `tool.answer` | Submit an answer with references to the supplied source snapshots. Reuse the request ID only for an identical retry. | 4 | |
| +| `tool.render` | Request a trusted render of the submitted candidate commit. Reuse the request ID only for an identical retry. | 4 | |
| +| `evidence.acceptance` | Acceptance tests | 3 | |
| +| `evidence.frozen` | Acceptance tests are frozen. | 3 | |
| +| `evidence.render_approval` | Review the change | 3 | |
| +| `evidence.sources` | Sources | 3 | |
| +| `evidence.answer_delivered` | Answer delivered | 3 | |
| +| `evidence.missing_sources` | Add sources for this answer. | 3 | |
| +| `evidence.awaiting_person` | Waiting for the decision owner | 3 | |
| +| `evidence.candidate_changed` | The change has been updated. Review it again. | 3 | |
| +| `evidence.approve` | Approve this change | 3 | |
| +| `evidence.render_aid` | Approve the changes below. Use the image to help review them. | 3 | |
| +| `evidence.before` | Before | 3 | |
| +| `evidence.after` | After | 3 | |
| +| `evidence.approved` | Approved | 3 | |
| +| `plan.proposed` | Proposed plan | 2 | |
| +| `plan.edit` | Edit plan | 2 | |
| +| `plan.approve` | Approve plan | 2 | |
| +| `plan.immediate` | Start straight away | 2 | |
| +| `plan.required` | Wait for approval | 2 | |
| +| `plan.inherit` | Use the project setting | 2 | |
| +| `plan.locked_step` | This step has started and cannot be changed. | 2 | |
| +| `plan.revision_conflict` | The plan has changed. Open the latest version. | 2 | |
| +| `plan.project` | Project | 2 | |
| +| `plan.correct_project` | Correct project | 2 | |
| +| `plan.replacement` | Replacement task | 2 | |
| +| `plan.investigation_checkpoint` | Review the findings before planning more work. | 2 | |
| +| `plan.playbook` | Playbook | 2 | |
| +| `plan.changes` | Plan changes | 2 | |
| +| `task.state.proposed` | Proposed | 2 | |
| +| `api.unauthenticated` | Sign in to continue. | 10 | |
| +| `api.forbidden` | You cannot do that with your current access. | 10 | |
| +| `api.not_found` | This item is not available. | 10 | |
| +| `api.method_not_allowed` | This action is not available here. | 10 | |
| +| `api.precondition_required` | Send the request key and current revision. | 10 | |
| +| `api.revision_conflict` | This item changed. Fetch its current revision and try again. | 10 | |
| +| `api.invalid_input` | Check the request fields and try again. | 10 | |
| +| `api.cursor_expired` | This page link expired. Fetch the list again. | 10 | |
| +| `api.unavailable` | This information is unavailable. Try again later. | 10 | |
| +| `conversation.cursor_expired` | This conversation page has expired. Open the conversation again. | 1 | |
| + |
| +Pending document copy is separate from runtime keys: |
| + |
| +| Artifact/key | Draft text | Owning task | |
| +| --- | --- | --- | |
| +| OpenAPI `info.title` | Equipo person API | 10 | |
| +| OpenAPI response descriptions | OK; stable error code identifiers (`unauthenticated`, `forbidden`, `not_found`, `method_not_allowed`, `precondition_required`, `revision_conflict`, `invalid_input`, `cursor_expired`, `unavailable`) | 10 | |
| +| `docs/plan-3-acceptance.md` | Full draft at the named file, headed “Draft: pending copy review” | 11 | |
| +| `docs/superpowers/plans/LIVE-GATE-plan-3.md` | Full 3a script, prompts and checklist at the named file, headed “Draft: pending copy review” | 11 | |
| + |
| +### Self-review and remaining limits |
| + |
| +Reviewed authority-before-replay, read-transaction membership/epoch checks, wrong-principal and wrong-stream cursors, recency ties and deleted items, containment and generation changes, completion receipts, cancellation, pending-copy eligibility and the release boundary. Existing targeted tests cover the unchanged privacy and authority paths. The false-positive release and HTTP fixture setup failures were corrected; none is counted as behavioral red evidence. |
| + |
| +The generic API lists still build current authorized projections and collect their audit timestamps before applying the keyset in memory. This change restores order and avoids cursor rows; it does not add database-level pagination. Editing a resource can move it ahead of an existing cursor, so the draft guide tells the reader to restart the list for current order. HTML cursor reclamation runs on fresh page reads, not on a background schedule. Live provider compatibility, live coordinator certification and reviewed copy remain the release blockers. |
| + |
| +Commit subject: `test: verify the coordinator conversation acceptance flow`. |
| +Required author: `codex <codex~paul@keymail.dev>`. No push. |
| + |
| +Final supplemental checks: `CGO_ENABLED=0 go test ./internal/runner -run '^Test(CertifiedRefreshRuntimePolicy|PolicyHashIndependentOfReleaseManifest|RuntimeMountsStandaloneToolProxy|CertifiedNetworkConflictDiagnostic)$' -count=1` exited 0 (0.403s). `bash -n` accepted the extracted future live script without executing it. Both reports contain the identical 122-row copy table, and the previous controller-report bytes remain unchanged. |
| + |
| +### 3a usable stop |
| + |
| +| Gate | State | |
| +| --- | --- | |
| +| Offline implementation and acceptance | PASS, targeted gates above | |
| +| Copy | PENDING, 122 new runtime entries plus draft documents and inherited pending copy | |
| +| Live certification and Paul's usable acceptance | NOT RUN; follow LIVE-GATE-plan-3.md section 3a after controller review | |
| +| Production release | DISABLED pending the copy and live gates | |
diff --git a/docs/superpowers/plans/LIVE-GATE-plan-3.md b/docs/superpowers/plans/LIVE-GATE-plan-3.md| new file mode 100644 |
| index 00000000..3ee562dc |
| --- /dev/null |
| +++ b/docs/superpowers/plans/LIVE-GATE-plan-3.md |
| @@ -0,0 +1,142 @@ |
| +# Draft: pending copy review |
| + |
| +## 3a |
| + |
| +Paul runs this gate after the controller has reviewed the offline results and |
| +copy. Task 11 did not run it. Keep the release disabled until the reviewed live |
| +bundle and the usable checks below pass. Fixtures cannot certify a production |
| +provider, model, account or policy. |
| + |
| +Use Linux/amd64, the enrolled runner, Paul's existing dedicated Equipo Claude |
| +and Codex homes, and a disposable repository. Use the configuration and identity |
| +file shapes in [the direct live guide](../../live-gate.md). Supply actual account |
| +IDs, home IDs, model names, auth hosts, executable paths and machine fingerprint. |
| +Do not copy interactive credentials, create a shared login, or put credentials |
| +in the evidence. This pass needs no new sign-in or enrolment. |
| + |
| +Before running: |
| + |
| +- Finish the Plan 2b release gate. Its checked-in manifest still has no certified |
| + tuples, binary digests or evidence references. A passing fixture is insufficient. |
| +- Review the `3a copy inventory` in `CONTROLLER-REPORT-plan-3.md`, the API schema |
| + prose and both Task 11 draft documents. Leave pending entries marked until Paul |
| + approves them through the controller's review channel. |
| +- Select `.equipo/checks.json` and a small reproducible defect in the disposable |
| + repository. Record its default branch and starting commit. Record an acceptance |
| + test for a small feature and a project document to cite in a recommendation. |
| +- Confirm separate, positive call, input-token, output-token and duration limits |
| + in the private `DirectLiveConfig`. Record job funding and remaining project/team |
| + headroom. Set `Seconds` to at most 3600 for this run. Stop when the chosen bound |
| + is reached. Never raise it automatically. The verifier calculates twice the |
| + measured maximum, rounded up to 1,000, and checks the 23-reservation job floor. |
| +- Confirm that `EQUIPO_LIVE_CONFIG` names that private file, `disposable` is true, |
| + both selected homes belong to Paul, and `evidence_dir` is a new empty directory |
| + outside scratch. Preserve that directory after the run. Configure the required |
| + sentinels and protected paths from the direct live guide. |
| +- Export the reviewed runner path variables from the direct live guide. Choose |
| + the intended installation paths for `EQUIPO_TOOL_PROXY_PATH` and |
| + `EQUIPO_RUNNER_EXECUTABLE`; they must not overwrite a running installation. |
| + Certification binds the constructed policy and installed binaries. |
| + |
| +Run this script from the reviewed `plan-3` checkout. It uses the existing |
| +`directlive` driver once and verifies all five groups, including both coordinator |
| +profiles. It does not enable instance execution or promote a manifest. |
| + |
| +```bash |
| +#!/usr/bin/env bash |
| +set -euo pipefail |
| +umask 077 |
| +: "${TMPDIR:?Set on-disk TMPDIR}" |
| +: "${EQUIPO_LIVE_CONFIG:?Set the reviewed private config file}" |
| +: "${EQUIPO_CLAUDE_PATH:?Set the pinned Claude executable}" |
| +: "${EQUIPO_CODEX_PATH:?Set the pinned Codex executable}" |
| +: "${EQUIPO_CODEX_CODE_MODE_HOST_PATH:?Set the pinned code-mode host}" |
| +: "${EQUIPO_BWRAP_PATH:?Set bubblewrap 0.11.0}" |
| +: "${EQUIPO_TOOL_PROXY_PATH:?Set the intended helper installation path}" |
| +: "${EQUIPO_RUNNER_EXECUTABLE:?Set the intended runner installation path}" |
| +: "${EQUIPO_RUNNER_STATE_DIR:?Set private runner state}" |
| +: "${EQUIPO_ACCOUNT_BINDINGS_PATH:?Set private account bindings}" |
| +: "${EQUIPO_AMADAN_CREDENTIAL_PATH:?Set the private forge credential path}" |
| +: "${EQUIPO_WORKSPACE_ROOT:?Set the workspace root}" |
| +: "${EQUIPO_SCRATCH_ROOT:?Set on-disk runner scratch}" |
| + |
| +python3 - <<'PY' |
| +import json, os |
| +from pathlib import Path |
| +c = json.loads(Path(os.environ['EQUIPO_LIVE_CONFIG']).read_text()) |
| +assert c['disposable'] is True |
| +assert 0 < c['funding']['Seconds'] <= 3600 |
| +assert {b['binding']['Provider'] for b in c['bindings']} == {'claude', 'codex'} |
| +evidence = Path(c['evidence_dir']) |
| +assert evidence.is_absolute() and evidence.is_dir() and not any(evidence.iterdir()) |
| +assert Path(c['repository'], '.git').is_dir() |
| +PY |
| + |
| +read -r -p 'Type LIVE DISPOSABLE ONLY: ' equipo_confirmation |
| +[[ "$equipo_confirmation" == 'LIVE DISPOSABLE ONLY' ]] |
| +read -r -p 'Type RUN LIVE GATE: ' equipo_confirmation |
| +[[ "$equipo_confirmation" == 'RUN LIVE GATE' ]] |
| + |
| +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -buildvcs=false \ |
| + -ldflags '-s -w' -o "$EQUIPO_TOOL_PROXY_PATH" ./cmd/equipo-tool-proxy |
| +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags direct_live -trimpath \ |
| + -buildvcs=false -ldflags '-s -w' -o "$EQUIPO_RUNNER_EXECUTABLE" ./cmd/equipo-runner |
| +EQUIPO_LIVE_DIRECT=1 CGO_ENABLED=0 go test -tags direct_live \ |
| + ./internal/runner/provider \ |
| + -run '^TestDirectLive(Contract|Isolation|Recovery|Calibration|Coordinator)$' \ |
| + -count=1 -timeout=70m |
| +``` |
| + |
| +The bounded driver runs the Engineering implementation and reproduction, Review, |
| +legacy Product, Scope, Research, Investigation, Copy, Design and Coordinator |
| +profiles for Claude. It runs the same profiles except legacy Product for Codex. |
| +This covers the new executable actions `scope`, `recommend`, `investigate`, |
| +`copy`, `design` and `coordinate`, as well as the changed policies for existing |
| +actions. `research` shares the Research profile. Every configured model needs its |
| +own reviewed run and fresh evidence directory. |
| + |
| +For each exact tuple, retain the configuration hash, provider/launcher/bwrap |
| +versions, policy hash, executable digests, account and home identity, model, |
| +tool inventory, sanitized captures, bounded usage and funding, and the |
| +`index.json` and per-tuple `certification.json` files. Every assertion must name |
| +an artifact and its digest. Missing observations stay uncertified. Check refresh, |
| +readback, durable replay, no automatic redispatch, active cancellation and absence |
| +of surviving descendants. A failure in one tuple cannot authorize it through a |
| +passing tuple from the other provider. |
| + |
| +The Codex coordinator profile includes three inert MCP resource tools by |
| +controller ruling, Amadan discussion 7: `list_mcp_resources`, |
| +`list_mcp_resource_templates`, and `read_mcp_resource`. Its only MCP server |
| +exposes no resources. Require those tools plus the scoped Equipo coordinator |
| +tools, with no shell, file, search, image or delegation capability. Claude has no |
| +native-tool exception. Record an actual structured question and its answer for |
| +both coordinator profiles. |
| + |
| +The current `ManifestCandidate` deliberately excludes coordinator-only evidence. |
| +Do not treat its specialist candidate as coordinator release approval. The |
| +controller must review complete coordinator evidence and the release promotion |
| +path before removing the corresponding `uncertified_policies` entries. Keep |
| +`ActionCertified` false for any pending action. No handwritten certificate or |
| +fixture digest can replace live evidence. |
| + |
| +After certification and human release approval, Paul installs a versioned release |
| +and explicitly enables execution for the disposable instance. Use two fixture |
| +people in separate browser sessions and manual personal connection choices: |
| + |
| +| Check | Paul does | Expected evidence | |
| +| --- | --- | --- | |
| +| Bug | Send “Fix the failing test in the disposable project.” Choose the project when asked, inspect and approve the plan. | One task and thread, frozen reproduction, candidate commit, review from a family independent of every retained builder, checks on that exact candidate, review-branch head and description readback. | |
| +| Feature | Send “Add the small feature described in the acceptance document.” Edit a future step and correct the project before it starts. Approve the current plan. | Revision conflict for a stale edit, unchanged started steps, frozen acceptance, exact candidate review/checks, publication readback. | |
| +| Recommendation | Send “Recommend one improvement and cite the project document.” Choose one permitted family. | One answer with source IDs, revisions and content hashes. No branch or pretend software-fix evidence. | |
| +| Question and thread | Answer a current question, then explicitly route a private reply to the task thread. Read it as the other person. | One answer effect, one routed reply, shared discussion visible to both, private history and preferences isolated. | |
| +| Preference | Confirm, correct and delete a preference, then start a fresh turn. | Only the current confirmed value enters instructions. Team rules and authority remain unchanged. | |
| +| Interrupted turn | Stop the runner during one admitted coordinator turn, then restart it. | No duplicate task, turn, tool effect or delivery. Unknown usage remains charged. A contained uncertain turn blocks its queue until Paul explicitly chooses retry or reset. | |
| +| Cancel | Cancel active work, wait for containment, then inspect its state. | Cancellation acknowledgement, no new work for the cancelled attempt, no surviving process or retained account lease. | |
| +| Manual merge | Inspect the published branch, diff, review and checks. Merge it personally, then acknowledge the merge in Equipo. | The app waits for the decision owner. Before Paul's merge the default branch has not moved. Record the merge commit and acknowledgement. | |
| + |
| +Record the run ID, release commit/version, task IDs, plan revisions, actual |
| +provider families and accounts, candidate/review/check hashes, readback records, |
| +question and cancellation outcomes, and Paul's merge reference in the controller |
| +report. Stop the disposable instance and runner, verify that their children have |
| +exited, and remove only scratch created for this run. Preserve the private evidence |
| +bundle and the dedicated homes. Do not publish secrets or sign-in links. |
diff --git a/internal/equipo/conversation/coordinator_refusal.go b/internal/equipo/conversation/coordinator_refusal.go| index 09d91b31..fb6b75c7 100644 |
| --- a/internal/equipo/conversation/coordinator_refusal.go |
| +++ b/internal/equipo/conversation/coordinator_refusal.go |
| @@ -26,7 +26,7 @@ func (e *Engine) coordinatorRefusal(ctx context.Context, p RunnerPrincipal, id s |
| if err := tx.First(&b, "id=? AND person=?", row.BindingID, p.Person).Error; err != nil { |
| return err |
| } |
| - if row.State == "delivered" { |
| + if row.State == "delivered" || row.State == "uncertain" && b.Generation == row.Generation { |
| return nil |
| } |
| if row.State != "uncertain" && row.State != "superseded" && row.State != "fenced" && b.Generation == row.Generation { |
diff --git a/internal/equipo/conversation/handlers.go b/internal/equipo/conversation/handlers.go| index 3f9d8c26..4a636cea 100644 |
| --- a/internal/equipo/conversation/handlers.go |
| +++ b/internal/equipo/conversation/handlers.go |
| @@ -69,7 +69,7 @@ func (h *Handler) Send(w http.ResponseWriter, r *http.Request) { |
| if task != "" { |
| path = "/tasks/" + url.PathEscape(task) + "/thread" |
| } |
| - http.Redirect(w, r, path, 303) |
| + http.Redirect(w, r, path, http.StatusSeeOther) |
| } |
| func (h *Handler) Route(w http.ResponseWriter, r *http.Request) { |
| a, ok := h.actor(w, r) |
| @@ -84,7 +84,7 @@ func (h *Handler) Route(w http.ResponseWriter, r *http.Request) { |
| h.Failure(w, r, err) |
| return |
| } |
| - http.Redirect(w, r, "/conversation", 303) |
| + http.Redirect(w, r, "/conversation", http.StatusSeeOther) |
| } |
| func (h *Handler) Answer(w http.ResponseWriter, r *http.Request) { |
| a, ok := h.actor(w, r) |
| @@ -99,5 +99,5 @@ func (h *Handler) Answer(w http.ResponseWriter, r *http.Request) { |
| h.Failure(w, r, err) |
| return |
| } |
| - http.Redirect(w, r, "/conversation", 303) |
| + http.Redirect(w, r, "/conversation", http.StatusSeeOther) |
| } |
diff --git a/internal/equipo/conversation/preferences.go b/internal/equipo/conversation/preferences.go| index f064aa72..bc331b0e 100644 |
| --- a/internal/equipo/conversation/preferences.go |
| +++ b/internal/equipo/conversation/preferences.go |
| @@ -199,9 +199,9 @@ func (s *Store) DeletePreference(actor Actor, id string, m Mutation) error { |
| row.Revision++ |
| row.Text = "" |
| if !exists { |
| - source, err := s.preferenceSource(main, row.SourceMessageID) |
| - if err != nil { |
| - return err |
| + source, sourceErr := s.preferenceSource(main, row.SourceMessageID) |
| + if sourceErr != nil { |
| + return sourceErr |
| } |
| row.SourceRevision = source.Revision |
| err = s.tx.Create(&row).Error |
diff --git a/internal/equipo/conversation/settings.go b/internal/equipo/conversation/settings.go| index 43b0cbee..a33feadf 100644 |
| --- a/internal/equipo/conversation/settings.go |
| +++ b/internal/equipo/conversation/settings.go |
| @@ -140,5 +140,5 @@ func (h *Handler) SaveSettings(w http.ResponseWriter, r *http.Request) { |
| h.Failure(w, r, err) |
| return |
| } |
| - http.Redirect(w, r, "/settings/coordinator", 303) |
| + http.Redirect(w, r, "/settings/coordinator", http.StatusSeeOther) |
| } |
diff --git a/internal/equipo/conversation/store.go b/internal/equipo/conversation/store.go| index 52e048e8..0f93a933 100644 |
| --- a/internal/equipo/conversation/store.go |
| +++ b/internal/equipo/conversation/store.go |
| @@ -186,6 +186,11 @@ func (s *Store) pageAfter(actor kernel.Actor, stream string, through, revision i |
| if limit < 1 || limit > 100 { |
| return page, s.deps.Invalid |
| } |
| + if !s.readOnly && cursor == "" { |
| + if err := s.tx.Where("expires_at <= ?", time.Now().UTC()).Delete(&cursorRecord{}).Error; err != nil { |
| + return page, err |
| + } |
| + } |
| if cursor != "" && s.readOnly { |
| var c cursorRecord |
| if err := s.cursorCodec.Open(actor.Address+"\x00stream:"+stream, cursor, &c); err != nil { |
diff --git a/internal/equipo/personapi/auth.go b/internal/equipo/personapi/auth.go| index 5a6d4087..549bc563 100644 |
| --- a/internal/equipo/personapi/auth.go |
| +++ b/internal/equipo/personapi/auth.go |
| @@ -138,3 +138,8 @@ func PrincipalFrom(ctx context.Context) (PersonPrincipal, bool) { |
| func DenyPersonBearer(context.Context, string) (PersonPrincipal, error) { |
| return PersonPrincipal{}, ErrUnauthenticated |
| } |
| + |
| +func CurrentSession(ctx context.Context, address string, epoch int64) bool { |
| + p, ok := PrincipalFrom(ctx) |
| + return !ok || p.Address == address && p.SessionEpoch >= epoch |
| +} |
diff --git a/internal/equipo/personapi/list_order.go b/internal/equipo/personapi/list_order.go| new file mode 100644 |
| index 00000000..8a293db4 |
| --- /dev/null |
| +++ b/internal/equipo/personapi/list_order.go |
| @@ -0,0 +1,57 @@ |
| +package personapi |
| + |
| +import ( |
| + "context" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// orderedItems retains server-owned sort keys without adding them to API projections. |
| +type orderedItems struct { |
| + Values any |
| + Positions map[string]listPosition |
| +} |
| +type listPosition struct { |
| + At time.Time |
| + ID string |
| +} |
| + |
| +func (p listPosition) before(q listPosition) bool { |
| + if !p.At.Equal(q.At) { |
| + return p.At.After(q.At) |
| + } |
| + return p.ID < q.ID |
| +} |
| + |
| +// Resource audit times include edits as well as creation. IDs break timestamp |
| +// ties; resources predating audit history sort last in a deterministic order. |
| +func (s *Reader) order(ctx context.Context, a kernel.Actor, values any, resources map[string]string) (orderedItems, error) { |
| + out := orderedItems{Values: values, Positions: map[string]listPosition{}} |
| + ids := make([]string, 0, len(resources)) |
| + for id, resource := range resources { |
| + ids = append(ids, resource) |
| + out.Positions[id] = listPosition{ID: id} |
| + } |
| + err := s.ReadTeam(ctx, a, func(tx *gorm.DB, _ Team) error { |
| + var rows []struct { |
| + RecordID string |
| + At time.Time |
| + } |
| + if err := tx.Table("audit_events").Select("record_id,at").Where("record_id IN ?", ids).Order("at").Find(&rows).Error; err != nil { |
| + return err |
| + } |
| + times := map[string]time.Time{} |
| + for _, row := range rows { |
| + if row.At.After(times[row.RecordID]) { |
| + times[row.RecordID] = row.At.UTC() |
| + } |
| + } |
| + for id, resource := range resources { |
| + out.Positions[id] = listPosition{At: times[resource], ID: id} |
| + } |
| + return nil |
| + }) |
| + return out, err |
| +} |
diff --git a/internal/equipo/personapi/reads.go b/internal/equipo/personapi/reads.go| index f561e5e7..4bd0152c 100644 |
| --- a/internal/equipo/personapi/reads.go |
| +++ b/internal/equipo/personapi/reads.go |
| @@ -53,7 +53,12 @@ func (s *Reader) Read(ctx context.Context, a kernel.Actor, op, id, cursor string |
| for _, p := range prefs { |
| items = append(items, ProjectPreference(p)) |
| } |
| - return Result{Value: items}, nil |
| + resources := map[string]string{} |
| + for _, item := range items { |
| + resources[item.ID] = item.ID |
| + } |
| + ordered, err := s.order(ctx, a, items, resources) |
| + return Result{Value: ordered}, err |
| case "settings": |
| v, err := s.Conversation.PersonalSettings(ctx, a) |
| return Result{Settings{v.Landing, v.Revision}, v.Revision}, err |
| @@ -124,7 +129,12 @@ func (s *Reader) Read(ctx context.Context, a kernel.Actor, op, id, cursor string |
| items = append(items, apiTask(v)) |
| } |
| } |
| - return Result{Value: items}, nil |
| + resources := map[string]string{} |
| + for _, item := range items { |
| + resources[item.ID] = item.ID |
| + } |
| + ordered, err := s.order(ctx, a, items, resources) |
| + return Result{Value: ordered}, err |
| case "cards", "card": |
| cards, err := s.Conversation.ConversationCards(ctx, a) |
| if err != nil { |
| @@ -140,7 +150,12 @@ func (s *Reader) Read(ctx context.Context, a kernel.Actor, op, id, cursor string |
| if op == "card" { |
| return Result{}, s.NotFound |
| } |
| - return Result{Value: out}, nil |
| + resources := map[string]string{} |
| + for _, item := range out { |
| + resources[item.ID] = item.ResourceID |
| + } |
| + ordered, err := s.order(ctx, a, out, resources) |
| + return Result{Value: ordered}, err |
| case "question": |
| return s.question(ctx, a, id) |
| case "coordinator": |
diff --git a/internal/equipo/personapi/requests.go b/internal/equipo/personapi/requests.go| index 10cc0b72..c3afd2e8 100644 |
| --- a/internal/equipo/personapi/requests.go |
| +++ b/internal/equipo/personapi/requests.go |
| @@ -111,7 +111,12 @@ func Revision(v any) int64 { |
| } |
| func Paginate(codec kernel.CursorCodec, principal, scope, cursor string, limit int, in Result, expired error) (Result, error) { |
| var items []json.RawMessage |
| - raw, err := json.Marshal(in.Value) |
| + values := in.Value |
| + positions := map[string]listPosition{} |
| + if ordered, ok := values.(orderedItems); ok { |
| + values, positions = ordered.Values, ordered.Positions |
| + } |
| + raw, err := json.Marshal(values) |
| if err != nil { |
| return Result{}, err |
| } |
| @@ -122,7 +127,7 @@ func Paginate(codec kernel.CursorCodec, principal, scope, cursor string, limit i |
| items = []json.RawMessage{} |
| } |
| type entry struct { |
| - key string |
| + key listPosition |
| value json.RawMessage |
| } |
| entries := make([]entry, 0, len(items)) |
| @@ -141,11 +146,13 @@ func Paginate(codec kernel.CursorCodec, principal, scope, cursor string, limit i |
| if k == "" { |
| return Result{}, errors.New("missing pagination key") |
| } |
| - entries = append(entries, entry{k, item}) |
| + position := positions[k] |
| + position.ID = k |
| + entries = append(entries, entry{position, item}) |
| } |
| - sort.Slice(entries, func(i, j int) bool { return entries[i].key < entries[j].key }) |
| + sort.Slice(entries, func(i, j int) bool { return entries[i].key.before(entries[j].key) }) |
| binding := principal + "\x00" + scope |
| - var after string |
| + var after listPosition |
| if cursor != "" { |
| if err = codec.Open(binding, cursor, &after); err != nil { |
| return Result{}, expired |
| @@ -153,11 +160,11 @@ func Paginate(codec kernel.CursorCodec, principal, scope, cursor string, limit i |
| } |
| revision := in.Revision |
| if revision < 1 { |
| - revision = Revision(in.Value) |
| + revision = Revision(values) |
| } |
| out := Page[json.RawMessage]{Items: []json.RawMessage{}, Revision: revision} |
| for i, e := range entries { |
| - if e.key <= after { |
| + if cursor != "" && !after.before(e.key) { |
| continue |
| } |
| out.Items = append(out.Items, e.value) |
diff --git a/internal/equipo/planning/handlers.go b/internal/equipo/planning/handlers.go| index d314ac8c..1dcac6f0 100644 |
| --- a/internal/equipo/planning/handlers.go |
| +++ b/internal/equipo/planning/handlers.go |
| @@ -69,7 +69,7 @@ func (h *Handler) finish(w http.ResponseWriter, r *http.Request, id string, err |
| h.Failure(w, r, err) |
| return |
| } |
| - http.Redirect(w, r, "/tasks/"+url.PathEscape(id)+"/plan", 303) |
| + http.Redirect(w, r, "/tasks/"+url.PathEscape(id)+"/plan", http.StatusSeeOther) |
| } |
| func (h *Handler) Edit(w http.ResponseWriter, r *http.Request) { |
| a, ok := h.actor(w, r) |
diff --git a/internal/equipo/task_views.go b/internal/equipo/task_views.go| index 93a9a57e..8b4cc637 100644 |
| --- a/internal/equipo/task_views.go |
| +++ b/internal/equipo/task_views.go |
| @@ -8,6 +8,7 @@ import ( |
| "strings" |
| "time" |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| @@ -25,8 +26,10 @@ type SpecialistWorkView = planning.SpecialistWorkView |
| func (s *Store) readTeam(ctx context.Context, actor Actor, fn func(*gorm.DB, Team) error) error { |
| return storeErrorRead(s.db.G.WithContext(ctx).Clauses(dbresolver.Read).Transaction(func(tx *gorm.DB) error { |
| - if _, err := currentRunnerMember(tx, actor.Address); err != nil { |
| + if member, err := currentRunnerMember(tx, actor.Address); err != nil { |
| return err |
| + } else if !personapi.CurrentSession(ctx, member.Address, member.SessionEpoch) { |
| + return ErrForbidden |
| } |
| var instance Team |
| if err := tx.Order("id").First(&instance).Error; err != nil { |
diff --git a/internal/plan3test/coordinator_acceptance_http_test.go b/internal/plan3test/coordinator_acceptance_http_test.go| new file mode 100644 |
| index 00000000..03d6ff51 |
| --- /dev/null |
| +++ b/internal/plan3test/coordinator_acceptance_http_test.go |
| @@ -0,0 +1,313 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/coordinator" |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| +) |
| + |
| +// Only provider I/O and containment are simulated. Requests cross the HTTP |
| +// handlers, real application transactions, runner journal and tool broker. |
| +func acceptanceHTTP(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + apiRouter(t, f, nil) |
| + validators := runnerproto.ReportValidators(runnerproto.ReportErrors{Invalid: equipo.ErrInvalid, Forbidden: equipo.ErrForbidden, Conflict: equipo.ErrConflict}, nil) |
| + validators.Containment = func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil } |
| + x.SetRunnerValidators(validators) |
| + h := runnerproto.Handler{Execution: func() runnerproto.ExecutionAPI { return x }, AuthenticateRunner: func(context.Context, string) (runnerproto.RunnerPrincipal, error) { return p, nil }, JSON: func(w http.ResponseWriter, status int, v any) { |
| + w.WriteHeader(status) |
| + raw, err := runnerproto.Marshal(v) |
| + if err != nil { |
| + t.Error(err) |
| + } |
| + _, _ = w.Write(raw) |
| + }, Failure: func(w http.ResponseWriter, err error) { |
| + t.Log("runner refusal", err) |
| + http.Error(w, err.Error(), http.StatusConflict) |
| + }, Invalid: equipo.ErrInvalid, Forbidden: equipo.ErrForbidden, Unavailable: equipo.ErrUnavailable} |
| + mux := http.NewServeMux() |
| + mux.Handle("/coordinator/", h.Router()) |
| + mux.Handle("/", f.Handler) |
| + server := httptest.NewServer(mux) |
| + t.Cleanup(server.Close) |
| + request := func(actor equipo.Actor, method, path, body, key, rev string) *httptest.ResponseRecorder { |
| + req, err := http.NewRequest(method, server.URL+path, strings.NewReader(body)) |
| + must(t, err) |
| + req.AddCookie(f.Cookies[actor.Address]) |
| + req.Header.Set("Origin", origin) |
| + req.Header.Set("Content-Type", "application/json") |
| + if key != "" { |
| + req.Header.Set("Idempotency-Key", key) |
| + } |
| + if rev != "" { |
| + req.Header.Set("If-Match", rev) |
| + } |
| + res, err := server.Client().Do(req) |
| + must(t, err) |
| + defer res.Body.Close() |
| + raw, err := io.ReadAll(res.Body) |
| + must(t, err) |
| + w := httptest.NewRecorder() |
| + w.WriteHeader(res.StatusCode) |
| + _, err = w.Write(raw) |
| + must(t, err) |
| + expectHTTP(t, w, 200) |
| + return w |
| + } |
| + for _, a := range []equipo.Actor{owner, peer} { |
| + request(a, "GET", "/api/v1/me", "", "", "") |
| + } |
| + request(peer, "POST", "/api/v1/conversation/messages", `{"body":"peer private request"}`, "peer", "") |
| + var project int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) |
| + var second equipo.Project |
| + must(t, f.DB.G.First(&second, project).Error) |
| + second.ID = 0 |
| + second.Name = "other fixture" |
| + second.Repository = "amadan.net/test/other" |
| + must(t, f.DB.G.Create(&second).Error) |
| + must(t, f.DB.G.Create(&equipo.DecisionOwner{ProjectID: second.ID, Decision: "merge", Address: owner.Address}).Error) |
| + f.exec(t, `INSERT INTO connection_choices(person,project_id,revision,connection_ids_json,pinned_id) VALUES(?,?,1,'["claude","codex"]','claude')`, owner.Address, second.ID) |
| + budget, err := f.Store.Budgets(ctx) |
| + must(t, err) |
| + budget.Projects[team.ProjectID(second.ID)] = budget.Projects[team.ProjectID(project)] |
| + must(t, f.Store.SaveBudgets(ctx, owner, budget)) |
| + journalPath := filepath.Join(t.TempDir(), "runner", "journal.db") |
| + j, err := runner.OpenJournal(ctx, journalPath) |
| + must(t, err) |
| + t.Cleanup(func() { _ = j.Close() }) |
| + l := &acceptanceLauncher{journal: j} |
| + api, err := runner.NewHTTPInstance(server.URL, j, runnerproto.RunnerCredential{Token: "fixture", ExpiresAt: time.Now().Add(time.Hour)}) |
| + must(t, err) |
| + service := &runner.CoordinatorService{Journal: j, API: api, Launchers: map[string]provider.Launcher{"claude": l}} |
| + service.Contain = func(_ context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { |
| + return runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle, Version: 2, CheckedAt: time.Now()}, nil |
| + } |
| + service.OpenLaunch = func(ctx context.Context, c runnerproto.CoordinatorClaim, proxy *runner.ToolProxy) (provider.Launch, func() error, error) { |
| + l.proxy = proxy |
| + l.claim = c |
| + v := provider.Launch{AttemptKey: c.Turn.ID, Binding: provider.Binding{Provider: "claude", AccountID: c.Brief.Selection.AccountID, Expected: provider.Identity{ProviderVersion: "2.1.312"}}, Selection: provider.Selection{Provider: "claude", Family: "claude", AccountID: c.Brief.Selection.AccountID, Model: c.Brief.Selection.Model}, Policy: provider.Policy{Hash: "fixture-policy", Manifest: json.RawMessage(`{"Action":"coordinate"}`)}} |
| + v.Policy.ManifestHash = runnerproto.EventHash(v.Policy.Manifest) |
| + return v, func() error { return nil }, j.RecordDirectLaunch(ctx, v, containment.Record{ID: c.Turn.ID, AttemptKey: c.Turn.ID, ManifestHash: v.Policy.ManifestHash, PolicyHash: v.Policy.Hash}) |
| + } |
| + var taskIDs []string |
| + for _, kind := range []taskplan.Kind{taskplan.Bug, taskplan.Feature, taskplan.Recommendation} { |
| + msg := apiValue[personapi.Message](t, request(owner, "POST", "/api/v1/conversation/messages", jsonBody(t, personapi.MessageInput{Body: "Please plan a " + string(kind)}), string(kind), "")) |
| + l.plan = taskplan.BugPlan("", project) |
| + l.plan.Kind = kind |
| + if kind == taskplan.Feature { |
| + l.plan.Steps[0].Action = "scope" |
| + l.plan.Steps[0].Specialist = "product" |
| + } |
| + if kind == taskplan.Recommendation { |
| + l.plan.Steps = []taskplan.Step{{Key: "research", Specialist: "product", Action: "recommend", Instructions: "Read the project"}, {Key: "merge", Action: "person"}} |
| + } |
| + l.message = msg.ID |
| + if err := service.Poll(ctx); err != nil { |
| + t.Fatalf("poll: %v starts=%d resource=%s", err, l.starts, l.result.ResourceID) |
| + } |
| + if l.result.ResourceID == "" { |
| + t.Fatal("runner failed to propose", kind) |
| + } |
| + id := l.result.ResourceID |
| + taskIDs = append(taskIDs, id) |
| + if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE message_id=? AND state='delivered'", msg.ID) != 1 { |
| + t.Fatal("message did not produce one delivered turn", kind) |
| + } |
| + current := apiValue[personapi.Plan](t, request(owner, "GET", "/api/v1/tasks/"+id+"/plan", "", "", "")) |
| + current.Steps[1].Instructions = "Use the explicit acceptance criteria" |
| + request(owner, "PATCH", "/api/v1/tasks/"+id+"/plan", jsonBody(t, current.PlanInput), "edit-"+id, fmt.Sprintf(`"%d"`, current.Revision)) |
| + if kind == taskplan.Feature { |
| + request(owner, "POST", "/api/v1/tasks/"+id+"/project", jsonBody(t, personapi.ProjectInput{ProjectID: second.ID}), "correct", `"2"`) |
| + } |
| + current = apiValue[personapi.Plan](t, request(owner, "GET", "/api/v1/tasks/"+id+"/plan", "", "", "")) |
| + request(owner, "POST", "/api/v1/tasks/"+id+"/plan/approve", `{}`, "approve-"+id, fmt.Sprintf(`"%d"`, current.Revision)) |
| + } |
| + // Interrupt after durable input but before a provider completion. Reopening |
| + // the journal must preserve uncertainty and must never send that input again. |
| + request(owner, "POST", "/api/v1/conversation/messages", `{"body":"interrupt this turn"}`, "interrupt", "") |
| + l.interrupt = true |
| + if err := service.Poll(ctx); !errors.Is(err, provider.ErrUncertain) { |
| + t.Fatalf("interruption: %v", err) |
| + } |
| + if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='uncertain'") != 1 { |
| + t.Fatal("interruption did not retain uncertainty") |
| + } |
| + // Reopen the journal; no provider session or tool effect may be repeated. |
| + starts := l.starts |
| + must(t, j.Close()) |
| + j, err = runner.OpenJournal(ctx, journalPath) |
| + must(t, err) |
| + l.journal = j |
| + service.Journal = j |
| + must(t, service.Recover(ctx)) |
| + must(t, service.Poll(ctx)) |
| + if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='uncertain'") != 1 { |
| + t.Fatal("recovery cleared uncertain blocker") |
| + } |
| + if l.starts != starts { |
| + t.Fatal("restart repeated provider turn") |
| + } |
| + if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='coordinator.delivered'") != 3 { |
| + t.Fatal("delivery replay duplicated effects") |
| + } |
| + page := apiValue[personapi.ConversationPage](t, request(owner, "GET", "/api/v1/conversation", "", "", "")) |
| + for _, m := range page.Messages { |
| + if strings.Contains(m.Body, "peer private") { |
| + t.Fatal("private conversation leaked") |
| + } |
| + } |
| + reply := apiValue[personapi.Message](t, request(owner, "POST", "/api/v1/conversation/messages", `{"body":"route this reply"}`, "reply", "")) |
| + request(owner, "POST", "/api/v1/conversation/messages/"+reply.ID+"/route", jsonBody(t, personapi.RouteInput{TaskID: taskIDs[0]}), "route", `"1"`) |
| + request(peer, "GET", "/api/v1/tasks/"+taskIDs[0]+"/thread", "", "", "") |
| + pref := apiValue[personapi.Preference](t, request(owner, "POST", "/api/v1/preferences", `{"text":"Short answers"}`, "pref", "")) |
| + request(owner, "PATCH", "/api/v1/preferences/"+pref.ID, `{"text":"Explain the evidence"}`, "pref-edit", `"1"`) |
| + if len(apiValue[personapi.Page[personapi.Preference]](t, request(peer, "GET", "/api/v1/preferences", "", "", "")).Items) != 0 { |
| + t.Fatal("preferences leaked") |
| + } |
| + // Queued executable work is cancelled through the same guarded person operation. |
| + for _, id := range taskIDs { |
| + task := apiValue[personapi.Task](t, request(owner, "GET", "/api/v1/tasks/"+id, "", "", "")) |
| + request(owner, "POST", "/api/v1/tasks/"+id+"/cancel", `{}`, "cancel-"+id, fmt.Sprintf(`"%d"`, task.Revision)) |
| + } |
| +} |
| + |
| +type acceptanceLauncher struct { |
| + capture *provider.Capture |
| + process *acceptanceProcess |
| + journal *runner.Journal |
| + proxy *runner.ToolProxy |
| + claim runnerproto.CoordinatorClaim |
| + plan taskplan.Plan |
| + message string |
| + result runnerproto.CoordinatorToolResult |
| + events chan provider.Event |
| + starts int |
| + interrupt bool |
| +} |
| + |
| +func (l *acceptanceLauncher) Preflight(_ context.Context, b provider.Binding, _ provider.Policy) (provider.Identity, error) { |
| + return b.Expected, nil |
| +} |
| +func (l *acceptanceLauncher) Open(ctx context.Context, v provider.Launch) (provider.Session, error) { |
| + s := provider.Session{ID: v.AttemptKey + "-session", AttemptKey: v.AttemptKey, Provider: v.Selection.Provider, AccountID: v.Selection.AccountID, Family: v.Selection.Family, Model: v.Selection.Model} |
| + stdout, writer := io.Pipe() |
| + l.process = &acceptanceProcess{record: containment.Record{ID: v.AttemptKey, AttemptKey: v.AttemptKey, ManifestHash: v.Policy.ManifestHash, PolicyHash: v.Policy.Hash}, stdout: stdout, writer: writer} |
| + var err error |
| + l.capture, err = runner.NewCaptureFactory(l.journal).Open(ctx, l.process, v) |
| + if err != nil { |
| + return s, err |
| + } |
| + l.events = make(chan provider.Event, 1) |
| + go func() { |
| + defer close(l.events) |
| + for frame := range l.capture.Frames { |
| + var event provider.Event |
| + if json.Unmarshal(frame.Bytes, &event) == nil { |
| + event.Sequence = frame.Sequence |
| + l.events <- event |
| + } |
| + } |
| + }() |
| + return s, l.journal.BindSession(ctx, s) |
| +} |
| +func (l *acceptanceLauncher) Events(context.Context, provider.Session) (<-chan provider.Event, error) { |
| + return l.events, nil |
| +} |
| +func (l *acceptanceLauncher) StartTurn(ctx context.Context, s provider.Session, turn provider.Turn) error { |
| + if strings.Contains(turn.Prompt, "peer private") { |
| + return fmt.Errorf("foreign private context") |
| + } |
| + if err := l.journal.BeginTurn(ctx, s, turn); err != nil { |
| + return fmt.Errorf("begin: %w", err) |
| + } |
| + l.starts++ |
| + rawInput, _ := json.Marshal(map[string]any{"type": "user", "session_id": s.ID, "message": map[string]string{"role": "user", "content": turn.Prompt}}) |
| + if _, err := l.capture.Input.Write(append(rawInput, '\n')); err != nil { |
| + return err |
| + } |
| + if l.interrupt { |
| + return provider.ErrUncertain |
| + } |
| + draft := coordinator.Plan{Kind: l.plan.Kind, ProjectID: l.plan.ProjectID} |
| + for _, step := range l.plan.Steps { |
| + draft.Steps = append(draft.Steps, coordinator.PlanStep{Key: step.Key, Specialist: step.Specialist, Action: step.Action, Instructions: step.Instructions, DependsOn: step.DependsOn}) |
| + } |
| + input := coordinator.ProposePlan{MessageID: l.message, Plan: draft} |
| + raw, err := json.Marshal(input) |
| + if err != nil { |
| + return err |
| + } |
| + call := runnerproto.CoordinatorToolCall{RequestID: "proposal", Name: "propose_plan", Arguments: raw} |
| + l.result, err = l.proxy.CallCoordinatorTool(ctx, call) |
| + if err != nil { |
| + return err |
| + } |
| + again, err := l.proxy.CallCoordinatorTool(ctx, call) |
| + if err != nil { |
| + return err |
| + } |
| + if again.ResourceID != l.result.ResourceID { |
| + return fmt.Errorf("duplicate proposal") |
| + } |
| + event := provider.Event{SessionID: s.ID, TurnID: turn.ID, Kind: "turn.completed", Payload: json.RawMessage(`{"usage":{"input_tokens":2,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"output_tokens":3}}`)} |
| + raw, err = json.Marshal(event) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = l.process.writer.Write(append(raw, '\n')) |
| + return err |
| +} |
| +func (l *acceptanceLauncher) Respond(context.Context, provider.Session, provider.Answer) error { |
| + return nil |
| +} |
| +func (l *acceptanceLauncher) Interrupt(context.Context, provider.Session) error { |
| + return l.process.Contain(ctx) |
| +} |
| +func (l *acceptanceLauncher) Close(context.Context, provider.Session) error { |
| + _ = l.process.Contain(ctx) |
| + return <-l.capture.Done |
| +} |
| + |
| +type acceptanceProcess struct { |
| + record containment.Record |
| + stdout *io.PipeReader |
| + writer *io.PipeWriter |
| + once sync.Once |
| +} |
| + |
| +func (p *acceptanceProcess) ID() string { return p.record.ID } |
| +func (p *acceptanceProcess) Record() containment.Record { return p.record } |
| +func (p *acceptanceProcess) Stdin() io.WriteCloser { return acceptanceInput{} } |
| +func (p *acceptanceProcess) Stdout() io.ReadCloser { return p.stdout } |
| +func (p *acceptanceProcess) Stderr() io.ReadCloser { return io.NopCloser(bytes.NewReader(nil)) } |
| +func (p *acceptanceProcess) Wait(context.Context) (provider.Exit, error) { return provider.Exit{}, nil } |
| +func (p *acceptanceProcess) Contain(context.Context) error { |
| + p.once.Do(func() { _ = p.writer.Close() }) |
| + return nil |
| +} |
| + |
| +type acceptanceInput struct{} |
| + |
| +func (acceptanceInput) Write(raw []byte) (int, error) { return len(raw), nil } |
| +func (acceptanceInput) Close() error { return nil } |
diff --git a/internal/plan3test/coordinator_acceptance_test.go b/internal/plan3test/coordinator_acceptance_test.go| new file mode 100644 |
| index 00000000..29ab94e4 |
| --- /dev/null |
| +++ b/internal/plan3test/coordinator_acceptance_test.go |
| @@ -0,0 +1,257 @@ |
| +package plan3test |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "gorm.io/gorm" |
| + "net/http/httptest" |
| + "net/url" |
| + "sort" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func TestCoordinatorAcceptance3A(t *testing.T) { |
| + t.Run("http_runner", acceptanceHTTP) |
| + t.Run("active_cancel", acceptanceActiveCancel) |
| + t.Run("account_scope", TestCoordinatorToolScope) |
| + t.Run("claim_identity", TestCoordinatorAuthorityClaimTampering) |
| + t.Run("uncertain_requires_person", acceptanceUncertainRequiresPerson) |
| + t.Run("recency", TestPersonAPIRecencyAcrossPages) |
| + t.Run("task_card_recency", TestPersonAPITaskAndCardRecency) |
| + t.Run("read_epoch", TestPersonAPIReadEpochTransaction) |
| + t.Run("stream_cursors", TestPersonAPIStreamCursorIsolation) |
| + t.Run("html_cursor_retention", TestConversationCursorRetention) |
| + t.Run("delivery_receipt", TestCoordinatorSessionTrustedReceipt) |
| + t.Run("atomic_delivery", TestCoordinatorTurnDeliveryAtomic) |
| + t.Run("plan_replay", TestCoordinatorToolCommitCrash) |
| + t.Run("recommendation", TestPlanWorkflowRecommendationDelivery) |
| + t.Run("question", TestPersonAPIQuestions) |
| + t.Run("human_merge", TestPersonAPIRenderedAndMerge) |
| + t.Run("preferences", TestPreferencesCorrectionAndDelete) |
| +} |
| + |
| +func acceptanceUncertainRequiresPerson(t *testing.T) { |
| + f, x, p, b := coordinatorFixture(t) |
| + x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| + turn := queueCoordinator(t, f, "first", "first") |
| + c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| + next := queueCoordinator(t, f, "later", "later") |
| + _, err = x.RecoverCoordinator(ctx, p, turn.ID, turn.Revision) |
| + var refusal *runnerproto.RefusalError |
| + if err == nil || errors.As(err, &refusal) && refusal.CoordinatorDefinitive() { |
| + t.Fatal("uncertain turn fenced without person's choice", err) |
| + } |
| + var state string |
| + must(t, f.DB.Writer().QueryRow("SELECT state FROM coordinator_turns WHERE id=?", turn.ID).Scan(&state)) |
| + if state != "uncertain" { |
| + t.Fatal("uncertainty lost", state) |
| + } |
| + offers, err := x.PollCoordinator(ctx, p) |
| + must(t, err) |
| + if len(offers) != 0 { |
| + t.Fatal("uncertain turn released queue", offers) |
| + } |
| + _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| + must(t, err) |
| + _, err = x.RecoverCoordinator(ctx, p, turn.ID, turn.Revision) |
| + if !errors.As(err, &refusal) || !refusal.CoordinatorDefinitive() { |
| + t.Fatal("explicit reset did not fence old turn", err) |
| + } |
| + offers, err = x.PollCoordinator(ctx, p) |
| + must(t, err) |
| + if len(offers) != 1 || offers[0].MessageID != next.MessageID { |
| + t.Fatal("explicit reset lost queued request", offers) |
| + } |
| +} |
| + |
| +func TestPersonAPIRecencyAcrossPages(t *testing.T) { |
| + f := newFixture(t) |
| + for i, id := range []string{"a-old", "z-new", "b-tie"} { |
| + _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: id, Status: "confirmed"}, equipo.Mutation{RequestID: id}) |
| + must(t, err) |
| + var old string |
| + must(t, f.DB.Writer().QueryRow("SELECT id FROM personal_preferences WHERE text=?", id).Scan(&old)) |
| + f.exec(t, "UPDATE personal_preferences SET id=? WHERE id=?", id, old) |
| + at := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) |
| + if i > 0 { |
| + at = at.Add(time.Hour) |
| + } |
| + f.exec(t, "UPDATE audit_events SET record_id=?,at=? WHERE record_id=?", id, at, old) |
| + } |
| + cursor := "" |
| + for _, want := range []string{"b-tie", "z-new", "a-old"} { |
| + w := apiRequest(t, f, owner, "GET", "/api/v1/preferences?limit=1&cursor="+url.QueryEscape(cursor), "", "", "") |
| + expectHTTP(t, w, 200) |
| + page := apiValue[personapi.Page[personapi.Preference]](t, w) |
| + if len(page.Items) != 1 || page.Items[0].ID != want { |
| + t.Fatalf("recency order: got %+v want %s", page.Items, want) |
| + } |
| + cursor = page.NextCursor |
| + } |
| + if cursor != "" { |
| + t.Fatal("extra page") |
| + } |
| +} |
| + |
| +func TestPersonAPIReadEpochTransaction(t *testing.T) { |
| + f := newFixture(t) |
| + // Advance the epoch after the HTTP authentication read and before the data read. |
| + fired := false |
| + must(t, f.DB.G.Callback().Query().After("gorm:query").Register("task11_epoch", func(tx *gorm.DB) { |
| + if !fired && tx.Statement.Table == "members" && tx.Statement.Context.Value(epochTestKey{}) != nil { |
| + fired = true |
| + f.exec(t, "UPDATE members SET session_epoch=? WHERE address=?", time.Now().Unix()+100, owner.Address) |
| + } |
| + })) |
| + t.Cleanup(func() { _ = f.DB.G.Callback().Query().Remove("task11_epoch") }) |
| + r := httptest.NewRequest("GET", "/api/v1/conversation", nil).WithContext(context.WithValue(ctx, epochTestKey{}, true)) |
| + r.AddCookie(f.Cookies[owner.Address]) |
| + w := httptest.NewRecorder() |
| + f.Handler.ServeHTTP(w, r) |
| + if !fired { |
| + t.Fatal("race hook not reached") |
| + } |
| + expectHTTP(t, w, 403) |
| +} |
| + |
| +type epochTestKey struct{} |
| + |
| +func TestPersonAPIStreamCursorIsolation(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + otherTask := f.task(t, owner, "other-thread") |
| + for i := 0; i < 3; i++ { |
| + _, err := f.Store.SendMessage(ctx, owner, "", "private", equipo.Mutation{RequestID: fmt.Sprint("p", i)}) |
| + must(t, err) |
| + _, err = f.Store.SendMessage(ctx, owner, p.TaskID, "shared", equipo.Mutation{RequestID: fmt.Sprint("t", i)}) |
| + must(t, err) |
| + } |
| + for _, path := range []string{"/api/v1/conversation", "/api/v1/tasks/" + p.TaskID + "/thread"} { |
| + w := apiRequest(t, f, owner, "GET", path+"?limit=1", "", "", "") |
| + expectHTTP(t, w, 200) |
| + page := apiValue[personapi.ConversationPage](t, w) |
| + if page.NextCursor == "" { |
| + t.Fatal("missing cursor") |
| + } |
| + expectHTTP(t, apiRequest(t, f, peer, "GET", path+"?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410) |
| + expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/tasks/"+otherTask.ID+"/thread?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410) |
| + other := "/api/v1/conversation" |
| + if path == other { |
| + other = "/api/v1/tasks/" + p.TaskID + "/thread" |
| + } |
| + expectHTTP(t, apiRequest(t, f, owner, "GET", other+"?cursor="+url.QueryEscape(page.NextCursor), "", "", ""), 410) |
| + } |
| +} |
| +func TestConversationCursorRetention(t *testing.T) { |
| + f := newFixture(t) |
| + for i := 0; i < 3; i++ { |
| + _, err := f.Store.SendMessage(ctx, owner, "", "page", equipo.Mutation{RequestID: fmt.Sprint(i)}) |
| + must(t, err) |
| + } |
| + page, err := f.Store.Conversation(ctx, owner, "", 1) |
| + must(t, err) |
| + if page.NextCursor == "" { |
| + t.Fatal("missing cursor") |
| + } |
| + f.exec(t, "UPDATE conversation_cursors SET expires_at=?", time.Now().Add(-time.Hour)) |
| + _, err = f.Store.Conversation(ctx, owner, "", 1) |
| + must(t, err) |
| + if f.count(t, "SELECT count(*) FROM conversation_cursors WHERE expires_at <= ?", time.Now()) != 0 { |
| + t.Fatal("expired HTML cursors retained") |
| + } |
| +} |
| + |
| +func TestPersonAPITaskAndCardRecency(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + ids := []string{p.TaskID} |
| + for i := 0; i < 2; i++ { |
| + p.TaskID = "" |
| + p.Revision = 0 |
| + next, err := f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: fmt.Sprint("recency", i)}) |
| + must(t, err) |
| + ids = append(ids, next.TaskID) |
| + } |
| + sort.Strings(ids) |
| + for i, id := range ids { |
| + f.exec(t, "UPDATE audit_events SET at=? WHERE record_id=?", time.Now().UTC().Add(time.Duration(i+1)*time.Hour), id) |
| + } |
| + for _, path := range []string{"tasks", "journey", "conversation/cards"} { |
| + t.Run(path, func(t *testing.T) { |
| + cursor := "" |
| + for i := len(ids) - 1; i >= 0; i-- { |
| + w := apiRequest(t, f, owner, "GET", "/api/v1/"+path+"?limit=1&cursor="+url.QueryEscape(cursor), "", "", "") |
| + expectHTTP(t, w, 200) |
| + page := apiValue[personapi.Page[struct { |
| + ID string `json:"id"` |
| + ResourceID string `json:"resource_id"` |
| + }]](t, w) |
| + if len(page.Items) != 1 { |
| + t.Fatal("missing page", page) |
| + } |
| + id := page.Items[0].ID |
| + if path == "conversation/cards" { |
| + id = page.Items[0].ResourceID |
| + } |
| + if id != ids[i] { |
| + t.Fatalf("recency: got %s want %s", id, ids[i]) |
| + } |
| + cursor = page.NextCursor |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPreferencesInferredDeleteFailure(t *testing.T) { |
| + f, x, p, c := claimTools(t) |
| + toolCall(t, x, p, c, "suggest", "suggest_preference", map[string]any{"source_message_id": c.Turn.MessageID, "text": "Keep the explanation brief"}) |
| + prefs, err := f.Store.Preferences(ctx, owner) |
| + must(t, err) |
| + if len(prefs) != 1 || prefs[0].Status != "inferred" { |
| + t.Fatal(prefs) |
| + } |
| + before := f.count(t, "SELECT count(*) FROM audit_events") |
| + f.exec(t, `CREATE TRIGGER reject_preference_delete BEFORE INSERT ON personal_preferences BEGIN SELECT RAISE(ABORT,'fixture write failure'); END`) |
| + err = f.Store.DeletePreference(ctx, owner, prefs[0].ID, equipo.Mutation{RequestID: "delete", Revision: prefs[0].Revision}) |
| + if err == nil { |
| + t.Fatal("failed inferred deletion reported success") |
| + } |
| + if f.count(t, "SELECT count(*) FROM audit_events") != before { |
| + t.Fatal("failed deletion committed audit") |
| + } |
| +} |
| + |
| +func acceptanceActiveCancel(t *testing.T) { |
| + f, x, principal, q, question := nativeConversationFixture(t) |
| + x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| + apiRouter(t, f, nil) |
| + path := "/api/v1/tasks/" + question.TaskID |
| + current, err := f.Store.Task(ctx, owner, question.TaskID) |
| + must(t, err) |
| + response := apiRequest(t, f, owner, "POST", path+"/cancel", `{}`, "cancel-active", fmt.Sprintf(`"%d"`, current.Revision)) |
| + expectHTTP(t, response, 200) |
| + current, err = f.Store.Task(ctx, owner, question.TaskID) |
| + must(t, err) |
| + if current.State != "cancel_requested" { |
| + t.Fatal("active cancellation invented containment", current.State) |
| + } |
| + if err = x.Core.ValidateHandle(ctx, q.Scope, q.Handle); err == nil { |
| + t.Fatal("cancelled attempt retained authority") |
| + } |
| + q.RequestID = "contained" |
| + _, err = x.Mutate(ctx, principal, "contained", q) |
| + must(t, err) |
| + current, err = f.Store.Task(ctx, owner, question.TaskID) |
| + must(t, err) |
| + if current.State != "cancelled" { |
| + t.Fatal("contained cancellation did not finish", current.State) |
| + } |
| +} |
diff --git a/internal/plan3test/coordinator_refusal3_test.go b/internal/plan3test/coordinator_refusal3_test.go| index 25391c70..641381c2 100644 |
| --- a/internal/plan3test/coordinator_refusal3_test.go |
| +++ b/internal/plan3test/coordinator_refusal3_test.go |
| @@ -87,26 +87,8 @@ func TestCoordinatorRefusalDoesNotFenceTransientOrPending(t *testing.T) { |
| } |
| } |
| -func TestCoordinatorDefinitiveFenceSameGeneration(t *testing.T) { |
| - f, x, p, _ := coordinatorFixture(t) |
| - x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| - first := queueCoordinator(t, f, "first", "first") |
| - c, err := x.ClaimCoordinator(ctx, p, first.ID, first.Revision) |
| - must(t, err) |
| - must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| - next := queueCoordinator(t, f, "next", "next") |
| - _, err = x.RecoverCoordinator(ctx, p, first.ID, first.Revision) |
| - var refusal *runnerproto.RefusalError |
| - if !errors.As(err, &refusal) || !refusal.CoordinatorDefinitive() { |
| - t.Fatal("missing definitive refusal", err) |
| - } |
| - offers, err := x.PollCoordinator(ctx, p) |
| - must(t, err) |
| - if len(offers) != 1 || offers[0].ID != next.ID { |
| - t.Fatal("fenced turn still blocks next offer", offers) |
| - } |
| - _, err = x.ClaimCoordinator(ctx, p, next.ID, next.Revision) |
| - must(t, err) |
| +func TestCoordinatorUncertainSameGenerationWaitsForPerson(t *testing.T) { |
| + acceptanceUncertainRequiresPerson(t) |
| } |
| func TestCoordinatorDefinitiveFenceAtomic(t *testing.T) { |
diff --git a/internal/plan3test/coordinator_release_test.go b/internal/plan3test/coordinator_release_test.go| new file mode 100644 |
| index 00000000..5e3e0312 |
| --- /dev/null |
| +++ b/internal/plan3test/coordinator_release_test.go |
| @@ -0,0 +1,43 @@ |
| +package plan3test |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/release" |
| +) |
| + |
| +func TestCoordinatorReleaseNeedsPolicyCertification(t *testing.T) { |
| + for _, name := range []string{"claude", "codex"} { |
| + t.Run(name, func(t *testing.T) { |
| + m := release.BuildManifest() |
| + hash, err := release.ActionInventoryHash(name, "coordinate") |
| + must(t, err) |
| + version := map[string]string{"claude": m.Claude, "codex": m.Codex}[name] |
| + if m.ActionCertified(name, "coordinate", version, hash) { |
| + t.Fatal("missing certificate accepted") |
| + } |
| + certificate := release.PolicyCertificate{Provider: name, ProviderVersion: version, LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, PolicyHash: hash, CertifiedRefresh: release.CertifiedRefresh{AuthHost: "auth.example.test", EvidenceSHA256: strings.Repeat("b", 64)}} |
| + m.DirectPolicies = []release.PolicyCertificate{certificate} |
| + m.Certifications = []release.Certification{{Provider: name, PolicyHash: hash, SHA256: certificate.CertifiedRefresh.EvidenceSHA256, Path: "fixture"}} |
| + m.LiveGateCopyReviewed = true |
| + if m.ActionCertified(name, "coordinate", version, hash) { |
| + t.Fatal("old certificate authorized pending coordinator inventory") |
| + } |
| + m.UncertifiedPolicies = nil |
| + if !m.ActionCertified(name, "coordinate", version, hash) { |
| + t.Fatal("positive exact certificate fixture refused") |
| + } |
| + if m.ActionCertified(name, "coordinate", version, strings.Repeat("c", 64)) { |
| + t.Fatal("wrong policy accepted") |
| + } |
| + if m.ActionCertified(name, "coordinate", "old", hash) { |
| + t.Fatal("old provider accepted") |
| + } |
| + m.LiveGateCopyReviewed = false |
| + if m.ActionCertified(name, "coordinate", version, hash) { |
| + t.Fatal("pending copy authorized release") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/plan3test/person_api_fixes_test.go b/internal/plan3test/person_api_fixes_test.go| index 989e652a..bf6ac6c8 100644 |
| --- a/internal/plan3test/person_api_fixes_test.go |
| +++ b/internal/plan3test/person_api_fixes_test.go |
| @@ -170,6 +170,8 @@ func TestPersonAPICursorFreshnessAndOrder(t *testing.T) { |
| for _, id := range []string{"b", "d", "f"} { |
| _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "secret-" + id, Status: "confirmed"}, equipo.Mutation{RequestID: id}) |
| must(t, err) |
| + f.exec(t, "UPDATE audit_events SET at=? WHERE record_id=(SELECT id FROM personal_preferences WHERE text=?)", time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), "secret-"+id) |
| + f.exec(t, "UPDATE audit_events SET record_id=? WHERE record_id=(SELECT id FROM personal_preferences WHERE text=?)", id, "secret-"+id) |
| f.exec(t, "UPDATE personal_preferences SET id=? WHERE text=?", id, "secret-"+id) |
| } |
| read := func(cursor string) personapi.Page[personapi.Preference] { |
| @@ -185,6 +187,8 @@ func TestPersonAPICursorFreshnessAndOrder(t *testing.T) { |
| for _, id := range []string{"a", "c"} { |
| _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "secret-" + id, Status: "confirmed"}, equipo.Mutation{RequestID: id}) |
| must(t, err) |
| + f.exec(t, "UPDATE audit_events SET at=? WHERE record_id=(SELECT id FROM personal_preferences WHERE text=?)", time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), "secret-"+id) |
| + f.exec(t, "UPDATE audit_events SET record_id=? WHERE record_id=(SELECT id FROM personal_preferences WHERE text=?)", id, "secret-"+id) |
| f.exec(t, "UPDATE personal_preferences SET id=? WHERE text=?", id, "secret-"+id) |
| } |
| var ids []string |
diff --git a/internal/release/policy_inventory.go b/internal/release/policy_inventory.go| index 2ba7ac45..526b58d6 100644 |
| --- a/internal/release/policy_inventory.go |
| +++ b/internal/release/policy_inventory.go |
| @@ -45,6 +45,9 @@ func ActionInventoryHash(name, action string) (string, error) { |
| return hex.EncodeToString(hash[:]), nil |
| } |
| func (m Manifest) ActionCertified(name, action, version, hash string) bool { |
| + if !m.LiveGateCopyReviewed { |
| + return false |
| + } |
| for _, p := range m.UncertifiedPolicies { |
| if p.Provider == name && p.Action == action { |
| return false |
diff --git a/internal/runner/checks/render_test.go b/internal/runner/checks/render_test.go| index 4f455589..42da1704 100644 |
| --- a/internal/runner/checks/render_test.go |
| +++ b/internal/runner/checks/render_test.go |
| @@ -64,7 +64,7 @@ func (s frozenRenderSandbox) Run(ctx context.Context, c Command, w string, p pro |
| if string(raw) != "trusted renderer" { |
| s.t.Fatal("candidate replaced the trusted renderer") |
| } |
| - return renderSandbox{s.t}.Run(ctx, c, w, p, out, errout) |
| + return renderSandbox(s).Run(ctx, c, w, p, out, errout) |
| } |
| func TestPlanWorkflowRenderDefinition(t *testing.T) { |
| f := newFixture(t) |
diff --git a/internal/runner/coordinator_recovery.go b/internal/runner/coordinator_recovery.go| index 144d1949..9fc844c6 100644 |
| --- a/internal/runner/coordinator_recovery.go |
| +++ b/internal/runner/coordinator_recovery.go |
| @@ -271,9 +271,6 @@ func (r *Runtime) coordinatorService() *CoordinatorService { |
| } |
| return s |
| } |
| -func coordinatorAttempt(c runnerproto.CoordinatorClaim) *attemptState { |
| - return &attemptState{Direct: true, Claim: RunClaim{Assignment: runnerproto.Assignment{ID: c.Turn.ID, TaskID: c.Turn.ID, Kind: "coordinator", StepKey: "coordinate", Selection: c.Brief.Selection, Scope: c.Scope}, ClaimResponse: runnerproto.ClaimResponse{Scope: c.Scope, Handle: c.Handle, Brief: c.Brief, LeaseDeadline: c.LeaseDeadline, AttemptDeadline: c.AttemptDeadline}}} |
| -} |
| // Containment reporting uses the coordinator endpoint, not task credentials. |
| func (r *Runtime) containCoordinator(ctx context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { |
diff --git a/internal/runner/runtime_direct.go b/internal/runner/runtime_direct.go| index c232d2b9..60875d18 100644 |
| --- a/internal/runner/runtime_direct.go |
| +++ b/internal/runner/runtime_direct.go |
| @@ -21,10 +21,6 @@ func directLauncherVersion() string { |
| } |
| return provider.PolicyVersion |
| } |
| -func certifiedDirect(name, version, hash string) bool { |
| - return release.BuildManifest().CertifiedAuthHost(name, version, hash) != "" |
| -} |
| - |
| func (r *Runtime) constructDirect(ctx context.Context, s provider.Selection, work, step string) (provider.Launch, func() error, error) { |
| return r.constructDirectManifest(ctx, s, work, step, release.BuildManifest()) |
| } |
diff --git a/internal/runner/turn_prompt.go b/internal/runner/turn_prompt.go| index acf0bec9..c4458854 100644 |
| --- a/internal/runner/turn_prompt.go |
| +++ b/internal/runner/turn_prompt.go |
| @@ -8,8 +8,6 @@ import ( |
| var ErrPromptTooLarge = planflow.ErrPromptTooLarge |
| -const maxTurnPromptBytes = planflow.MaxPromptBytes |
| - |
| func buildTurnPrompt(c RunClaim, artifacts []team.Artifact) (string, error) { |
| return planflow.Prompt(c.Assignment, c.Brief, artifacts) |
| } |