Skip to content

Commit 5d3c540

Browse files
committed
feat(bots): mediate execution through Employee and streamline research
Preserve private Chat discovery, approvals, recovery and run isolation. Complete scheduling synchronously with verified Employee feedback, keep runtime status separate from speech, and retain clarification ordering. Replace Bot execution caps with usage accounting and add request-proportional research guidance. Include focused regressions, browser/PTY coverage and opt-in SAP/Docker acceptance harnesses.
1 parent 14e47ca commit 5d3c540

187 files changed

Lines changed: 15763 additions & 1365 deletions

File tree

Some content is hidden

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

‎cmd/astonish/bots_employee_pty_test.go‎

Lines changed: 391 additions & 0 deletions
Large diffs are not rendered by default.

‎cmd/astonish/bots_title_pty_test.go‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -171,11 +171,10 @@ func testBotTitleChatPTYAnswer(t *testing.T, mode string) {
171171
if mode == "custom" {
172172
_, _ = io.WriteString(pt, "\x1b[B\x1b[B\x1b[B"+wantAnswer)
173173
}
174-
_, _ = io.WriteString(pt, "\r")
175-
wait(fmt.Sprintf("Confirm answer %q", wantAnswer))
174+
wait("Enter submits answer")
176175
select {
177176
case <-answers:
178-
t.Fatal("answer posted before confirmation")
177+
t.Fatal("answer posted before Enter")
179178
default:
180179
}
181180
_, _ = io.WriteString(pt, "\r")

‎docs/architecture/bot-authorized-scheduling.md‎

Lines changed: 63 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,68 @@
22

33
The schedule-control runtime is a trusted composition capability, separate from generic operation persistence and manual control-proposal review. Construct it with `entstore.NewBotAuthorizedOperationRuntime`, the current mandate policy resolver, an issuer-policy source authorizer, and candidate readiness checker. Nil callbacks fail closed.
44

5+
## Synchronous Employee coordinator
6+
7+
Daemon source commits use a server-only context marker and persist private
8+
`EmployeeScheduleCoordinator` ownership only for captured schedule operations in
9+
Home-interactive terminal runs. `CoordinateEmployeeSchedules` applies the exact
10+
source-linked operations directly after supervisor return, then independently reads
11+
the committed operation and scheduler job. Enabled requests require both `Enabled`
12+
and `NextRun`. Applied replays retain their original revision. Cancelled, interrupted
13+
or failed sources do not activate their capture. Definitive typed denials become
14+
cancelled operation receipts; ambiguous/busy records are not blindly reapplied by
15+
pending polling. The legacy pending drain skips marked schedule sources entirely.
16+
Only marked application suppresses the separate runtime receipt publication.
17+
18+
The daemon then prepares and claims the original private presentation envelope and
19+
uses `NewBotEmployeePresentationFactory` with the stored provider/model and original
20+
accounting ledger. It completes presentation before reconciling publication; no fresh tool
21+
lease or execution allowance is issued. Readiness failures carry a typed unsupported
22+
category and retain their private underlying error for trusted diagnostics; they
23+
are not converted to a background readiness retry. `TestEmployeeSynchronousScheduleHTTPAcceptance`
24+
uses real loopback admission and the production shared Employee/private Chat runtime,
25+
with native scheduling and proposal routes in both scopes. Its final model callback
26+
requires terminal lease release, the exact applied operation, independently matching
27+
enabled job/NextRun, and no tools before it generates digest-bound JSON. The fixture
28+
also requires the production `evidence_bound_v1` Work contract and zero
29+
`BOT_WORK_PENDING_REVIEW_V1` model assessments for fresh validated private captures.
30+
The typed tool arguments are the turn model's schedule selection; enqueue validates
31+
and persists the exact immutable payload. Private schedule completion mechanically
32+
binds the settled runtime capture to its candidate under the original lease/CAS,
33+
recording enqueue completion separately from still-unverified application. It does
34+
not make another semantic model judgment against older history or impose a new
35+
execution allowance. Only settled, runtime-bound enqueue-only captures qualify;
36+
unknown or uncertain effects and mixed changed/artifact work retain ordinary
37+
fail-closed content review. A later private worker policy denial with a bound
38+
pre-dispatch nonexecution receipt does not invalidate a previously captured
39+
schedule. Fully observed private finals retain that capture for mechanical
40+
completion; missing responses, mixed native errors, foreign receipts and uncertain
41+
effects still fail closed. This does not grant
42+
`get_bot` permission or claim that enqueue has applied the schedule. The coordinator still
43+
applies and independently verifies only after source commit; no pending capture is
44+
called an applied schedule. The focused HTTP gate passes with controlled models and
45+
isolated temporary SQL stores; it is not a live-provider or deployed-daemon proof.
46+
Store coordination tests cover personal/team success, denial, duplicate replay and
47+
exclusion from later activation. The focused HTTP gate also covers readiness,
48+
cancellation, restart and original-limit scenarios.
49+
50+
Final presentation separates `operations` (terminal outcomes) from
51+
`preapplication_context` (the older source report, private workers and history).
52+
The Employee must use matching verified receipts for the current result, not
53+
repeat an earlier pending acknowledgment. Definitive failed/blocked/cancelled
54+
operations are reported without claiming activation; source sequence/time/digest
55+
remain immutable even when presentation is unavailable. Tools-disabled failure
56+
communication retains original expiry, revocation and cumulative-accounting checks;
57+
production accounting does not enforce historic token/tool/runtime quotas.
58+
When it cannot run, neutral terminal state remains visible without assistant fallback.
59+
The opt-in `TestBotEmployeeRealScheduleHTTPAcceptance` uses a live provider and
60+
production HTTP/worker/coordinator, independent enabled-job/NextRun readback,
61+
pre-attached live SSE and stable history/reconcile publication checks. Its Home
62+
transport is controlled, not physical Docker/Kubernetes execution.
63+
564
## Authority and capture
665

7-
`EnqueueAuthorizedOperation` accepts a live worker lease, its source task mandate pin, stable key and a typed schedule create/edit/pause/remove payload. It verifies the lease before exposing canonical source text to the trusted authorizer, then verifies again in its scoped transaction. The source must be an authenticated-owner manual run with an actual user event and matching persisted digest. The issuer authorizer receives canonical plaintext and protected direct-owner-message provenance, not model-provided consent claims. Ordinary natural-language messages need no `schedule_command` envelope. The existing turn model selects a candidate contextually; no regex or second model claims to prove semantic intent. The issuer checks exact own-control tool resources under trusted mandate configuration, while storage enforces bot scope, live source lease, immutable payload and finite quotas. Title-start provenance is distinct and cannot authorize recurrence; missing legacy provenance also fails closed. HTTP does not accept a schedule-grant DTO.
66+
`EnqueueAuthorizedOperation` accepts a live worker lease, its source task mandate pin, stable key and a typed schedule create/edit/pause/remove payload. It verifies the lease before exposing canonical source text to the trusted authorizer, then verifies again in its scoped transaction. The source must be an authenticated-owner manual run with an actual user event and matching persisted digest. The issuer authorizer receives canonical plaintext and protected direct-owner-message provenance, not model-provided consent claims. Ordinary natural-language messages need no `schedule_command` envelope. The existing turn model selects a candidate contextually; no regex or second model claims to prove semantic intent. The issuer checks exact own-control tool resources under trusted mandate configuration, while storage enforces bot scope, live source lease, immutable payload and concurrency/authority boundaries. Title-start provenance is distinct and cannot authorize recurrence; missing legacy provenance also fails closed. HTTP does not accept a schedule-grant DTO.
867

968
A private immutable `authorized-schedule-grant` record binds source run/user/event/digest, payload digest, schedule-control purpose and captured root revision/version. The original task mandate remains task-purpose. This bounded issuer transition does not issue future scheduled execution pins or expand task permissions. Current membership, revocation, expiry and operator limits are checked again on apply.
1069

@@ -14,7 +73,7 @@ Pending operations are immutable outbox revisions with deterministic operation/t
1473

1574
The effective Bot system prompt, Bot-specific job-scheduling guidance and `schedule_job` description agree: an explicit owner request for recurring work within the current bounded mandate proceeds to the scoped schedule adapter. Use the task and cadence already supplied in conversation. For example, when the preceding task is known, “send this here every minute” needs no second “yes, every minute,” mode questionnaire or generic proposal review merely because output may repeat or be frequent. Home delivery needs no external recipient.
1675

17-
This is model guidance, not an authorization shortcut. Runtime minimum interval, finite budgets, source provenance and exact-operation checks remain authoritative. Clarify genuinely ambiguous tasks/cadences or unknown destinations; honor cost/policy limits and `RequireAuthorization`. External effects still require their own authority; legacy non-mandated review and control-only restrictions remain. A queued operation is not an applied schedule. The prohibition on parsing prose as consent concerns bypassing typed authorization or synthesizing an approval, not refusing a clear owner request to call the guarded adapter.
76+
This is model guidance, not an authorization shortcut. Runtime minimum interval, authority expiry, source provenance and exact-operation checks remain authoritative. Historic execution quotas (including public-research call caps) are accounting metadata, not stopping limits; a thirteenth permitted search must not fail because twelve calls were retained. Clarify genuinely ambiguous tasks/cadences or unknown destinations; honor cost/policy limits and `RequireAuthorization`. External effects still require their own authority; legacy non-mandated review and control-only restrictions remain. A queued operation is not an applied schedule. The prohibition on parsing prose as consent concerns bypassing typed authorization or synthesizing an approval, not refusing a clear owner request to call the guarded adapter.
1877

1978
`TestBotRoutineScheduleConsentPrompt` covers interactive Chat and Home turns plus control-only/background exclusions; `TestSchedulingGuidanceRoutineConsent` covers the guidance override. `TestBotFactoryRoutineScheduleConsent` checks the effective provider system instruction and scoped tool description while preserving the natural user turn. These prompt contract tests do not prove a live model's choice. The unchanged controlled `TestBotAuthorizedScheduleHTTPAcceptance` separately exercises natural-language HTTP admission, pending capture, worker application and zero approvals in both scopes.
2079

@@ -28,13 +87,13 @@ This tool does not change task instructions. A preference-only memory request sh
2887

2988
## Verified enqueue is not applied scheduling
3089

31-
`botScheduleTools.enqueue` independently calls `ReadAuthorizedOperation` after enqueue. `verifyScheduleCapture` checks the returned operation against the durable pending record, requested payload, mandate, idempotency key and source provenance (including the payload digest). Missing, unreadable or mismatched records produce no trusted outcome. A pending-shaped JSON result or operation ID alone is not evidence.
90+
`botScheduleTools.enqueue` and mandated `propose_bot_control` schedule-create/edit/remove calls share `recordScheduleCapture`, which independently calls `ReadAuthorizedOperation` after enqueue. Both routes use the same authorized-operation factory, actual request mandate pin, source lease and exact call identity; the control payload's supplied revision and schedule bindings are preserved, not inferred. An eligible direct owner request therefore captures an authorized pending operation rather than a manual-review proposal or another confirmation. `schedule_pause` on the proposal route remains rejected with priority-pause/native-update guidance, and targeted resume remains separate. Non-mandated proposals and true source/policy denials are unchanged. `verifyScheduleCapture` checks the returned operation against the durable pending record, requested payload, mandate, idempotency key and source provenance (including the payload digest). Missing, unreadable or mismatched records produce no trusted outcome. A pending-shaped JSON result or operation ID alone is not evidence.
3291

3392
Only successful read-back records a server-only `bot.ScheduleCapture` in the current call's `ToolOutcomes` ledger. The ledger snapshots the capture and consumes it once; ADK's serialized result metadata cannot create an attestation. The runner checks the run/owner identity, operation ID and pending response status again and rejects receipts mixed with changed-schedule, artifact or next-run claims. This works for direct scheduling calls and `execute_tool` without tool-name success exceptions.
3493

3594
The source report records an unchanged observation with a `bot-operation://<bot>/<operation>` source and a server acknowledgment that the operation is durably queued and pending. That acknowledgment takes precedence over a model's premature “Done” summary. It does not set `Changed` or `NextRunAt`, hide unrelated unverified effects, or assert that the scheduler has changed. The later worker-committed receipt remains the authoritative application result in Home.
3695

37-
Regression coverage: `TestScheduleCaptureLedgerSnapshot`, `TestBotScheduleToolsProviderDurablePending`, and `TestBotScheduleCaptureOutcome` verify the ledger snapshot, independent read-back and runner rejection boundaries. `TestBotAuthorizedScheduleHTTPAcceptance` also checks pending-only source success despite premature model “Done”, and that the linked applied receipt follows source termination.
96+
Regression coverage: `TestMandatedScheduleControlUsesAuthorizedCapture` exercises create/edit/remove through the production durable issuer in personal/team fixtures, checks canonical source authorization, exact saved payload/revision, source-busy application, denied requests, and mismatched independent read-back without a manual proposal. `TestBotProposalMandatedScheduleSchema` preserves revision, closed-field and payload-union boundaries. `TestScheduleCaptureLedgerSnapshot`, `TestBotScheduleToolsProviderDurablePending`, and `TestBotScheduleCaptureOutcome` verify the ledger snapshot, independent read-back and runner rejection boundaries. `TestBotAuthorizedScheduleHTTPAcceptance` also checks pending-only source success despite premature model “Done”, and that the linked applied receipt follows source termination.
3897

3998
## Scoped schedule discovery
4099

‎docs/architecture/bot-chat-first.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ Interactive delegated children preserve the Bot/run identity and original truste
2424

2525
In personal and team Studio, `BotReviewCard` replaces a successfully answered `ask_user` form with a compact, non-interactive question and “Your answer” pair. It reads the approval's persisted `response`, matching `question_id` to the saved interaction, and accepts only `approved` or `consumed` checkpoints with a valid answer. Option IDs resolve against persisted option labels; yes/no uses Yes/No; custom text remains literal text. Reload and live submission use the same projection. The answered card does not display internal lifecycle values, queue receipts, or “Continue approved action”; answering does not claim that the Bot's work is complete.
2626

27-
The normal decision response must contain the matching saved approval. Explicit **Continue interactive** first succeeds at authorization/continuation, then refreshes scoped approvals and checks approval ID, run ID, action digest, question ID and answer before replacing the form. A click, in-flight selection, missing/foreign response, or failed refresh is not confirmation. Failed answers remain retryable; existing permission/proposal, pause, read-only and reauthorization behavior remains separate. Terminal answer controls retain their existing layout; this is a Studio answered-card presentation change, not a new transport or permission grant.
27+
A pending question submits once through **approve-and-continue**, including when run state says `continuation_required`. The response must contain the matching saved approval: approval ID, run ID, action digest, question ID and answer are checked before replacing the form. A click, in-flight selection, queue receipt, missing/foreign response or failed request is not confirmation. Failed answers preserve input and show the existing actionable error; HTTP 403 does not expose another authorization button or retry through a different endpoint. Duplicate input is disabled while awaiting the response. Expired, revoked and denied questions render only their historical prompt/status and specific inactive explanation, never answer controls or an unsaved “Your answer” claim. Canonical transcript and Details use the same renderer and authoritative approval records. Genuine permission/proposal decisions, plan consent, read-only safeguards and separate explicit paused/progress recovery remain unchanged. Terminal question input likewise submits on the first valid Enter; no public transport or broad permission grant is introduced.
2828

2929
## Minimal creation and durable conversation
3030

@@ -34,7 +34,7 @@ For newly created Bots with an omitted or whitespace-only charter, the generated
3434

3535
`POST /api/studio/bots/{botID}/messages?scope=personal|team` accepts `version`, `idempotency_key`, `instructions`, and supported attachments. Interactive composition selects server-owned `chat_interactive` independently of lifecycle intent. Active/Paused owner turns do not enable or resume recurrence. Control-only composition uses Paused → `conversation`, Active → regular execution with its existing restrictions. Stopped and Deleted reject admission. UI availability is never authority.
3636

37-
Queued/running persisted state drives the existing Chat thinking indicator before tokens and after reload. Waiting questions replace thinking with shared Chat question cards; terminal state clears it. Connectivity is not completion and old replay cannot supersede newer state. Durable `ask_user` uses saved option IDs and supported custom text, never prose parsing; No is input, not permission denial. Lost registry authority requires explicit authenticated continuation preserving the caller ceiling and checkpoint. Retried answers resume the same saved run once. Studio and terminal consume the same contract. The 2026-11-09 owned real-provider journey now passes seventeen checks, including title-first useful work; see the [current evidence boundary](#evidence-boundary). Historical nine-stage receipts are not substituted for that proof, and production external-effect acceptance remains blocked.
37+
Queued/running persisted state drives the existing Chat thinking indicator before tokens and after reload. Waiting questions replace thinking with shared Chat question cards; terminal state clears it. Connectivity is not completion and old replay cannot supersede newer state. Durable `ask_user` uses saved option IDs and supported custom text, never prose parsing; No is input, not permission denial. Question submission continues the originating request under internally revalidated durable mandate or narrowed caller authority; failed authority checks remain errors, not client-side authorization recovery. Retried answers resume the same saved run once. Studio and terminal consume the same contract. The 2026-11-09 owned real-provider journey now passes seventeen checks, including title-first useful work; see the [current evidence boundary](#evidence-boundary). Historical nine-stage receipts are not substituted for that proof, and production external-effect acceptance remains blocked.
3838

3939
Admission atomically commits the run, canonical user event and dispatch outbox. HTTP 202 returns `run`, `home_session_id`, `user_event_id`, and `history_cursor`. An identical retry returns the same receipt; changed payload under the same key conflicts. `presentation=home_interactive` projects interactive turns into ordered durable Home history independently of execution intent. Legacy runs with empty presentation keep their original projection. Clients reconcile canonical events rather than fabricating duplicate echoes. Run traces remain separately inspectable and read-only. These additive JSON fields require no reset, schema regeneration or destructive migration.
4040

0 commit comments

Comments
 (0)