Repository navigation
Conversation
krokoko
left a comment
There was a problem hiding this comment.
Thanks for bringing these three PRs together on top of main, and for the extra agent fixes. That was a lot of work, and the description made the review much easier.
I read the whole change and ran the new Bash path parser on its own with a list of commands. I did not deploy anything or run the test suites, so the IAM points come from reading the constructs.
The seat release part looks good to me. I tried to find an order of events that releases a seat twice or not at all, and could not find one.
I did find problems in the other parts and left a comment on each line. I'm marking this as "changes requested" because of these six:
- Approving one file rule lets a Bash command skip its other approval gates (
policy.py). - The parser misses writes in very common commands, for example any command with a
#comment above the write (bash_writes.py). - A resumed run seems to count its cost twice (
model_retry.py). - The approval writer Lambda has no
dynamodb:GetItemon the approvals table, so the repeat-create fix cannot work once deployed. - The "No change made" reason shows the rule id instead of what was denied, and it can keep part of a secret (
hooks.py). - A task can end as "No change made" while its work is still on another branch or in a stash (
pipeline.py).
The other comments are smaller. I'm happy to talk about which of them belong here and which can be follow-up issues.
Three things that have no single line to comment on:
- Rollout. The need to drain tasks and to deploy the stack and the worker image together is written in the ADRs and in
docs/verification/645-payload-bootstrap.md, but not indocs/guides/DEPLOYMENT_GUIDE.md. The MicroVM image is packaged in a separate step (package-microvm-artifact.sh), so someone who only runs a stack deploy would keep the old image and break MicroVM tasks. The runbook also says its AWS checks are still pending. Could we run them in a test account before merging, or note here that we accept merging without them? - Docs.
docs/design/SECURITY.md(line 44) anddocs/design/CEDAR_HITL_GATES.md(line 1624) still say the worker writes approval rows itself, anddocs/guides/CEDAR_POLICY_GUIDE.md(line 59) still sayswrite_filerules cover Write and Edit only. - Not from this PR, but the new checks rely on it: the session role can still write any attribute of its own task row, including
user_idandconcurrency_slot, and the ECS and AgentCore worker roles can still write the concurrency table. These probably deserve their own issue.
One suggestion: splitting this up would let the finished parts land sooner. The seat change looks ready, the approval writer and the payload bootstrap need small fixes, and most of the open points are in the four agent-side changes.
| for path in bash_written_paths(command): | ||
| write_decision, write_reasons = run( | ||
| "write_file", "Agent::File", "file", {**base_context, "file_path": path} | ||
| ) | ||
| if write_decision == "deny": | ||
| reasons.extend(r for r in write_reasons if r not in reasons) | ||
| return ("deny", reasons) if reasons else None |
There was a problem hiding this comment.
I think this breaks the "nothing turns a deny into an allow" point in the description.
The list now holds the command rules and the file rules together. Further up, at line 1244, the call is allowed as soon as any one of the matched rules has a rule: approval. So once rule:write_env_files is approved for a task, this no longer asks for approval:
git push --force origin main > x.env
On main the same command asks, because a Bash call could not match a file rule. test_a_command_rule_and_a_file_rule_both_count already shows both rule ids arriving in one list.
Could we skip the gate only when every matched rule is approved, and keep asking about the ones that are not? That would also fix the older case where rule:force_push_any covers a force push to main.
| Such a command must not read as writing nothing, so its rough words come back | ||
| unparsed and the caller treats every one as a possible target. | ||
| """ | ||
| lexer = shlex.shlex(command.replace("\n", " ; "), posix=True, punctuation_chars=True) |
There was a problem hiding this comment.
Two things on this line make the parser miss ordinary commands.
shlex.shlex treats # as the start of a comment by default, and the newlines are already replaced by ; here, so the comment runs to the end of the whole command. This returns no paths:
# create the env file
cp .env.example .env
The same happens with a # inside a word, such as ${GITHUB_REF#refs/heads/} or $#. Agents write comment lines all the time, so I think the file rules would be skipped quite often.
A backslash at the end of a line becomes an escaped space followed by ;, which cuts the command in two:
cp config/.env.example \
config/.env
This gives [' ', ' /.env.example'].
Setting lexer.commenters = '' after removing real comments, and joining backslash-newline before the replace, should cover both. _LINE_CONTINUATION_RE in hooks.py already does the second part for the re-clone guard.
| name = os.path.basename(argv[0]) | ||
| args = argv[1:] | ||
| if name in _SHELLS and "-c" in args: | ||
| idx = args.index("-c") | ||
| script = args[idx + 1] if idx + 1 < len(args) else "" | ||
| return _written(script, depth + 1) if depth < _MAX_SHELL_DEPTH else [] |
There was a problem hiding this comment.
Only the first word of each command is looked at, so a write is missed when something else comes first. Each of these returns no paths, although the shell does write the file:
if [ ! -f .env ]; then cp .env.example .env; fi
for h in pre-commit; do cp hooks/$h .git/hooks/pre-commit; done
(cd sub && make); cp a .env
timeout 30 cp /tmp/a .env
bash -lc 'echo A=1 > .env'
The first two need then, do, else, { and ! to be skipped like the prefix commands. In the third, ); arrives as one token and _segments does not split it. In the last one, -c is only found when it is a word of its own, so -lc and -ec are not read.
cd has a similar gap at line 252. cd -- .git && echo x > config and pushd .git && echo x > config both give ['config'], which matches neither .git rule. A cd made in an earlier Bash call is not known here either.
I know the docstring calls this a heuristic. My worry is that these are everyday forms, and the description says cd and bash -c are followed.
| if not exact: | ||
| return found + tokens |
There was a problem hiding this comment.
This fallback can also block harmless commands. When shlex cannot split the command, every word is checked as a path, at the hard tier too. For example:
git commit -m $'docs: explain .git/hooks/pre-commit; don\'t skip it'
would be hard-denied by write_git_internals, although it only writes a commit message. A heredoc whose end marker has a dash in it (<<'END-OF-DOC') has its body read as commands, so a README that mentions cp scripts/pre-commit .git/hooks/pre-commit would be denied as well.
With the new prompt rule telling the agent to stop when a control blocks it, a false deny like this can end the task. Handling $'...' before shlex, and accepting any word as a heredoc marker, would remove the common cases.
| Spend and turns add up; status, error and text are the last call's. | ||
| """ | ||
| merged = then.model_copy(deep=True) | ||
| merged.cost_usd = (first.cost_usd or 0.0) + (then.cost_usd or 0.0) |
There was a problem hiding this comment.
I think this counts the earlier attempts twice. The CLI bundled with claude-agent-sdk==0.2.179 describes the cost on a result like this:
each result carries the running total so far, so read the latest result rather than summing across results. [...] a resumed or forked session continues from the total its transcript saved, when it has one (so the first result already carries the earlier turns; [...])
Example: the first attempt spends $2.60 and fails, the resumed one spends $0.40 more and reports $3.00. The merge stores $5.60. That number goes to the task record and the budget rollup, and _remaining_caps uses it for the next retry, so a second retry can be refused while there is budget left.
I have not checked this with a live resume, so it would be good to confirm with one. If it holds, keeping the later value when the call resumed a session should be enough. The fake in test_model_retry.py reports the cost per call, so the tests would not catch it.
| if needs_input or overall_status != "success" or pr_url or changed: | ||
| return "" | ||
| text = agent_result.result_text or "" | ||
| return declined_no_change_reason( | ||
| agent_result.denied_approvals, text | ||
| ) or blocked_no_change_reason(agent_result.platform_blocks, text) |
There was a problem hiding this comment.
As written, any denial or hard deny recorded at any time in the run is enough, as long as the clone is clean at the end. Nothing checks that the agent stopped because of it. rm_slash alone fires on any rm -rf /some/absolute/path, so quite a few runs will carry a record.
Two cases worry me. A run that gave up for another reason now completes instead of failing. And in an orchestration, isSuccess in orchestration-reconcile.ts only looks at the status and build_passed, so a child that ends this way releases the tasks that depend on it, and they start from the default branch without its change.
Would it be possible to tie this to the stop itself, for example only when the denied call was the last thing the agent tried? For orchestration children it may be simpler to keep the old FAILED result.
| suffix = "amazonaws.com.cn" if region.startswith("cn-") else "amazonaws.com" | ||
| host = f"s3.{region}.{suffix}" | ||
| valid = ( | ||
| parsed.netloc == f"{bucket}.{host}" and parsed.path == f"/{task_id}/payload.json" | ||
| ) or (parsed.netloc == host and parsed.path == f"/{bucket}/{task_id}/payload.json") |
There was a problem hiding this comment.
The region here is taken from the URL itself and is not compared with anything the worker knows. Bucket names are only unique inside one AWS partition, so a URL for a bucket with the same name in GovCloud or China passes this check, as long as it uses the same task id.
It needs someone who can hand the worker a forged reference, so it is not easy to reach. But that is the case this check is for, and the fix is small: compare the region with the worker's own AWS_REGION (or put it in the manifest), and only allow the .com.cn suffix when that region is a cn- one.
| ...(blueprintConfig.system_prompt_overrides ? [{ name: 'SYSTEM_PROMPT_OVERRIDES', value: blueprintConfig.system_prompt_overrides }] : []), | ||
| { name: 'CLAUDE_CODE_USE_BEDROCK', value: '1' }, | ||
| // Prefer the S3 pointer; fall back to the inline payload when no bucket is | ||
| // configured (keeps small-payload / AgentCore-only deployments working with | ||
| // no behavior change). | ||
| ...(payloadS3Uri | ||
| ? [{ name: 'AGENT_PAYLOAD_S3_URI', value: payloadS3Uri }] | ||
| : [{ name: 'AGENT_PAYLOAD', value: payloadJson }]), | ||
| { name: 'AGENT_PAYLOAD_REF', value: JSON.stringify(reference) }, |
There was a problem hiding this comment.
AGENT_PAYLOAD_REF holds a presigned URL with a session token, so it is roughly a couple of kilobytes. It shares the 8192-byte limit with SYSTEM_PROMPT_OVERRIDES on line 173. As far as I can see nothing in agent/ reads that variable, since the agent takes the value from the payload.
A blueprint with a few kilobytes of prompt overrides (around 5 KB by my estimate) would now fail every ECS start with PAYLOAD_BOOTSTRAP_TOO_LARGE, and only after payload.json and launch.json were written. Dropping the env entry on line 173 would avoid that.
| - **Platform controls**: When a platform control blocks you (a policy denial, an \ | ||
| approval that was denied or timed out, a push refused for permissions or protected \ | ||
| paths such as `.github/`, a failing gate you aren't allowed to change), stop and say \ | ||
| so in your reply. Never work around it: no renaming or moving files to dodge a check, \ | ||
| no writing the same change through another tool or path, no disabling or skipping \ | ||
| checks or hooks. |
There was a problem hiding this comment.
A few things about this rule.
It tells the agent to stop when an approval times out, but the delivery gate only knows about denied approvals and Cedar denies. An agent that follows the rule after a timeout, and has changed nothing, still ends as FAILED with deliverable=lost. This matters more now because cp .env.example .env needs approval, and a write_path: or tool_group:file_write pre-approval does not cover a Bash write (ApprovalAllowlist.matches only checks those for Write and Edit).
It also pulls against text that did not change. The deny message in hooks.py says "Find an alternative task strategy or report back", and step 6 in new_task.py says a PR must always be created.
And as far as I can tell the reply this rule asks for is only shown when nothing changed. If the agent had already edited files, a normal PR is opened and the explanation is not shown anywhere.
Maybe the rule could say: do not retry or disguise the blocked action, carry on with the work the control does not cover, and if the task cannot be finished without it, push what exists and say so.
| /** | ||
| * Why a coding task completed without changing anything on purpose: a person | ||
| * denied what it needed, or a platform control blocked it ("No change made: …"). | ||
| * Shown instead of "Task completed"; absent for every other run. | ||
| */ | ||
| readonly no_change_reason?: string; |
There was a problem hiding this comment.
This field is only read by the Linear final comment in fanout-task-events.ts. Slack, the GitHub comment, Jira, the API, the CLI and the web console do not know about it, so there a task that ended this way looks like a plain success with no PR and no reason. A task started from a Linear comment gets the "Updated." reply.
Before this PR those tasks showed as failed with an explanation, so on those channels the user now learns less. Adding the field to TaskDetail and the other renderers, or limiting the sentence in the user guide to Linear, would make it consistent.
…val records (#1000) Workers wrote PENDING approval rows directly with task-scoped session credentials that live alongside the repository's code, so malicious or prompt-injected repo code could write any approval record for its task. - ApprovalRequestService (nested stack): IAM-authenticated API Gateway + request-approval Lambda. POST /tasks/{task_id} accepts only "create" (PENDING request + RUNNING -> AWAITING_APPROVAL, one transaction) and "timeout" (PENDING -> TIMED_OUT, conditioned on the task still awaiting that request). It validates a fixed field set, ownership and deadline_epoch, and sets the row TTL itself. - The session role may invoke only /tasks/${aws:PrincipalTag/task_id}; the approvals table moves to a task-scoped read-only grant (listing it as read/write as well fails synth). - Every backend gets APPROVAL_REQUESTS_API_URL: AgentCore runtime env, ECS task env (reserved key), MicroVM platform config (new required contract key approval_requests_api_url). - Agent: approval_requests.py signs requests (SigV4, no redirects, endpoint validated) and never sends retention; task_state routes create/timeout through it and refuses human statuses; hooks carry deadline_epoch. - ADR-025 records the decision. Also in this change: the orchestrator fixtures carry the required approvalRequestsApiUrl; the approval-requests stack's state-bearing resources are recorded in legacy-state-ids.json; the DynamoDB Local approval suite is opt-in; the MicroVM network-extraction fixture leaves out the vault; the AWAITING_APPROVAL transition keeps status_created_at; the emulator tier follows the trusted writer. Rebased onto main after the Lambda MicroVM approval lifecycle (#904): the hook keeps main's shared approval_deadline_epoch (the writer cross-checks the same created_at + timeout_s), the orchestrator passes both the MicroVM approvals table and APPROVAL_REQUESTS_API_URL, and the MicroVM checkpoint only condition-checks approval rows, which the read-only session role allows.
Workers no longer read a shared payload bucket or receive deployment identifiers baked into images. - The coordinator publishes an IAM-readable deployment manifest (bootstrap/<sha>.json) and a per-task payload, and hands the worker a small launch reference with a short-lived signed one-object URL for its own payload.json. MicroVM sends it as runHookPayload (always under the 4 KB cap); ECS sends it as AGENT_PAYLOAD_REF, consumed by load_ecs_payload() before the pipeline imports. - Worker credentials get GetObject on bootstrap/* only; other object reads and listing are denied, so a task cannot read another task's payload (#700). The coordinator signs reads and deletes payload.json/launch.json at finalize; lifecycle reaps leftovers. - Signed URLs are redacted from MicroVM error messages and logs. - Old unsigned envelopes (inline hook, S3 pointer, AGENT_PAYLOAD, AGENT_PAYLOAD_S3_URI) are rejected: deploy the coordinator and images together with in-flight tasks drained (docs/verification/645-payload-bootstrap.md). - The orchestrator role now overflows its inline policy; its overflow policy gets the same documented cdk-nag suppression as the runtime and Linear webhook roles. Extracted from the #904 working branch onto main's flat MicroVM layout, without start receipts or P3 lifecycle code. Also in this change: every ARN-shaped platform-config field must be listed in the contract's arn_keys (#817 item 3, enforced both ways by the sync check); the new lint, dead-code and typecheck gates pass; dead verification links are dropped. Rebased onto main after the Lambda MicroVM approval lifecycle (#904): - the v2 launch reference is produced in deliverRunHookPayload, after the start receipt is claimed, so a replayed start rewrites the same objects; the v1 inline/S3-pointer envelope and its tests are gone - terminate-failure logs keep main's identity-only fields (no error text, so no signed URL can reach a log) - the MicroVM execution role keeps main's description: the least-privilege bootstrap cannot update a role description - the orchestrator overflow suppression keeps main's scoped appliesTo list - vulture (newer on main) also allowlists the override's `req` parameter - tests follow the nested MicroVM layout, and the stack counts include the trusted approval writer's nested stack and Lambda
…up progress #1000 adds the ApprovalRequests nested stack at the top level of AgentStack; without a component it would show as a platform helper.
The writer commits the PENDING approval row and the task's move to AWAITING_APPROVAL in one transaction. When the worker lost the response to a committed create, a repeat with the same request id was cancelled, because the row exists and the task is no longer RUNNING, so the worker could never learn that the task was waiting on it. A cancelled create now reads the row and the task with ConsistentRead and returns the first create's success when the row is for the same task, user and tool input and the task still awaits that request id. Any other state stays a failure; the transaction conditions are unchanged.
…task waiting A create whose response was lost (timeout, connection error, 5xx) denied the tool call and returned while the writer might have committed the request, so the task stayed AWAITING_APPROVAL with a PENDING row and the agent carried on. The worker now repeats such a create up to two more times with the same request id, which the writer answers with the first create's success. A rejected or cancelled create is not repeated. A create that stays unconfirmed gets the timeout and resume that follow an unanswered gate, both conditioned on the task awaiting that request, and the call is denied as before.
…s a repeat from A repeated create reads the approval row with GetItem to report the first create's success, but the writer's role allowed only PutItem and UpdateItem on the approvals table. Every repeat would have failed with AccessDenied and reached the worker as an unanswered create. The role now has GetItem on that table, and the construct test pins the exact actions on each table.
… sends The writer's tests sent timeout_s 0 with no deadline_epoch, a shape the hook never builds, so no test reached the deadline check. The CDK unit tests, the DynamoDB Local suite and the worker's broker tests now share one row in contracts/approval-request-row.json, with a 300 s timeout and its deadline_epoch. A hook test checks that the gate builds exactly those fields, and the writer rejects a deadline that is not created_at plus the timeout, a missing one, and a timeout above the maximum.
The writer derives the gate deadline and the row's TTL from the worker's created_at, but only checked it with Date.parse. A worker could send a created_at in 2099 and keep the row for decades, or +275760-09-13, which makes the owner's pending list throw. The writer now accepts only the hook's YYYY-MM-DDTHH:MM:SSZ form, a real calendar date, and a time within 300 s of its own clock (SigV4 already refuses a larger skew). The timeout_s 0 case is gone: the hook always sends at least the minimum timeout with its deadline, so the TTL is always the deadline plus the 120 s cleanup margin.
The worker took the Region of the presigned payload URL from the URL itself. Bucket names are unique only inside one partition, so a reference to a bucket of the same name in GovCloud or China passed the check. The URL's Region must now equal the worker's AWS_REGION (or AWS_DEFAULT_REGION), and only a cn- Region gets the amazonaws.com.cn host. A worker without a Region reads no payload.
The ECS start put the Blueprint's system_prompt_overrides in the SYSTEM_PROMPT_OVERRIDES container variable, which nothing in agent/ reads: the agent takes the overrides from the payload. That variable shares the 8192-byte container-override limit with AGENT_PAYLOAD_REF, whose presigned URL is about 2 KB, so about 6 KB of overrides failed every ECS start with PAYLOAD_BOOTSTRAP_TOO_LARGE. The variable is gone.
…o writes approval rows The deployment guide now says to drain tasks and deploy the stack and the worker images together, and that the MicroVM image is packaged in its own step (package-microvm-artifact.sh), so a stack deploy alone keeps the old image. It also says the payload bootstrap runbook's AWS checks have not been run on a deployed stack. SECURITY.md and CEDAR_HITL_GATES.md still said the worker writes approval rows with its own credentials. They now say the session role only reads the approvals table and the trusted approval writer creates requests and records timeouts.
6a0d6ea to
5034303
Compare
Workers can no longer write approval records, and ECS and Lambda MicroVM workers read their task payload through a signed, task-scoped reference. The seat release and the agent-side changes moved to their own pull requests, as the review asked.
Area
cdk: infrastructure, handlers, constructsagent: Python runtime and Docker imagecli:bgagentclientdocs: guides and design sources (docs/guides/,docs/design/)tooling: rootmise.toml, scripts, CI workflowsRelated
Changes
Trusted approval writer (#1000, ADR-025)
The session role is read-only on the approvals table. A worker asks an IAM-authenticated API, which it may call only on its own task's path, to create a PENDING request or to mark one TIMED_OUT. The API cannot record a human decision. The writer sets the row's retention itself.
A create whose response was lost no longer leaves the task waiting. The writer answers a repeat of a committed create with the first create's success, but only when the row is for the same task, user and tool input and the task still waits on that request. The worker repeats a create that got no answer or a 5xx up to two more times with the same request id. If it still has no answer, it marks the request TIMED_OUT, resumes the task and denies the call.
bgagentsetup progress shows the newApprovalRequestsstack under Orchestration.Payload bootstrap v2 (#1002)
ECS and Lambda MicroVM workers get a short-lived presigned URL for their own task's payload, and an IAM-authenticated deployment manifest whose digest is its key. The worker checks that the payload belongs to its task and that its configuration equals the manifest. The image accepts only v2.
Changes from the review
dynamodb:GetItemon the approvals table. Without it every repeated create failed with AccessDenied. The construct test asserts the exact actions on each table.created_atonly in theYYYY-MM-DDTHH:MM:SSZform, as a real calendar date, and within 300 s of its own clock.timeout_smust be between the approval timeout minimum and maximum, so thetimeout_s0 case is gone, and the TTL is always the deadline plus 120 s.test_approval_requests.pyuse one shared row,contracts/approval-request-row.json, with a 300 s timeout and itsdeadline_epoch. A hook test checks that the gate builds exactly those fields.AWS_REGION. Only acn-Region gets theamazonaws.com.cnhost. A worker without a Region reads no payload.SYSTEM_PROMPT_OVERRIDES. Nothing inagent/read it; the agent takes the overrides from the payload. About 6 KB of overrides plus the presigned reference passed the 8192-byte container-override limit.DEPLOYMENT_GUIDE.mdsays to drain tasks and to deploy the stack and the worker images together, and thatpackage-microvm-artifact.shpackages the MicroVM image in its own step.SECURITY.mdandCEDAR_HITL_GATES.mdsay that the writer, not the worker, creates approval rows.Validation
mise run lintandmise run drift-preventionpass.mise run //agent:quality): 3,323 passed, 11 skipped (the DynamoDB Local tests are opt-in).request-approval-local.test.ts): 11 passed.main. gitleaks finds no leaks.Not deployed. The AWS checks of the payload bootstrap runbook (
docs/verification/645-payload-bootstrap.md) have not been run on a deployed stack yet. A deploy must drain in-flight tasks and ship the stack and the worker images together: older images write approval rows directly and cannot read a v2 payload reference.Acknowledgment
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.